• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 #include "builtin.h"
3 #include "perf-sys.h"
4 
5 #include "util/cpumap.h"
6 #include "util/evlist.h"
7 #include "util/evsel.h"
8 #include "util/evsel_fprintf.h"
9 #include "util/mutex.h"
10 #include "util/symbol.h"
11 #include "util/thread.h"
12 #include "util/header.h"
13 #include "util/session.h"
14 #include "util/tool.h"
15 #include "util/cloexec.h"
16 #include "util/thread_map.h"
17 #include "util/color.h"
18 #include "util/stat.h"
19 #include "util/string2.h"
20 #include "util/callchain.h"
21 #include "util/time-utils.h"
22 
23 #include <subcmd/pager.h>
24 #include <subcmd/parse-options.h>
25 #include "util/trace-event.h"
26 
27 #include "util/debug.h"
28 #include "util/event.h"
29 #include "util/util.h"
30 
31 #include <linux/kernel.h>
32 #include <linux/log2.h>
33 #include <linux/zalloc.h>
34 #include <sys/prctl.h>
35 #include <sys/resource.h>
36 #include <inttypes.h>
37 
38 #include <errno.h>
39 #include <semaphore.h>
40 #include <pthread.h>
41 #include <math.h>
42 #include <api/fs/fs.h>
43 #include <perf/cpumap.h>
44 #include <linux/time64.h>
45 #include <linux/err.h>
46 
47 #include <linux/ctype.h>
48 
49 #define PR_SET_NAME		15               /* Set process name */
50 #define MAX_CPUS		4096
51 #define COMM_LEN		20
52 #define SYM_LEN			129
53 #define MAX_PID			1024000
54 #define MAX_PRIO		140
55 
56 static const char *cpu_list;
57 static DECLARE_BITMAP(cpu_bitmap, MAX_NR_CPUS);
58 
59 struct sched_atom;
60 
61 struct task_desc {
62 	unsigned long		nr;
63 	unsigned long		pid;
64 	char			comm[COMM_LEN];
65 
66 	unsigned long		nr_events;
67 	unsigned long		curr_event;
68 	struct sched_atom	**atoms;
69 
70 	pthread_t		thread;
71 	sem_t			sleep_sem;
72 
73 	sem_t			ready_for_work;
74 	sem_t			work_done_sem;
75 
76 	u64			cpu_usage;
77 };
78 
79 enum sched_event_type {
80 	SCHED_EVENT_RUN,
81 	SCHED_EVENT_SLEEP,
82 	SCHED_EVENT_WAKEUP,
83 	SCHED_EVENT_MIGRATION,
84 };
85 
86 struct sched_atom {
87 	enum sched_event_type	type;
88 	int			specific_wait;
89 	u64			timestamp;
90 	u64			duration;
91 	unsigned long		nr;
92 	sem_t			*wait_sem;
93 	struct task_desc	*wakee;
94 };
95 
96 enum thread_state {
97 	THREAD_SLEEPING = 0,
98 	THREAD_WAIT_CPU,
99 	THREAD_SCHED_IN,
100 	THREAD_IGNORE
101 };
102 
103 struct work_atom {
104 	struct list_head	list;
105 	enum thread_state	state;
106 	u64			sched_out_time;
107 	u64			wake_up_time;
108 	u64			sched_in_time;
109 	u64			runtime;
110 };
111 
112 struct work_atoms {
113 	struct list_head	work_list;
114 	struct thread		*thread;
115 	struct rb_node		node;
116 	u64			max_lat;
117 	u64			max_lat_start;
118 	u64			max_lat_end;
119 	u64			total_lat;
120 	u64			nb_atoms;
121 	u64			total_runtime;
122 	int			num_merged;
123 };
124 
125 typedef int (*sort_fn_t)(struct work_atoms *, struct work_atoms *);
126 
127 struct perf_sched;
128 
129 struct trace_sched_handler {
130 	int (*switch_event)(struct perf_sched *sched, struct evsel *evsel,
131 			    struct perf_sample *sample, struct machine *machine);
132 
133 	int (*runtime_event)(struct perf_sched *sched, struct evsel *evsel,
134 			     struct perf_sample *sample, struct machine *machine);
135 
136 	int (*wakeup_event)(struct perf_sched *sched, struct evsel *evsel,
137 			    struct perf_sample *sample, struct machine *machine);
138 
139 	/* PERF_RECORD_FORK event, not sched_process_fork tracepoint */
140 	int (*fork_event)(struct perf_sched *sched, union perf_event *event,
141 			  struct machine *machine);
142 
143 	int (*migrate_task_event)(struct perf_sched *sched,
144 				  struct evsel *evsel,
145 				  struct perf_sample *sample,
146 				  struct machine *machine);
147 };
148 
149 #define COLOR_PIDS PERF_COLOR_BLUE
150 #define COLOR_CPUS PERF_COLOR_BG_RED
151 
152 struct perf_sched_map {
153 	DECLARE_BITMAP(comp_cpus_mask, MAX_CPUS);
154 	struct perf_cpu		*comp_cpus;
155 	bool			 comp;
156 	struct perf_thread_map *color_pids;
157 	const char		*color_pids_str;
158 	struct perf_cpu_map	*color_cpus;
159 	const char		*color_cpus_str;
160 	const char		*task_name;
161 	struct strlist		*task_names;
162 	bool			fuzzy;
163 	struct perf_cpu_map	*cpus;
164 	const char		*cpus_str;
165 };
166 
167 struct perf_sched {
168 	struct perf_tool tool;
169 	const char	 *sort_order;
170 	unsigned long	 nr_tasks;
171 	struct task_desc **pid_to_task;
172 	struct task_desc **tasks;
173 	const struct trace_sched_handler *tp_handler;
174 	struct mutex	 start_work_mutex;
175 	struct mutex	 work_done_wait_mutex;
176 	int		 profile_cpu;
177 /*
178  * Track the current task - that way we can know whether there's any
179  * weird events, such as a task being switched away that is not current.
180  */
181 	struct perf_cpu	 max_cpu;
182 	u32		 *curr_pid;
183 	struct thread	 **curr_thread;
184 	struct thread	 **curr_out_thread;
185 	char		 next_shortname1;
186 	char		 next_shortname2;
187 	unsigned int	 replay_repeat;
188 	unsigned long	 nr_run_events;
189 	unsigned long	 nr_sleep_events;
190 	unsigned long	 nr_wakeup_events;
191 	unsigned long	 nr_sleep_corrections;
192 	unsigned long	 nr_run_events_optimized;
193 	unsigned long	 targetless_wakeups;
194 	unsigned long	 multitarget_wakeups;
195 	unsigned long	 nr_runs;
196 	unsigned long	 nr_timestamps;
197 	unsigned long	 nr_unordered_timestamps;
198 	unsigned long	 nr_context_switch_bugs;
199 	unsigned long	 nr_events;
200 	unsigned long	 nr_lost_chunks;
201 	unsigned long	 nr_lost_events;
202 	u64		 run_measurement_overhead;
203 	u64		 sleep_measurement_overhead;
204 	u64		 start_time;
205 	u64		 cpu_usage;
206 	u64		 runavg_cpu_usage;
207 	u64		 parent_cpu_usage;
208 	u64		 runavg_parent_cpu_usage;
209 	u64		 sum_runtime;
210 	u64		 sum_fluct;
211 	u64		 run_avg;
212 	u64		 all_runtime;
213 	u64		 all_count;
214 	u64		 *cpu_last_switched;
215 	struct rb_root_cached atom_root, sorted_atom_root, merged_atom_root;
216 	struct list_head sort_list, cmp_pid;
217 	bool force;
218 	bool skip_merge;
219 	struct perf_sched_map map;
220 
221 	/* options for timehist command */
222 	bool		summary;
223 	bool		summary_only;
224 	bool		idle_hist;
225 	bool		show_callchain;
226 	unsigned int	max_stack;
227 	bool		show_cpu_visual;
228 	bool		show_wakeups;
229 	bool		show_next;
230 	bool		show_migrations;
231 	bool		show_state;
232 	bool		show_prio;
233 	u64		skipped_samples;
234 	const char	*time_str;
235 	struct perf_time_interval ptime;
236 	struct perf_time_interval hist_time;
237 	volatile bool   thread_funcs_exit;
238 	const char	*prio_str;
239 	DECLARE_BITMAP(prio_bitmap, MAX_PRIO);
240 };
241 
242 /* per thread run time data */
243 struct thread_runtime {
244 	u64 last_time;      /* time of previous sched in/out event */
245 	u64 dt_run;         /* run time */
246 	u64 dt_sleep;       /* time between CPU access by sleep (off cpu) */
247 	u64 dt_iowait;      /* time between CPU access by iowait (off cpu) */
248 	u64 dt_preempt;     /* time between CPU access by preempt (off cpu) */
249 	u64 dt_delay;       /* time between wakeup and sched-in */
250 	u64 ready_to_run;   /* time of wakeup */
251 
252 	struct stats run_stats;
253 	u64 total_run_time;
254 	u64 total_sleep_time;
255 	u64 total_iowait_time;
256 	u64 total_preempt_time;
257 	u64 total_delay_time;
258 
259 	char last_state;
260 
261 	char shortname[3];
262 	bool comm_changed;
263 
264 	u64 migrations;
265 
266 	int prio;
267 };
268 
269 /* per event run time data */
270 struct evsel_runtime {
271 	u64 *last_time; /* time this event was last seen per cpu */
272 	u32 ncpu;       /* highest cpu slot allocated */
273 };
274 
275 /* per cpu idle time data */
276 struct idle_thread_runtime {
277 	struct thread_runtime	tr;
278 	struct thread		*last_thread;
279 	struct rb_root_cached	sorted_root;
280 	struct callchain_root	callchain;
281 	struct callchain_cursor	cursor;
282 };
283 
284 /* track idle times per cpu */
285 static struct thread **idle_threads;
286 static int idle_max_cpu;
287 static char idle_comm[] = "<idle>";
288 
get_nsecs(void)289 static u64 get_nsecs(void)
290 {
291 	struct timespec ts;
292 
293 	clock_gettime(CLOCK_MONOTONIC, &ts);
294 
295 	return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
296 }
297 
burn_nsecs(struct perf_sched * sched,u64 nsecs)298 static void burn_nsecs(struct perf_sched *sched, u64 nsecs)
299 {
300 	u64 T0 = get_nsecs(), T1;
301 
302 	do {
303 		T1 = get_nsecs();
304 	} while (T1 + sched->run_measurement_overhead < T0 + nsecs);
305 }
306 
sleep_nsecs(u64 nsecs)307 static void sleep_nsecs(u64 nsecs)
308 {
309 	struct timespec ts;
310 
311 	ts.tv_nsec = nsecs % 999999999;
312 	ts.tv_sec = nsecs / 999999999;
313 
314 	nanosleep(&ts, NULL);
315 }
316 
calibrate_run_measurement_overhead(struct perf_sched * sched)317 static void calibrate_run_measurement_overhead(struct perf_sched *sched)
318 {
319 	u64 T0, T1, delta, min_delta = NSEC_PER_SEC;
320 	int i;
321 
322 	for (i = 0; i < 10; i++) {
323 		T0 = get_nsecs();
324 		burn_nsecs(sched, 0);
325 		T1 = get_nsecs();
326 		delta = T1-T0;
327 		min_delta = min(min_delta, delta);
328 	}
329 	sched->run_measurement_overhead = min_delta;
330 
331 	printf("run measurement overhead: %" PRIu64 " nsecs\n", min_delta);
332 }
333 
calibrate_sleep_measurement_overhead(struct perf_sched * sched)334 static void calibrate_sleep_measurement_overhead(struct perf_sched *sched)
335 {
336 	u64 T0, T1, delta, min_delta = NSEC_PER_SEC;
337 	int i;
338 
339 	for (i = 0; i < 10; i++) {
340 		T0 = get_nsecs();
341 		sleep_nsecs(10000);
342 		T1 = get_nsecs();
343 		delta = T1-T0;
344 		min_delta = min(min_delta, delta);
345 	}
346 	min_delta -= 10000;
347 	sched->sleep_measurement_overhead = min_delta;
348 
349 	printf("sleep measurement overhead: %" PRIu64 " nsecs\n", min_delta);
350 }
351 
352 static struct sched_atom *
get_new_event(struct task_desc * task,u64 timestamp)353 get_new_event(struct task_desc *task, u64 timestamp)
354 {
355 	struct sched_atom *event = zalloc(sizeof(*event));
356 	unsigned long idx = task->nr_events;
357 	size_t size;
358 
359 	event->timestamp = timestamp;
360 	event->nr = idx;
361 
362 	task->nr_events++;
363 	size = sizeof(struct sched_atom *) * task->nr_events;
364 	task->atoms = realloc(task->atoms, size);
365 	BUG_ON(!task->atoms);
366 
367 	task->atoms[idx] = event;
368 
369 	return event;
370 }
371 
last_event(struct task_desc * task)372 static struct sched_atom *last_event(struct task_desc *task)
373 {
374 	if (!task->nr_events)
375 		return NULL;
376 
377 	return task->atoms[task->nr_events - 1];
378 }
379 
add_sched_event_run(struct perf_sched * sched,struct task_desc * task,u64 timestamp,u64 duration)380 static void add_sched_event_run(struct perf_sched *sched, struct task_desc *task,
381 				u64 timestamp, u64 duration)
382 {
383 	struct sched_atom *event, *curr_event = last_event(task);
384 
385 	/*
386 	 * optimize an existing RUN event by merging this one
387 	 * to it:
388 	 */
389 	if (curr_event && curr_event->type == SCHED_EVENT_RUN) {
390 		sched->nr_run_events_optimized++;
391 		curr_event->duration += duration;
392 		return;
393 	}
394 
395 	event = get_new_event(task, timestamp);
396 
397 	event->type = SCHED_EVENT_RUN;
398 	event->duration = duration;
399 
400 	sched->nr_run_events++;
401 }
402 
add_sched_event_wakeup(struct perf_sched * sched,struct task_desc * task,u64 timestamp,struct task_desc * wakee)403 static void add_sched_event_wakeup(struct perf_sched *sched, struct task_desc *task,
404 				   u64 timestamp, struct task_desc *wakee)
405 {
406 	struct sched_atom *event, *wakee_event;
407 
408 	event = get_new_event(task, timestamp);
409 	event->type = SCHED_EVENT_WAKEUP;
410 	event->wakee = wakee;
411 
412 	wakee_event = last_event(wakee);
413 	if (!wakee_event || wakee_event->type != SCHED_EVENT_SLEEP) {
414 		sched->targetless_wakeups++;
415 		return;
416 	}
417 	if (wakee_event->wait_sem) {
418 		sched->multitarget_wakeups++;
419 		return;
420 	}
421 
422 	wakee_event->wait_sem = zalloc(sizeof(*wakee_event->wait_sem));
423 	sem_init(wakee_event->wait_sem, 0, 0);
424 	wakee_event->specific_wait = 1;
425 	event->wait_sem = wakee_event->wait_sem;
426 
427 	sched->nr_wakeup_events++;
428 }
429 
add_sched_event_sleep(struct perf_sched * sched,struct task_desc * task,u64 timestamp,const char task_state __maybe_unused)430 static void add_sched_event_sleep(struct perf_sched *sched, struct task_desc *task,
431 				  u64 timestamp, const char task_state __maybe_unused)
432 {
433 	struct sched_atom *event = get_new_event(task, timestamp);
434 
435 	event->type = SCHED_EVENT_SLEEP;
436 
437 	sched->nr_sleep_events++;
438 }
439 
register_pid(struct perf_sched * sched,unsigned long pid,const char * comm)440 static struct task_desc *register_pid(struct perf_sched *sched,
441 				      unsigned long pid, const char *comm)
442 {
443 	struct task_desc *task;
444 	static int pid_max;
445 
446 	if (sched->pid_to_task == NULL) {
447 		if (sysctl__read_int("kernel/pid_max", &pid_max) < 0)
448 			pid_max = MAX_PID;
449 		BUG_ON((sched->pid_to_task = calloc(pid_max, sizeof(struct task_desc *))) == NULL);
450 	}
451 	if (pid >= (unsigned long)pid_max) {
452 		BUG_ON((sched->pid_to_task = realloc(sched->pid_to_task, (pid + 1) *
453 			sizeof(struct task_desc *))) == NULL);
454 		while (pid >= (unsigned long)pid_max)
455 			sched->pid_to_task[pid_max++] = NULL;
456 	}
457 
458 	task = sched->pid_to_task[pid];
459 
460 	if (task)
461 		return task;
462 
463 	task = zalloc(sizeof(*task));
464 	task->pid = pid;
465 	task->nr = sched->nr_tasks;
466 	strcpy(task->comm, comm);
467 	/*
468 	 * every task starts in sleeping state - this gets ignored
469 	 * if there's no wakeup pointing to this sleep state:
470 	 */
471 	add_sched_event_sleep(sched, task, 0, 0);
472 
473 	sched->pid_to_task[pid] = task;
474 	sched->nr_tasks++;
475 	sched->tasks = realloc(sched->tasks, sched->nr_tasks * sizeof(struct task_desc *));
476 	BUG_ON(!sched->tasks);
477 	sched->tasks[task->nr] = task;
478 
479 	if (verbose > 0)
480 		printf("registered task #%ld, PID %ld (%s)\n", sched->nr_tasks, pid, comm);
481 
482 	return task;
483 }
484 
485 
print_task_traces(struct perf_sched * sched)486 static void print_task_traces(struct perf_sched *sched)
487 {
488 	struct task_desc *task;
489 	unsigned long i;
490 
491 	for (i = 0; i < sched->nr_tasks; i++) {
492 		task = sched->tasks[i];
493 		printf("task %6ld (%20s:%10ld), nr_events: %ld\n",
494 			task->nr, task->comm, task->pid, task->nr_events);
495 	}
496 }
497 
add_cross_task_wakeups(struct perf_sched * sched)498 static void add_cross_task_wakeups(struct perf_sched *sched)
499 {
500 	struct task_desc *task1, *task2;
501 	unsigned long i, j;
502 
503 	for (i = 0; i < sched->nr_tasks; i++) {
504 		task1 = sched->tasks[i];
505 		j = i + 1;
506 		if (j == sched->nr_tasks)
507 			j = 0;
508 		task2 = sched->tasks[j];
509 		add_sched_event_wakeup(sched, task1, 0, task2);
510 	}
511 }
512 
perf_sched__process_event(struct perf_sched * sched,struct sched_atom * atom)513 static void perf_sched__process_event(struct perf_sched *sched,
514 				      struct sched_atom *atom)
515 {
516 	int ret = 0;
517 
518 	switch (atom->type) {
519 		case SCHED_EVENT_RUN:
520 			burn_nsecs(sched, atom->duration);
521 			break;
522 		case SCHED_EVENT_SLEEP:
523 			if (atom->wait_sem)
524 				ret = sem_wait(atom->wait_sem);
525 			BUG_ON(ret);
526 			break;
527 		case SCHED_EVENT_WAKEUP:
528 			if (atom->wait_sem)
529 				ret = sem_post(atom->wait_sem);
530 			BUG_ON(ret);
531 			break;
532 		case SCHED_EVENT_MIGRATION:
533 			break;
534 		default:
535 			BUG_ON(1);
536 	}
537 }
538 
get_cpu_usage_nsec_parent(void)539 static u64 get_cpu_usage_nsec_parent(void)
540 {
541 	struct rusage ru;
542 	u64 sum;
543 	int err;
544 
545 	err = getrusage(RUSAGE_SELF, &ru);
546 	BUG_ON(err);
547 
548 	sum =  ru.ru_utime.tv_sec * NSEC_PER_SEC + ru.ru_utime.tv_usec * NSEC_PER_USEC;
549 	sum += ru.ru_stime.tv_sec * NSEC_PER_SEC + ru.ru_stime.tv_usec * NSEC_PER_USEC;
550 
551 	return sum;
552 }
553 
self_open_counters(struct perf_sched * sched,unsigned long cur_task)554 static int self_open_counters(struct perf_sched *sched, unsigned long cur_task)
555 {
556 	struct perf_event_attr attr;
557 	char sbuf[STRERR_BUFSIZE], info[STRERR_BUFSIZE];
558 	int fd;
559 	struct rlimit limit;
560 	bool need_privilege = false;
561 
562 	memset(&attr, 0, sizeof(attr));
563 
564 	attr.type = PERF_TYPE_SOFTWARE;
565 	attr.config = PERF_COUNT_SW_TASK_CLOCK;
566 
567 force_again:
568 	fd = sys_perf_event_open(&attr, 0, -1, -1,
569 				 perf_event_open_cloexec_flag());
570 
571 	if (fd < 0) {
572 		if (errno == EMFILE) {
573 			if (sched->force) {
574 				BUG_ON(getrlimit(RLIMIT_NOFILE, &limit) == -1);
575 				limit.rlim_cur += sched->nr_tasks - cur_task;
576 				if (limit.rlim_cur > limit.rlim_max) {
577 					limit.rlim_max = limit.rlim_cur;
578 					need_privilege = true;
579 				}
580 				if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
581 					if (need_privilege && errno == EPERM)
582 						strcpy(info, "Need privilege\n");
583 				} else
584 					goto force_again;
585 			} else
586 				strcpy(info, "Have a try with -f option\n");
587 		}
588 		pr_err("Error: sys_perf_event_open() syscall returned "
589 		       "with %d (%s)\n%s", fd,
590 		       str_error_r(errno, sbuf, sizeof(sbuf)), info);
591 		exit(EXIT_FAILURE);
592 	}
593 	return fd;
594 }
595 
get_cpu_usage_nsec_self(int fd)596 static u64 get_cpu_usage_nsec_self(int fd)
597 {
598 	u64 runtime;
599 	int ret;
600 
601 	ret = read(fd, &runtime, sizeof(runtime));
602 	BUG_ON(ret != sizeof(runtime));
603 
604 	return runtime;
605 }
606 
607 struct sched_thread_parms {
608 	struct task_desc  *task;
609 	struct perf_sched *sched;
610 	int fd;
611 };
612 
thread_func(void * ctx)613 static void *thread_func(void *ctx)
614 {
615 	struct sched_thread_parms *parms = ctx;
616 	struct task_desc *this_task = parms->task;
617 	struct perf_sched *sched = parms->sched;
618 	u64 cpu_usage_0, cpu_usage_1;
619 	unsigned long i, ret;
620 	char comm2[22];
621 	int fd = parms->fd;
622 
623 	zfree(&parms);
624 
625 	sprintf(comm2, ":%s", this_task->comm);
626 	prctl(PR_SET_NAME, comm2);
627 	if (fd < 0)
628 		return NULL;
629 
630 	while (!sched->thread_funcs_exit) {
631 		ret = sem_post(&this_task->ready_for_work);
632 		BUG_ON(ret);
633 		mutex_lock(&sched->start_work_mutex);
634 		mutex_unlock(&sched->start_work_mutex);
635 
636 		cpu_usage_0 = get_cpu_usage_nsec_self(fd);
637 
638 		for (i = 0; i < this_task->nr_events; i++) {
639 			this_task->curr_event = i;
640 			perf_sched__process_event(sched, this_task->atoms[i]);
641 		}
642 
643 		cpu_usage_1 = get_cpu_usage_nsec_self(fd);
644 		this_task->cpu_usage = cpu_usage_1 - cpu_usage_0;
645 		ret = sem_post(&this_task->work_done_sem);
646 		BUG_ON(ret);
647 
648 		mutex_lock(&sched->work_done_wait_mutex);
649 		mutex_unlock(&sched->work_done_wait_mutex);
650 	}
651 	return NULL;
652 }
653 
create_tasks(struct perf_sched * sched)654 static void create_tasks(struct perf_sched *sched)
655 	EXCLUSIVE_LOCK_FUNCTION(sched->start_work_mutex)
656 	EXCLUSIVE_LOCK_FUNCTION(sched->work_done_wait_mutex)
657 {
658 	struct task_desc *task;
659 	pthread_attr_t attr;
660 	unsigned long i;
661 	int err;
662 
663 	err = pthread_attr_init(&attr);
664 	BUG_ON(err);
665 	err = pthread_attr_setstacksize(&attr,
666 			(size_t) max(16 * 1024, (int)PTHREAD_STACK_MIN));
667 	BUG_ON(err);
668 	mutex_lock(&sched->start_work_mutex);
669 	mutex_lock(&sched->work_done_wait_mutex);
670 	for (i = 0; i < sched->nr_tasks; i++) {
671 		struct sched_thread_parms *parms = malloc(sizeof(*parms));
672 		BUG_ON(parms == NULL);
673 		parms->task = task = sched->tasks[i];
674 		parms->sched = sched;
675 		parms->fd = self_open_counters(sched, i);
676 		sem_init(&task->sleep_sem, 0, 0);
677 		sem_init(&task->ready_for_work, 0, 0);
678 		sem_init(&task->work_done_sem, 0, 0);
679 		task->curr_event = 0;
680 		err = pthread_create(&task->thread, &attr, thread_func, parms);
681 		BUG_ON(err);
682 	}
683 }
684 
destroy_tasks(struct perf_sched * sched)685 static void destroy_tasks(struct perf_sched *sched)
686 	UNLOCK_FUNCTION(sched->start_work_mutex)
687 	UNLOCK_FUNCTION(sched->work_done_wait_mutex)
688 {
689 	struct task_desc *task;
690 	unsigned long i;
691 	int err;
692 
693 	mutex_unlock(&sched->start_work_mutex);
694 	mutex_unlock(&sched->work_done_wait_mutex);
695 	/* Get rid of threads so they won't be upset by mutex destrunction */
696 	for (i = 0; i < sched->nr_tasks; i++) {
697 		task = sched->tasks[i];
698 		err = pthread_join(task->thread, NULL);
699 		BUG_ON(err);
700 		sem_destroy(&task->sleep_sem);
701 		sem_destroy(&task->ready_for_work);
702 		sem_destroy(&task->work_done_sem);
703 	}
704 }
705 
wait_for_tasks(struct perf_sched * sched)706 static void wait_for_tasks(struct perf_sched *sched)
707 	EXCLUSIVE_LOCKS_REQUIRED(sched->work_done_wait_mutex)
708 	EXCLUSIVE_LOCKS_REQUIRED(sched->start_work_mutex)
709 {
710 	u64 cpu_usage_0, cpu_usage_1;
711 	struct task_desc *task;
712 	unsigned long i, ret;
713 
714 	sched->start_time = get_nsecs();
715 	sched->cpu_usage = 0;
716 	mutex_unlock(&sched->work_done_wait_mutex);
717 
718 	for (i = 0; i < sched->nr_tasks; i++) {
719 		task = sched->tasks[i];
720 		ret = sem_wait(&task->ready_for_work);
721 		BUG_ON(ret);
722 		sem_init(&task->ready_for_work, 0, 0);
723 	}
724 	mutex_lock(&sched->work_done_wait_mutex);
725 
726 	cpu_usage_0 = get_cpu_usage_nsec_parent();
727 
728 	mutex_unlock(&sched->start_work_mutex);
729 
730 	for (i = 0; i < sched->nr_tasks; i++) {
731 		task = sched->tasks[i];
732 		ret = sem_wait(&task->work_done_sem);
733 		BUG_ON(ret);
734 		sem_init(&task->work_done_sem, 0, 0);
735 		sched->cpu_usage += task->cpu_usage;
736 		task->cpu_usage = 0;
737 	}
738 
739 	cpu_usage_1 = get_cpu_usage_nsec_parent();
740 	if (!sched->runavg_cpu_usage)
741 		sched->runavg_cpu_usage = sched->cpu_usage;
742 	sched->runavg_cpu_usage = (sched->runavg_cpu_usage * (sched->replay_repeat - 1) + sched->cpu_usage) / sched->replay_repeat;
743 
744 	sched->parent_cpu_usage = cpu_usage_1 - cpu_usage_0;
745 	if (!sched->runavg_parent_cpu_usage)
746 		sched->runavg_parent_cpu_usage = sched->parent_cpu_usage;
747 	sched->runavg_parent_cpu_usage = (sched->runavg_parent_cpu_usage * (sched->replay_repeat - 1) +
748 					 sched->parent_cpu_usage)/sched->replay_repeat;
749 
750 	mutex_lock(&sched->start_work_mutex);
751 
752 	for (i = 0; i < sched->nr_tasks; i++) {
753 		task = sched->tasks[i];
754 		sem_init(&task->sleep_sem, 0, 0);
755 		task->curr_event = 0;
756 	}
757 }
758 
run_one_test(struct perf_sched * sched)759 static void run_one_test(struct perf_sched *sched)
760 	EXCLUSIVE_LOCKS_REQUIRED(sched->work_done_wait_mutex)
761 	EXCLUSIVE_LOCKS_REQUIRED(sched->start_work_mutex)
762 {
763 	u64 T0, T1, delta, avg_delta, fluct;
764 
765 	T0 = get_nsecs();
766 	wait_for_tasks(sched);
767 	T1 = get_nsecs();
768 
769 	delta = T1 - T0;
770 	sched->sum_runtime += delta;
771 	sched->nr_runs++;
772 
773 	avg_delta = sched->sum_runtime / sched->nr_runs;
774 	if (delta < avg_delta)
775 		fluct = avg_delta - delta;
776 	else
777 		fluct = delta - avg_delta;
778 	sched->sum_fluct += fluct;
779 	if (!sched->run_avg)
780 		sched->run_avg = delta;
781 	sched->run_avg = (sched->run_avg * (sched->replay_repeat - 1) + delta) / sched->replay_repeat;
782 
783 	printf("#%-3ld: %0.3f, ", sched->nr_runs, (double)delta / NSEC_PER_MSEC);
784 
785 	printf("ravg: %0.2f, ", (double)sched->run_avg / NSEC_PER_MSEC);
786 
787 	printf("cpu: %0.2f / %0.2f",
788 		(double)sched->cpu_usage / NSEC_PER_MSEC, (double)sched->runavg_cpu_usage / NSEC_PER_MSEC);
789 
790 #if 0
791 	/*
792 	 * rusage statistics done by the parent, these are less
793 	 * accurate than the sched->sum_exec_runtime based statistics:
794 	 */
795 	printf(" [%0.2f / %0.2f]",
796 		(double)sched->parent_cpu_usage / NSEC_PER_MSEC,
797 		(double)sched->runavg_parent_cpu_usage / NSEC_PER_MSEC);
798 #endif
799 
800 	printf("\n");
801 
802 	if (sched->nr_sleep_corrections)
803 		printf(" (%ld sleep corrections)\n", sched->nr_sleep_corrections);
804 	sched->nr_sleep_corrections = 0;
805 }
806 
test_calibrations(struct perf_sched * sched)807 static void test_calibrations(struct perf_sched *sched)
808 {
809 	u64 T0, T1;
810 
811 	T0 = get_nsecs();
812 	burn_nsecs(sched, NSEC_PER_MSEC);
813 	T1 = get_nsecs();
814 
815 	printf("the run test took %" PRIu64 " nsecs\n", T1 - T0);
816 
817 	T0 = get_nsecs();
818 	sleep_nsecs(NSEC_PER_MSEC);
819 	T1 = get_nsecs();
820 
821 	printf("the sleep test took %" PRIu64 " nsecs\n", T1 - T0);
822 }
823 
824 static int
replay_wakeup_event(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct machine * machine __maybe_unused)825 replay_wakeup_event(struct perf_sched *sched,
826 		    struct evsel *evsel, struct perf_sample *sample,
827 		    struct machine *machine __maybe_unused)
828 {
829 	const char *comm = evsel__strval(evsel, sample, "comm");
830 	const u32 pid	 = evsel__intval(evsel, sample, "pid");
831 	struct task_desc *waker, *wakee;
832 
833 	if (verbose > 0) {
834 		printf("sched_wakeup event %p\n", evsel);
835 
836 		printf(" ... pid %d woke up %s/%d\n", sample->tid, comm, pid);
837 	}
838 
839 	waker = register_pid(sched, sample->tid, "<unknown>");
840 	wakee = register_pid(sched, pid, comm);
841 
842 	add_sched_event_wakeup(sched, waker, sample->time, wakee);
843 	return 0;
844 }
845 
replay_switch_event(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct machine * machine __maybe_unused)846 static int replay_switch_event(struct perf_sched *sched,
847 			       struct evsel *evsel,
848 			       struct perf_sample *sample,
849 			       struct machine *machine __maybe_unused)
850 {
851 	const char *prev_comm  = evsel__strval(evsel, sample, "prev_comm"),
852 		   *next_comm  = evsel__strval(evsel, sample, "next_comm");
853 	const u32 prev_pid = evsel__intval(evsel, sample, "prev_pid"),
854 		  next_pid = evsel__intval(evsel, sample, "next_pid");
855 	const char prev_state = evsel__taskstate(evsel, sample, "prev_state");
856 	struct task_desc *prev, __maybe_unused *next;
857 	u64 timestamp0, timestamp = sample->time;
858 	int cpu = sample->cpu;
859 	s64 delta;
860 
861 	if (verbose > 0)
862 		printf("sched_switch event %p\n", evsel);
863 
864 	if (cpu >= MAX_CPUS || cpu < 0)
865 		return 0;
866 
867 	timestamp0 = sched->cpu_last_switched[cpu];
868 	if (timestamp0)
869 		delta = timestamp - timestamp0;
870 	else
871 		delta = 0;
872 
873 	if (delta < 0) {
874 		pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
875 		return -1;
876 	}
877 
878 	pr_debug(" ... switch from %s/%d to %s/%d [ran %" PRIu64 " nsecs]\n",
879 		 prev_comm, prev_pid, next_comm, next_pid, delta);
880 
881 	prev = register_pid(sched, prev_pid, prev_comm);
882 	next = register_pid(sched, next_pid, next_comm);
883 
884 	sched->cpu_last_switched[cpu] = timestamp;
885 
886 	add_sched_event_run(sched, prev, timestamp, delta);
887 	add_sched_event_sleep(sched, prev, timestamp, prev_state);
888 
889 	return 0;
890 }
891 
replay_fork_event(struct perf_sched * sched,union perf_event * event,struct machine * machine)892 static int replay_fork_event(struct perf_sched *sched,
893 			     union perf_event *event,
894 			     struct machine *machine)
895 {
896 	struct thread *child, *parent;
897 
898 	child = machine__findnew_thread(machine, event->fork.pid,
899 					event->fork.tid);
900 	parent = machine__findnew_thread(machine, event->fork.ppid,
901 					 event->fork.ptid);
902 
903 	if (child == NULL || parent == NULL) {
904 		pr_debug("thread does not exist on fork event: child %p, parent %p\n",
905 				 child, parent);
906 		goto out_put;
907 	}
908 
909 	if (verbose > 0) {
910 		printf("fork event\n");
911 		printf("... parent: %s/%d\n", thread__comm_str(parent), thread__tid(parent));
912 		printf("...  child: %s/%d\n", thread__comm_str(child), thread__tid(child));
913 	}
914 
915 	register_pid(sched, thread__tid(parent), thread__comm_str(parent));
916 	register_pid(sched, thread__tid(child), thread__comm_str(child));
917 out_put:
918 	thread__put(child);
919 	thread__put(parent);
920 	return 0;
921 }
922 
923 struct sort_dimension {
924 	const char		*name;
925 	sort_fn_t		cmp;
926 	struct list_head	list;
927 };
928 
init_prio(struct thread_runtime * r)929 static inline void init_prio(struct thread_runtime *r)
930 {
931 	r->prio = -1;
932 }
933 
934 /*
935  * handle runtime stats saved per thread
936  */
thread__init_runtime(struct thread * thread)937 static struct thread_runtime *thread__init_runtime(struct thread *thread)
938 {
939 	struct thread_runtime *r;
940 
941 	r = zalloc(sizeof(struct thread_runtime));
942 	if (!r)
943 		return NULL;
944 
945 	init_stats(&r->run_stats);
946 	init_prio(r);
947 	thread__set_priv(thread, r);
948 
949 	return r;
950 }
951 
thread__get_runtime(struct thread * thread)952 static struct thread_runtime *thread__get_runtime(struct thread *thread)
953 {
954 	struct thread_runtime *tr;
955 
956 	tr = thread__priv(thread);
957 	if (tr == NULL) {
958 		tr = thread__init_runtime(thread);
959 		if (tr == NULL)
960 			pr_debug("Failed to malloc memory for runtime data.\n");
961 	}
962 
963 	return tr;
964 }
965 
966 static int
thread_lat_cmp(struct list_head * list,struct work_atoms * l,struct work_atoms * r)967 thread_lat_cmp(struct list_head *list, struct work_atoms *l, struct work_atoms *r)
968 {
969 	struct sort_dimension *sort;
970 	int ret = 0;
971 
972 	BUG_ON(list_empty(list));
973 
974 	list_for_each_entry(sort, list, list) {
975 		ret = sort->cmp(l, r);
976 		if (ret)
977 			return ret;
978 	}
979 
980 	return ret;
981 }
982 
983 static struct work_atoms *
thread_atoms_search(struct rb_root_cached * root,struct thread * thread,struct list_head * sort_list)984 thread_atoms_search(struct rb_root_cached *root, struct thread *thread,
985 			 struct list_head *sort_list)
986 {
987 	struct rb_node *node = root->rb_root.rb_node;
988 	struct work_atoms key = { .thread = thread };
989 
990 	while (node) {
991 		struct work_atoms *atoms;
992 		int cmp;
993 
994 		atoms = container_of(node, struct work_atoms, node);
995 
996 		cmp = thread_lat_cmp(sort_list, &key, atoms);
997 		if (cmp > 0)
998 			node = node->rb_left;
999 		else if (cmp < 0)
1000 			node = node->rb_right;
1001 		else {
1002 			BUG_ON(!RC_CHK_EQUAL(thread, atoms->thread));
1003 			return atoms;
1004 		}
1005 	}
1006 	return NULL;
1007 }
1008 
1009 static void
__thread_latency_insert(struct rb_root_cached * root,struct work_atoms * data,struct list_head * sort_list)1010 __thread_latency_insert(struct rb_root_cached *root, struct work_atoms *data,
1011 			 struct list_head *sort_list)
1012 {
1013 	struct rb_node **new = &(root->rb_root.rb_node), *parent = NULL;
1014 	bool leftmost = true;
1015 
1016 	while (*new) {
1017 		struct work_atoms *this;
1018 		int cmp;
1019 
1020 		this = container_of(*new, struct work_atoms, node);
1021 		parent = *new;
1022 
1023 		cmp = thread_lat_cmp(sort_list, data, this);
1024 
1025 		if (cmp > 0)
1026 			new = &((*new)->rb_left);
1027 		else {
1028 			new = &((*new)->rb_right);
1029 			leftmost = false;
1030 		}
1031 	}
1032 
1033 	rb_link_node(&data->node, parent, new);
1034 	rb_insert_color_cached(&data->node, root, leftmost);
1035 }
1036 
thread_atoms_insert(struct perf_sched * sched,struct thread * thread)1037 static int thread_atoms_insert(struct perf_sched *sched, struct thread *thread)
1038 {
1039 	struct work_atoms *atoms = zalloc(sizeof(*atoms));
1040 	if (!atoms) {
1041 		pr_err("No memory at %s\n", __func__);
1042 		return -1;
1043 	}
1044 
1045 	atoms->thread = thread__get(thread);
1046 	INIT_LIST_HEAD(&atoms->work_list);
1047 	__thread_latency_insert(&sched->atom_root, atoms, &sched->cmp_pid);
1048 	return 0;
1049 }
1050 
1051 static int
add_sched_out_event(struct work_atoms * atoms,char run_state,u64 timestamp)1052 add_sched_out_event(struct work_atoms *atoms,
1053 		    char run_state,
1054 		    u64 timestamp)
1055 {
1056 	struct work_atom *atom = zalloc(sizeof(*atom));
1057 	if (!atom) {
1058 		pr_err("Non memory at %s", __func__);
1059 		return -1;
1060 	}
1061 
1062 	atom->sched_out_time = timestamp;
1063 
1064 	if (run_state == 'R') {
1065 		atom->state = THREAD_WAIT_CPU;
1066 		atom->wake_up_time = atom->sched_out_time;
1067 	}
1068 
1069 	list_add_tail(&atom->list, &atoms->work_list);
1070 	return 0;
1071 }
1072 
1073 static void
add_runtime_event(struct work_atoms * atoms,u64 delta,u64 timestamp __maybe_unused)1074 add_runtime_event(struct work_atoms *atoms, u64 delta,
1075 		  u64 timestamp __maybe_unused)
1076 {
1077 	struct work_atom *atom;
1078 
1079 	BUG_ON(list_empty(&atoms->work_list));
1080 
1081 	atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1082 
1083 	atom->runtime += delta;
1084 	atoms->total_runtime += delta;
1085 }
1086 
1087 static void
add_sched_in_event(struct work_atoms * atoms,u64 timestamp)1088 add_sched_in_event(struct work_atoms *atoms, u64 timestamp)
1089 {
1090 	struct work_atom *atom;
1091 	u64 delta;
1092 
1093 	if (list_empty(&atoms->work_list))
1094 		return;
1095 
1096 	atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1097 
1098 	if (atom->state != THREAD_WAIT_CPU)
1099 		return;
1100 
1101 	if (timestamp < atom->wake_up_time) {
1102 		atom->state = THREAD_IGNORE;
1103 		return;
1104 	}
1105 
1106 	atom->state = THREAD_SCHED_IN;
1107 	atom->sched_in_time = timestamp;
1108 
1109 	delta = atom->sched_in_time - atom->wake_up_time;
1110 	atoms->total_lat += delta;
1111 	if (delta > atoms->max_lat) {
1112 		atoms->max_lat = delta;
1113 		atoms->max_lat_start = atom->wake_up_time;
1114 		atoms->max_lat_end = timestamp;
1115 	}
1116 	atoms->nb_atoms++;
1117 }
1118 
free_work_atoms(struct work_atoms * atoms)1119 static void free_work_atoms(struct work_atoms *atoms)
1120 {
1121 	struct work_atom *atom, *tmp;
1122 
1123 	if (atoms == NULL)
1124 		return;
1125 
1126 	list_for_each_entry_safe(atom, tmp, &atoms->work_list, list) {
1127 		list_del(&atom->list);
1128 		free(atom);
1129 	}
1130 	thread__zput(atoms->thread);
1131 	free(atoms);
1132 }
1133 
latency_switch_event(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)1134 static int latency_switch_event(struct perf_sched *sched,
1135 				struct evsel *evsel,
1136 				struct perf_sample *sample,
1137 				struct machine *machine)
1138 {
1139 	const u32 prev_pid = evsel__intval(evsel, sample, "prev_pid"),
1140 		  next_pid = evsel__intval(evsel, sample, "next_pid");
1141 	const char prev_state = evsel__taskstate(evsel, sample, "prev_state");
1142 	struct work_atoms *out_events, *in_events;
1143 	struct thread *sched_out, *sched_in;
1144 	u64 timestamp0, timestamp = sample->time;
1145 	int cpu = sample->cpu, err = -1;
1146 	s64 delta;
1147 
1148 	BUG_ON(cpu >= MAX_CPUS || cpu < 0);
1149 
1150 	timestamp0 = sched->cpu_last_switched[cpu];
1151 	sched->cpu_last_switched[cpu] = timestamp;
1152 	if (timestamp0)
1153 		delta = timestamp - timestamp0;
1154 	else
1155 		delta = 0;
1156 
1157 	if (delta < 0) {
1158 		pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
1159 		return -1;
1160 	}
1161 
1162 	sched_out = machine__findnew_thread(machine, -1, prev_pid);
1163 	sched_in = machine__findnew_thread(machine, -1, next_pid);
1164 	if (sched_out == NULL || sched_in == NULL)
1165 		goto out_put;
1166 
1167 	out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
1168 	if (!out_events) {
1169 		if (thread_atoms_insert(sched, sched_out))
1170 			goto out_put;
1171 		out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
1172 		if (!out_events) {
1173 			pr_err("out-event: Internal tree error");
1174 			goto out_put;
1175 		}
1176 	}
1177 	if (add_sched_out_event(out_events, prev_state, timestamp))
1178 		return -1;
1179 
1180 	in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
1181 	if (!in_events) {
1182 		if (thread_atoms_insert(sched, sched_in))
1183 			goto out_put;
1184 		in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
1185 		if (!in_events) {
1186 			pr_err("in-event: Internal tree error");
1187 			goto out_put;
1188 		}
1189 		/*
1190 		 * Take came in we have not heard about yet,
1191 		 * add in an initial atom in runnable state:
1192 		 */
1193 		if (add_sched_out_event(in_events, 'R', timestamp))
1194 			goto out_put;
1195 	}
1196 	add_sched_in_event(in_events, timestamp);
1197 	err = 0;
1198 out_put:
1199 	thread__put(sched_out);
1200 	thread__put(sched_in);
1201 	return err;
1202 }
1203 
latency_runtime_event(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)1204 static int latency_runtime_event(struct perf_sched *sched,
1205 				 struct evsel *evsel,
1206 				 struct perf_sample *sample,
1207 				 struct machine *machine)
1208 {
1209 	const u32 pid	   = evsel__intval(evsel, sample, "pid");
1210 	const u64 runtime  = evsel__intval(evsel, sample, "runtime");
1211 	struct thread *thread = machine__findnew_thread(machine, -1, pid);
1212 	struct work_atoms *atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
1213 	u64 timestamp = sample->time;
1214 	int cpu = sample->cpu, err = -1;
1215 
1216 	if (thread == NULL)
1217 		return -1;
1218 
1219 	BUG_ON(cpu >= MAX_CPUS || cpu < 0);
1220 	if (!atoms) {
1221 		if (thread_atoms_insert(sched, thread))
1222 			goto out_put;
1223 		atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
1224 		if (!atoms) {
1225 			pr_err("in-event: Internal tree error");
1226 			goto out_put;
1227 		}
1228 		if (add_sched_out_event(atoms, 'R', timestamp))
1229 			goto out_put;
1230 	}
1231 
1232 	add_runtime_event(atoms, runtime, timestamp);
1233 	err = 0;
1234 out_put:
1235 	thread__put(thread);
1236 	return err;
1237 }
1238 
latency_wakeup_event(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)1239 static int latency_wakeup_event(struct perf_sched *sched,
1240 				struct evsel *evsel,
1241 				struct perf_sample *sample,
1242 				struct machine *machine)
1243 {
1244 	const u32 pid	  = evsel__intval(evsel, sample, "pid");
1245 	struct work_atoms *atoms;
1246 	struct work_atom *atom;
1247 	struct thread *wakee;
1248 	u64 timestamp = sample->time;
1249 	int err = -1;
1250 
1251 	wakee = machine__findnew_thread(machine, -1, pid);
1252 	if (wakee == NULL)
1253 		return -1;
1254 	atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
1255 	if (!atoms) {
1256 		if (thread_atoms_insert(sched, wakee))
1257 			goto out_put;
1258 		atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
1259 		if (!atoms) {
1260 			pr_err("wakeup-event: Internal tree error");
1261 			goto out_put;
1262 		}
1263 		if (add_sched_out_event(atoms, 'S', timestamp))
1264 			goto out_put;
1265 	}
1266 
1267 	BUG_ON(list_empty(&atoms->work_list));
1268 
1269 	atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1270 
1271 	/*
1272 	 * As we do not guarantee the wakeup event happens when
1273 	 * task is out of run queue, also may happen when task is
1274 	 * on run queue and wakeup only change ->state to TASK_RUNNING,
1275 	 * then we should not set the ->wake_up_time when wake up a
1276 	 * task which is on run queue.
1277 	 *
1278 	 * You WILL be missing events if you've recorded only
1279 	 * one CPU, or are only looking at only one, so don't
1280 	 * skip in this case.
1281 	 */
1282 	if (sched->profile_cpu == -1 && atom->state != THREAD_SLEEPING)
1283 		goto out_ok;
1284 
1285 	sched->nr_timestamps++;
1286 	if (atom->sched_out_time > timestamp) {
1287 		sched->nr_unordered_timestamps++;
1288 		goto out_ok;
1289 	}
1290 
1291 	atom->state = THREAD_WAIT_CPU;
1292 	atom->wake_up_time = timestamp;
1293 out_ok:
1294 	err = 0;
1295 out_put:
1296 	thread__put(wakee);
1297 	return err;
1298 }
1299 
latency_migrate_task_event(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)1300 static int latency_migrate_task_event(struct perf_sched *sched,
1301 				      struct evsel *evsel,
1302 				      struct perf_sample *sample,
1303 				      struct machine *machine)
1304 {
1305 	const u32 pid = evsel__intval(evsel, sample, "pid");
1306 	u64 timestamp = sample->time;
1307 	struct work_atoms *atoms;
1308 	struct work_atom *atom;
1309 	struct thread *migrant;
1310 	int err = -1;
1311 
1312 	/*
1313 	 * Only need to worry about migration when profiling one CPU.
1314 	 */
1315 	if (sched->profile_cpu == -1)
1316 		return 0;
1317 
1318 	migrant = machine__findnew_thread(machine, -1, pid);
1319 	if (migrant == NULL)
1320 		return -1;
1321 	atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
1322 	if (!atoms) {
1323 		if (thread_atoms_insert(sched, migrant))
1324 			goto out_put;
1325 		register_pid(sched, thread__tid(migrant), thread__comm_str(migrant));
1326 		atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
1327 		if (!atoms) {
1328 			pr_err("migration-event: Internal tree error");
1329 			goto out_put;
1330 		}
1331 		if (add_sched_out_event(atoms, 'R', timestamp))
1332 			goto out_put;
1333 	}
1334 
1335 	BUG_ON(list_empty(&atoms->work_list));
1336 
1337 	atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1338 	atom->sched_in_time = atom->sched_out_time = atom->wake_up_time = timestamp;
1339 
1340 	sched->nr_timestamps++;
1341 
1342 	if (atom->sched_out_time > timestamp)
1343 		sched->nr_unordered_timestamps++;
1344 	err = 0;
1345 out_put:
1346 	thread__put(migrant);
1347 	return err;
1348 }
1349 
output_lat_thread(struct perf_sched * sched,struct work_atoms * work_list)1350 static void output_lat_thread(struct perf_sched *sched, struct work_atoms *work_list)
1351 {
1352 	int i;
1353 	int ret;
1354 	u64 avg;
1355 	char max_lat_start[32], max_lat_end[32];
1356 
1357 	if (!work_list->nb_atoms)
1358 		return;
1359 	/*
1360 	 * Ignore idle threads:
1361 	 */
1362 	if (!strcmp(thread__comm_str(work_list->thread), "swapper"))
1363 		return;
1364 
1365 	sched->all_runtime += work_list->total_runtime;
1366 	sched->all_count   += work_list->nb_atoms;
1367 
1368 	if (work_list->num_merged > 1) {
1369 		ret = printf("  %s:(%d) ", thread__comm_str(work_list->thread),
1370 			     work_list->num_merged);
1371 	} else {
1372 		ret = printf("  %s:%d ", thread__comm_str(work_list->thread),
1373 			     thread__tid(work_list->thread));
1374 	}
1375 
1376 	for (i = 0; i < 24 - ret; i++)
1377 		printf(" ");
1378 
1379 	avg = work_list->total_lat / work_list->nb_atoms;
1380 	timestamp__scnprintf_usec(work_list->max_lat_start, max_lat_start, sizeof(max_lat_start));
1381 	timestamp__scnprintf_usec(work_list->max_lat_end, max_lat_end, sizeof(max_lat_end));
1382 
1383 	printf("|%11.3f ms |%9" PRIu64 " | avg:%8.3f ms | max:%8.3f ms | max start: %12s s | max end: %12s s\n",
1384 	      (double)work_list->total_runtime / NSEC_PER_MSEC,
1385 		 work_list->nb_atoms, (double)avg / NSEC_PER_MSEC,
1386 		 (double)work_list->max_lat / NSEC_PER_MSEC,
1387 		 max_lat_start, max_lat_end);
1388 }
1389 
pid_cmp(struct work_atoms * l,struct work_atoms * r)1390 static int pid_cmp(struct work_atoms *l, struct work_atoms *r)
1391 {
1392 	pid_t l_tid, r_tid;
1393 
1394 	if (RC_CHK_EQUAL(l->thread, r->thread))
1395 		return 0;
1396 	l_tid = thread__tid(l->thread);
1397 	r_tid = thread__tid(r->thread);
1398 	if (l_tid < r_tid)
1399 		return -1;
1400 	if (l_tid > r_tid)
1401 		return 1;
1402 	return (int)(RC_CHK_ACCESS(l->thread) - RC_CHK_ACCESS(r->thread));
1403 }
1404 
avg_cmp(struct work_atoms * l,struct work_atoms * r)1405 static int avg_cmp(struct work_atoms *l, struct work_atoms *r)
1406 {
1407 	u64 avgl, avgr;
1408 
1409 	if (!l->nb_atoms)
1410 		return -1;
1411 
1412 	if (!r->nb_atoms)
1413 		return 1;
1414 
1415 	avgl = l->total_lat / l->nb_atoms;
1416 	avgr = r->total_lat / r->nb_atoms;
1417 
1418 	if (avgl < avgr)
1419 		return -1;
1420 	if (avgl > avgr)
1421 		return 1;
1422 
1423 	return 0;
1424 }
1425 
max_cmp(struct work_atoms * l,struct work_atoms * r)1426 static int max_cmp(struct work_atoms *l, struct work_atoms *r)
1427 {
1428 	if (l->max_lat < r->max_lat)
1429 		return -1;
1430 	if (l->max_lat > r->max_lat)
1431 		return 1;
1432 
1433 	return 0;
1434 }
1435 
switch_cmp(struct work_atoms * l,struct work_atoms * r)1436 static int switch_cmp(struct work_atoms *l, struct work_atoms *r)
1437 {
1438 	if (l->nb_atoms < r->nb_atoms)
1439 		return -1;
1440 	if (l->nb_atoms > r->nb_atoms)
1441 		return 1;
1442 
1443 	return 0;
1444 }
1445 
runtime_cmp(struct work_atoms * l,struct work_atoms * r)1446 static int runtime_cmp(struct work_atoms *l, struct work_atoms *r)
1447 {
1448 	if (l->total_runtime < r->total_runtime)
1449 		return -1;
1450 	if (l->total_runtime > r->total_runtime)
1451 		return 1;
1452 
1453 	return 0;
1454 }
1455 
sort_dimension__add(const char * tok,struct list_head * list)1456 static int sort_dimension__add(const char *tok, struct list_head *list)
1457 {
1458 	size_t i;
1459 	static struct sort_dimension avg_sort_dimension = {
1460 		.name = "avg",
1461 		.cmp  = avg_cmp,
1462 	};
1463 	static struct sort_dimension max_sort_dimension = {
1464 		.name = "max",
1465 		.cmp  = max_cmp,
1466 	};
1467 	static struct sort_dimension pid_sort_dimension = {
1468 		.name = "pid",
1469 		.cmp  = pid_cmp,
1470 	};
1471 	static struct sort_dimension runtime_sort_dimension = {
1472 		.name = "runtime",
1473 		.cmp  = runtime_cmp,
1474 	};
1475 	static struct sort_dimension switch_sort_dimension = {
1476 		.name = "switch",
1477 		.cmp  = switch_cmp,
1478 	};
1479 	struct sort_dimension *available_sorts[] = {
1480 		&pid_sort_dimension,
1481 		&avg_sort_dimension,
1482 		&max_sort_dimension,
1483 		&switch_sort_dimension,
1484 		&runtime_sort_dimension,
1485 	};
1486 
1487 	for (i = 0; i < ARRAY_SIZE(available_sorts); i++) {
1488 		if (!strcmp(available_sorts[i]->name, tok)) {
1489 			list_add_tail(&available_sorts[i]->list, list);
1490 
1491 			return 0;
1492 		}
1493 	}
1494 
1495 	return -1;
1496 }
1497 
perf_sched__sort_lat(struct perf_sched * sched)1498 static void perf_sched__sort_lat(struct perf_sched *sched)
1499 {
1500 	struct rb_node *node;
1501 	struct rb_root_cached *root = &sched->atom_root;
1502 again:
1503 	for (;;) {
1504 		struct work_atoms *data;
1505 		node = rb_first_cached(root);
1506 		if (!node)
1507 			break;
1508 
1509 		rb_erase_cached(node, root);
1510 		data = rb_entry(node, struct work_atoms, node);
1511 		__thread_latency_insert(&sched->sorted_atom_root, data, &sched->sort_list);
1512 	}
1513 	if (root == &sched->atom_root) {
1514 		root = &sched->merged_atom_root;
1515 		goto again;
1516 	}
1517 }
1518 
process_sched_wakeup_event(const struct perf_tool * tool,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)1519 static int process_sched_wakeup_event(const struct perf_tool *tool,
1520 				      struct evsel *evsel,
1521 				      struct perf_sample *sample,
1522 				      struct machine *machine)
1523 {
1524 	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1525 
1526 	if (sched->tp_handler->wakeup_event)
1527 		return sched->tp_handler->wakeup_event(sched, evsel, sample, machine);
1528 
1529 	return 0;
1530 }
1531 
process_sched_wakeup_ignore(const struct perf_tool * tool __maybe_unused,struct evsel * evsel __maybe_unused,struct perf_sample * sample __maybe_unused,struct machine * machine __maybe_unused)1532 static int process_sched_wakeup_ignore(const struct perf_tool *tool __maybe_unused,
1533 				      struct evsel *evsel __maybe_unused,
1534 				      struct perf_sample *sample __maybe_unused,
1535 				      struct machine *machine __maybe_unused)
1536 {
1537 	return 0;
1538 }
1539 
1540 union map_priv {
1541 	void	*ptr;
1542 	bool	 color;
1543 };
1544 
thread__has_color(struct thread * thread)1545 static bool thread__has_color(struct thread *thread)
1546 {
1547 	union map_priv priv = {
1548 		.ptr = thread__priv(thread),
1549 	};
1550 
1551 	return priv.color;
1552 }
1553 
1554 static struct thread*
map__findnew_thread(struct perf_sched * sched,struct machine * machine,pid_t pid,pid_t tid)1555 map__findnew_thread(struct perf_sched *sched, struct machine *machine, pid_t pid, pid_t tid)
1556 {
1557 	struct thread *thread = machine__findnew_thread(machine, pid, tid);
1558 	union map_priv priv = {
1559 		.color = false,
1560 	};
1561 
1562 	if (!sched->map.color_pids || !thread || thread__priv(thread))
1563 		return thread;
1564 
1565 	if (thread_map__has(sched->map.color_pids, tid))
1566 		priv.color = true;
1567 
1568 	thread__set_priv(thread, priv.ptr);
1569 	return thread;
1570 }
1571 
sched_match_task(struct perf_sched * sched,const char * comm_str)1572 static bool sched_match_task(struct perf_sched *sched, const char *comm_str)
1573 {
1574 	bool fuzzy_match = sched->map.fuzzy;
1575 	struct strlist *task_names = sched->map.task_names;
1576 	struct str_node *node;
1577 
1578 	strlist__for_each_entry(node, task_names) {
1579 		bool match_found = fuzzy_match ? !!strstr(comm_str, node->s) :
1580 							!strcmp(comm_str, node->s);
1581 		if (match_found)
1582 			return true;
1583 	}
1584 
1585 	return false;
1586 }
1587 
print_sched_map(struct perf_sched * sched,struct perf_cpu this_cpu,int cpus_nr,const char * color,bool sched_out)1588 static void print_sched_map(struct perf_sched *sched, struct perf_cpu this_cpu, int cpus_nr,
1589 								const char *color, bool sched_out)
1590 {
1591 	for (int i = 0; i < cpus_nr; i++) {
1592 		struct perf_cpu cpu = {
1593 			.cpu = sched->map.comp ? sched->map.comp_cpus[i].cpu : i,
1594 		};
1595 		struct thread *curr_thread = sched->curr_thread[cpu.cpu];
1596 		struct thread *curr_out_thread = sched->curr_out_thread[cpu.cpu];
1597 		struct thread_runtime *curr_tr;
1598 		const char *pid_color = color;
1599 		const char *cpu_color = color;
1600 		char symbol = ' ';
1601 		struct thread *thread_to_check = sched_out ? curr_out_thread : curr_thread;
1602 
1603 		if (thread_to_check && thread__has_color(thread_to_check))
1604 			pid_color = COLOR_PIDS;
1605 
1606 		if (sched->map.color_cpus && perf_cpu_map__has(sched->map.color_cpus, cpu))
1607 			cpu_color = COLOR_CPUS;
1608 
1609 		if (cpu.cpu == this_cpu.cpu)
1610 			symbol = '*';
1611 
1612 		color_fprintf(stdout, cpu.cpu != this_cpu.cpu ? color : cpu_color, "%c", symbol);
1613 
1614 		thread_to_check = sched_out ? sched->curr_out_thread[cpu.cpu] :
1615 								sched->curr_thread[cpu.cpu];
1616 
1617 		if (thread_to_check) {
1618 			curr_tr = thread__get_runtime(thread_to_check);
1619 			if (curr_tr == NULL)
1620 				return;
1621 
1622 			if (sched_out) {
1623 				if (cpu.cpu == this_cpu.cpu)
1624 					color_fprintf(stdout, color, "-  ");
1625 				else {
1626 					curr_tr = thread__get_runtime(sched->curr_thread[cpu.cpu]);
1627 					if (curr_tr != NULL)
1628 						color_fprintf(stdout, pid_color, "%2s ",
1629 										curr_tr->shortname);
1630 				}
1631 			} else
1632 				color_fprintf(stdout, pid_color, "%2s ", curr_tr->shortname);
1633 		} else
1634 			color_fprintf(stdout, color, "   ");
1635 	}
1636 }
1637 
map_switch_event(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)1638 static int map_switch_event(struct perf_sched *sched, struct evsel *evsel,
1639 			    struct perf_sample *sample, struct machine *machine)
1640 {
1641 	const u32 next_pid = evsel__intval(evsel, sample, "next_pid");
1642 	const u32 prev_pid = evsel__intval(evsel, sample, "prev_pid");
1643 	struct thread *sched_in, *sched_out;
1644 	struct thread_runtime *tr;
1645 	int new_shortname;
1646 	u64 timestamp0, timestamp = sample->time;
1647 	s64 delta;
1648 	struct perf_cpu this_cpu = {
1649 		.cpu = sample->cpu,
1650 	};
1651 	int cpus_nr;
1652 	int proceed;
1653 	bool new_cpu = false;
1654 	const char *color = PERF_COLOR_NORMAL;
1655 	char stimestamp[32];
1656 	const char *str;
1657 	int ret = -1;
1658 
1659 	BUG_ON(this_cpu.cpu >= MAX_CPUS || this_cpu.cpu < 0);
1660 
1661 	if (this_cpu.cpu > sched->max_cpu.cpu)
1662 		sched->max_cpu = this_cpu;
1663 
1664 	if (sched->map.comp) {
1665 		cpus_nr = bitmap_weight(sched->map.comp_cpus_mask, MAX_CPUS);
1666 		if (!__test_and_set_bit(this_cpu.cpu, sched->map.comp_cpus_mask)) {
1667 			sched->map.comp_cpus[cpus_nr++] = this_cpu;
1668 			new_cpu = true;
1669 		}
1670 	} else
1671 		cpus_nr = sched->max_cpu.cpu;
1672 
1673 	timestamp0 = sched->cpu_last_switched[this_cpu.cpu];
1674 	sched->cpu_last_switched[this_cpu.cpu] = timestamp;
1675 	if (timestamp0)
1676 		delta = timestamp - timestamp0;
1677 	else
1678 		delta = 0;
1679 
1680 	if (delta < 0) {
1681 		pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
1682 		return -1;
1683 	}
1684 
1685 	sched_in = map__findnew_thread(sched, machine, -1, next_pid);
1686 	sched_out = map__findnew_thread(sched, machine, -1, prev_pid);
1687 	if (sched_in == NULL || sched_out == NULL)
1688 		goto out;
1689 
1690 	tr = thread__get_runtime(sched_in);
1691 	if (tr == NULL)
1692 		goto out;
1693 
1694 	thread__put(sched->curr_thread[this_cpu.cpu]);
1695 	thread__put(sched->curr_out_thread[this_cpu.cpu]);
1696 
1697 	sched->curr_thread[this_cpu.cpu] = thread__get(sched_in);
1698 	sched->curr_out_thread[this_cpu.cpu] = thread__get(sched_out);
1699 
1700 	ret = 0;
1701 
1702 	str = thread__comm_str(sched_in);
1703 	new_shortname = 0;
1704 	if (!tr->shortname[0]) {
1705 		if (!strcmp(thread__comm_str(sched_in), "swapper")) {
1706 			/*
1707 			 * Don't allocate a letter-number for swapper:0
1708 			 * as a shortname. Instead, we use '.' for it.
1709 			 */
1710 			tr->shortname[0] = '.';
1711 			tr->shortname[1] = ' ';
1712 		} else if (!sched->map.task_name || sched_match_task(sched, str)) {
1713 			tr->shortname[0] = sched->next_shortname1;
1714 			tr->shortname[1] = sched->next_shortname2;
1715 
1716 			if (sched->next_shortname1 < 'Z') {
1717 				sched->next_shortname1++;
1718 			} else {
1719 				sched->next_shortname1 = 'A';
1720 				if (sched->next_shortname2 < '9')
1721 					sched->next_shortname2++;
1722 				else
1723 					sched->next_shortname2 = '0';
1724 			}
1725 		} else {
1726 			tr->shortname[0] = '-';
1727 			tr->shortname[1] = ' ';
1728 		}
1729 		new_shortname = 1;
1730 	}
1731 
1732 	if (sched->map.cpus && !perf_cpu_map__has(sched->map.cpus, this_cpu))
1733 		goto out;
1734 
1735 	proceed = 0;
1736 	str = thread__comm_str(sched_in);
1737 	/*
1738 	 * Check which of sched_in and sched_out matches the passed --task-name
1739 	 * arguments and call the corresponding print_sched_map.
1740 	 */
1741 	if (sched->map.task_name && !sched_match_task(sched, str)) {
1742 		if (!sched_match_task(sched, thread__comm_str(sched_out)))
1743 			goto out;
1744 		else
1745 			goto sched_out;
1746 
1747 	} else {
1748 		str = thread__comm_str(sched_out);
1749 		if (!(sched->map.task_name && !sched_match_task(sched, str)))
1750 			proceed = 1;
1751 	}
1752 
1753 	printf("  ");
1754 
1755 	print_sched_map(sched, this_cpu, cpus_nr, color, false);
1756 
1757 	timestamp__scnprintf_usec(timestamp, stimestamp, sizeof(stimestamp));
1758 	color_fprintf(stdout, color, "  %12s secs ", stimestamp);
1759 	if (new_shortname || tr->comm_changed || (verbose > 0 && thread__tid(sched_in))) {
1760 		const char *pid_color = color;
1761 
1762 		if (thread__has_color(sched_in))
1763 			pid_color = COLOR_PIDS;
1764 
1765 		color_fprintf(stdout, pid_color, "%s => %s:%d",
1766 			tr->shortname, thread__comm_str(sched_in), thread__tid(sched_in));
1767 		tr->comm_changed = false;
1768 	}
1769 
1770 	if (sched->map.comp && new_cpu)
1771 		color_fprintf(stdout, color, " (CPU %d)", this_cpu);
1772 
1773 	if (proceed != 1) {
1774 		color_fprintf(stdout, color, "\n");
1775 		goto out;
1776 	}
1777 
1778 sched_out:
1779 	if (sched->map.task_name) {
1780 		tr = thread__get_runtime(sched->curr_out_thread[this_cpu.cpu]);
1781 		if (strcmp(tr->shortname, "") == 0)
1782 			goto out;
1783 
1784 		if (proceed == 1)
1785 			color_fprintf(stdout, color, "\n");
1786 
1787 		printf("  ");
1788 		print_sched_map(sched, this_cpu, cpus_nr, color, true);
1789 		timestamp__scnprintf_usec(timestamp, stimestamp, sizeof(stimestamp));
1790 		color_fprintf(stdout, color, "  %12s secs ", stimestamp);
1791 	}
1792 
1793 	color_fprintf(stdout, color, "\n");
1794 
1795 out:
1796 	thread__put(sched_out);
1797 	thread__put(sched_in);
1798 
1799 	return ret;
1800 }
1801 
process_sched_switch_event(const struct perf_tool * tool,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)1802 static int process_sched_switch_event(const struct perf_tool *tool,
1803 				      struct evsel *evsel,
1804 				      struct perf_sample *sample,
1805 				      struct machine *machine)
1806 {
1807 	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1808 	int this_cpu = sample->cpu, err = 0;
1809 	u32 prev_pid = evsel__intval(evsel, sample, "prev_pid"),
1810 	    next_pid = evsel__intval(evsel, sample, "next_pid");
1811 
1812 	if (sched->curr_pid[this_cpu] != (u32)-1) {
1813 		/*
1814 		 * Are we trying to switch away a PID that is
1815 		 * not current?
1816 		 */
1817 		if (sched->curr_pid[this_cpu] != prev_pid)
1818 			sched->nr_context_switch_bugs++;
1819 	}
1820 
1821 	if (sched->tp_handler->switch_event)
1822 		err = sched->tp_handler->switch_event(sched, evsel, sample, machine);
1823 
1824 	sched->curr_pid[this_cpu] = next_pid;
1825 	return err;
1826 }
1827 
process_sched_runtime_event(const struct perf_tool * tool,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)1828 static int process_sched_runtime_event(const struct perf_tool *tool,
1829 				       struct evsel *evsel,
1830 				       struct perf_sample *sample,
1831 				       struct machine *machine)
1832 {
1833 	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1834 
1835 	if (sched->tp_handler->runtime_event)
1836 		return sched->tp_handler->runtime_event(sched, evsel, sample, machine);
1837 
1838 	return 0;
1839 }
1840 
perf_sched__process_fork_event(const struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct machine * machine)1841 static int perf_sched__process_fork_event(const struct perf_tool *tool,
1842 					  union perf_event *event,
1843 					  struct perf_sample *sample,
1844 					  struct machine *machine)
1845 {
1846 	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1847 
1848 	/* run the fork event through the perf machinery */
1849 	perf_event__process_fork(tool, event, sample, machine);
1850 
1851 	/* and then run additional processing needed for this command */
1852 	if (sched->tp_handler->fork_event)
1853 		return sched->tp_handler->fork_event(sched, event, machine);
1854 
1855 	return 0;
1856 }
1857 
process_sched_migrate_task_event(const struct perf_tool * tool,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)1858 static int process_sched_migrate_task_event(const struct perf_tool *tool,
1859 					    struct evsel *evsel,
1860 					    struct perf_sample *sample,
1861 					    struct machine *machine)
1862 {
1863 	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1864 
1865 	if (sched->tp_handler->migrate_task_event)
1866 		return sched->tp_handler->migrate_task_event(sched, evsel, sample, machine);
1867 
1868 	return 0;
1869 }
1870 
1871 typedef int (*tracepoint_handler)(const struct perf_tool *tool,
1872 				  struct evsel *evsel,
1873 				  struct perf_sample *sample,
1874 				  struct machine *machine);
1875 
perf_sched__process_tracepoint_sample(const struct perf_tool * tool __maybe_unused,union perf_event * event __maybe_unused,struct perf_sample * sample,struct evsel * evsel,struct machine * machine)1876 static int perf_sched__process_tracepoint_sample(const struct perf_tool *tool __maybe_unused,
1877 						 union perf_event *event __maybe_unused,
1878 						 struct perf_sample *sample,
1879 						 struct evsel *evsel,
1880 						 struct machine *machine)
1881 {
1882 	int err = 0;
1883 
1884 	if (evsel->handler != NULL) {
1885 		tracepoint_handler f = evsel->handler;
1886 		err = f(tool, evsel, sample, machine);
1887 	}
1888 
1889 	return err;
1890 }
1891 
perf_sched__process_comm(const struct perf_tool * tool __maybe_unused,union perf_event * event,struct perf_sample * sample,struct machine * machine)1892 static int perf_sched__process_comm(const struct perf_tool *tool __maybe_unused,
1893 				    union perf_event *event,
1894 				    struct perf_sample *sample,
1895 				    struct machine *machine)
1896 {
1897 	struct thread *thread;
1898 	struct thread_runtime *tr;
1899 	int err;
1900 
1901 	err = perf_event__process_comm(tool, event, sample, machine);
1902 	if (err)
1903 		return err;
1904 
1905 	thread = machine__find_thread(machine, sample->pid, sample->tid);
1906 	if (!thread) {
1907 		pr_err("Internal error: can't find thread\n");
1908 		return -1;
1909 	}
1910 
1911 	tr = thread__get_runtime(thread);
1912 	if (tr == NULL) {
1913 		thread__put(thread);
1914 		return -1;
1915 	}
1916 
1917 	tr->comm_changed = true;
1918 	thread__put(thread);
1919 
1920 	return 0;
1921 }
1922 
perf_sched__read_events(struct perf_sched * sched)1923 static int perf_sched__read_events(struct perf_sched *sched)
1924 {
1925 	struct evsel_str_handler handlers[] = {
1926 		{ "sched:sched_switch",	      process_sched_switch_event, },
1927 		{ "sched:sched_stat_runtime", process_sched_runtime_event, },
1928 		{ "sched:sched_wakeup",	      process_sched_wakeup_event, },
1929 		{ "sched:sched_waking",	      process_sched_wakeup_event, },
1930 		{ "sched:sched_wakeup_new",   process_sched_wakeup_event, },
1931 		{ "sched:sched_migrate_task", process_sched_migrate_task_event, },
1932 	};
1933 	struct perf_session *session;
1934 	struct perf_data data = {
1935 		.path  = input_name,
1936 		.mode  = PERF_DATA_MODE_READ,
1937 		.force = sched->force,
1938 	};
1939 	int rc = -1;
1940 
1941 	session = perf_session__new(&data, &sched->tool);
1942 	if (IS_ERR(session)) {
1943 		pr_debug("Error creating perf session");
1944 		return PTR_ERR(session);
1945 	}
1946 
1947 	symbol__init(&session->header.env);
1948 
1949 	/* prefer sched_waking if it is captured */
1950 	if (evlist__find_tracepoint_by_name(session->evlist, "sched:sched_waking"))
1951 		handlers[2].handler = process_sched_wakeup_ignore;
1952 
1953 	if (perf_session__set_tracepoints_handlers(session, handlers))
1954 		goto out_delete;
1955 
1956 	if (perf_session__has_traces(session, "record -R")) {
1957 		int err = perf_session__process_events(session);
1958 		if (err) {
1959 			pr_err("Failed to process events, error %d", err);
1960 			goto out_delete;
1961 		}
1962 
1963 		sched->nr_events      = session->evlist->stats.nr_events[0];
1964 		sched->nr_lost_events = session->evlist->stats.total_lost;
1965 		sched->nr_lost_chunks = session->evlist->stats.nr_events[PERF_RECORD_LOST];
1966 	}
1967 
1968 	rc = 0;
1969 out_delete:
1970 	perf_session__delete(session);
1971 	return rc;
1972 }
1973 
1974 /*
1975  * scheduling times are printed as msec.usec
1976  */
print_sched_time(unsigned long long nsecs,int width)1977 static inline void print_sched_time(unsigned long long nsecs, int width)
1978 {
1979 	unsigned long msecs;
1980 	unsigned long usecs;
1981 
1982 	msecs  = nsecs / NSEC_PER_MSEC;
1983 	nsecs -= msecs * NSEC_PER_MSEC;
1984 	usecs  = nsecs / NSEC_PER_USEC;
1985 	printf("%*lu.%03lu ", width, msecs, usecs);
1986 }
1987 
1988 /*
1989  * returns runtime data for event, allocating memory for it the
1990  * first time it is used.
1991  */
evsel__get_runtime(struct evsel * evsel)1992 static struct evsel_runtime *evsel__get_runtime(struct evsel *evsel)
1993 {
1994 	struct evsel_runtime *r = evsel->priv;
1995 
1996 	if (r == NULL) {
1997 		r = zalloc(sizeof(struct evsel_runtime));
1998 		evsel->priv = r;
1999 	}
2000 
2001 	return r;
2002 }
2003 
2004 /*
2005  * save last time event was seen per cpu
2006  */
evsel__save_time(struct evsel * evsel,u64 timestamp,u32 cpu)2007 static void evsel__save_time(struct evsel *evsel, u64 timestamp, u32 cpu)
2008 {
2009 	struct evsel_runtime *r = evsel__get_runtime(evsel);
2010 
2011 	if (r == NULL)
2012 		return;
2013 
2014 	if ((cpu >= r->ncpu) || (r->last_time == NULL)) {
2015 		int i, n = __roundup_pow_of_two(cpu+1);
2016 		void *p = r->last_time;
2017 
2018 		p = realloc(r->last_time, n * sizeof(u64));
2019 		if (!p)
2020 			return;
2021 
2022 		r->last_time = p;
2023 		for (i = r->ncpu; i < n; ++i)
2024 			r->last_time[i] = (u64) 0;
2025 
2026 		r->ncpu = n;
2027 	}
2028 
2029 	r->last_time[cpu] = timestamp;
2030 }
2031 
2032 /* returns last time this event was seen on the given cpu */
evsel__get_time(struct evsel * evsel,u32 cpu)2033 static u64 evsel__get_time(struct evsel *evsel, u32 cpu)
2034 {
2035 	struct evsel_runtime *r = evsel__get_runtime(evsel);
2036 
2037 	if ((r == NULL) || (r->last_time == NULL) || (cpu >= r->ncpu))
2038 		return 0;
2039 
2040 	return r->last_time[cpu];
2041 }
2042 
timehist__evsel_priv_destructor(void * priv)2043 static void timehist__evsel_priv_destructor(void *priv)
2044 {
2045 	struct evsel_runtime *r = priv;
2046 
2047 	if (r) {
2048 		free(r->last_time);
2049 		free(r);
2050 	}
2051 }
2052 
2053 static int comm_width = 30;
2054 
timehist_get_commstr(struct thread * thread)2055 static char *timehist_get_commstr(struct thread *thread)
2056 {
2057 	static char str[32];
2058 	const char *comm = thread__comm_str(thread);
2059 	pid_t tid = thread__tid(thread);
2060 	pid_t pid = thread__pid(thread);
2061 	int n;
2062 
2063 	if (pid == 0)
2064 		n = scnprintf(str, sizeof(str), "%s", comm);
2065 
2066 	else if (tid != pid)
2067 		n = scnprintf(str, sizeof(str), "%s[%d/%d]", comm, tid, pid);
2068 
2069 	else
2070 		n = scnprintf(str, sizeof(str), "%s[%d]", comm, tid);
2071 
2072 	if (n > comm_width)
2073 		comm_width = n;
2074 
2075 	return str;
2076 }
2077 
2078 /* prio field format: xxx or xxx->yyy */
2079 #define MAX_PRIO_STR_LEN 8
timehist_get_priostr(struct evsel * evsel,struct thread * thread,struct perf_sample * sample)2080 static char *timehist_get_priostr(struct evsel *evsel,
2081 				  struct thread *thread,
2082 				  struct perf_sample *sample)
2083 {
2084 	static char prio_str[16];
2085 	int prev_prio = (int)evsel__intval(evsel, sample, "prev_prio");
2086 	struct thread_runtime *tr = thread__priv(thread);
2087 
2088 	if (tr->prio != prev_prio && tr->prio != -1)
2089 		scnprintf(prio_str, sizeof(prio_str), "%d->%d", tr->prio, prev_prio);
2090 	else
2091 		scnprintf(prio_str, sizeof(prio_str), "%d", prev_prio);
2092 
2093 	return prio_str;
2094 }
2095 
timehist_header(struct perf_sched * sched)2096 static void timehist_header(struct perf_sched *sched)
2097 {
2098 	u32 ncpus = sched->max_cpu.cpu + 1;
2099 	u32 i, j;
2100 
2101 	printf("%15s %6s ", "time", "cpu");
2102 
2103 	if (sched->show_cpu_visual) {
2104 		printf(" ");
2105 		for (i = 0, j = 0; i < ncpus; ++i) {
2106 			printf("%x", j++);
2107 			if (j > 15)
2108 				j = 0;
2109 		}
2110 		printf(" ");
2111 	}
2112 
2113 	if (sched->show_prio) {
2114 		printf(" %-*s  %-*s  %9s  %9s  %9s",
2115 		       comm_width, "task name", MAX_PRIO_STR_LEN, "prio",
2116 		       "wait time", "sch delay", "run time");
2117 	} else {
2118 		printf(" %-*s  %9s  %9s  %9s", comm_width,
2119 		       "task name", "wait time", "sch delay", "run time");
2120 	}
2121 
2122 	if (sched->show_state)
2123 		printf("  %s", "state");
2124 
2125 	printf("\n");
2126 
2127 	/*
2128 	 * units row
2129 	 */
2130 	printf("%15s %-6s ", "", "");
2131 
2132 	if (sched->show_cpu_visual)
2133 		printf(" %*s ", ncpus, "");
2134 
2135 	if (sched->show_prio) {
2136 		printf(" %-*s  %-*s  %9s  %9s  %9s",
2137 		       comm_width, "[tid/pid]", MAX_PRIO_STR_LEN, "",
2138 		       "(msec)", "(msec)", "(msec)");
2139 	} else {
2140 		printf(" %-*s  %9s  %9s  %9s", comm_width,
2141 		       "[tid/pid]", "(msec)", "(msec)", "(msec)");
2142 	}
2143 
2144 	if (sched->show_state)
2145 		printf("  %5s", "");
2146 
2147 	printf("\n");
2148 
2149 	/*
2150 	 * separator
2151 	 */
2152 	printf("%.15s %.6s ", graph_dotted_line, graph_dotted_line);
2153 
2154 	if (sched->show_cpu_visual)
2155 		printf(" %.*s ", ncpus, graph_dotted_line);
2156 
2157 	if (sched->show_prio) {
2158 		printf(" %.*s  %.*s  %.9s  %.9s  %.9s",
2159 		       comm_width, graph_dotted_line, MAX_PRIO_STR_LEN, graph_dotted_line,
2160 		       graph_dotted_line, graph_dotted_line, graph_dotted_line);
2161 	} else {
2162 		printf(" %.*s  %.9s  %.9s  %.9s", comm_width,
2163 		       graph_dotted_line, graph_dotted_line, graph_dotted_line,
2164 		       graph_dotted_line);
2165 	}
2166 
2167 	if (sched->show_state)
2168 		printf("  %.5s", graph_dotted_line);
2169 
2170 	printf("\n");
2171 }
2172 
timehist_print_sample(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct addr_location * al,struct thread * thread,u64 t,const char state)2173 static void timehist_print_sample(struct perf_sched *sched,
2174 				  struct evsel *evsel,
2175 				  struct perf_sample *sample,
2176 				  struct addr_location *al,
2177 				  struct thread *thread,
2178 				  u64 t, const char state)
2179 {
2180 	struct thread_runtime *tr = thread__priv(thread);
2181 	const char *next_comm = evsel__strval(evsel, sample, "next_comm");
2182 	const u32 next_pid = evsel__intval(evsel, sample, "next_pid");
2183 	u32 max_cpus = sched->max_cpu.cpu + 1;
2184 	char tstr[64];
2185 	char nstr[30];
2186 	u64 wait_time;
2187 
2188 	if (cpu_list && !test_bit(sample->cpu, cpu_bitmap))
2189 		return;
2190 
2191 	timestamp__scnprintf_usec(t, tstr, sizeof(tstr));
2192 	printf("%15s [%04d] ", tstr, sample->cpu);
2193 
2194 	if (sched->show_cpu_visual) {
2195 		u32 i;
2196 		char c;
2197 
2198 		printf(" ");
2199 		for (i = 0; i < max_cpus; ++i) {
2200 			/* flag idle times with 'i'; others are sched events */
2201 			if (i == sample->cpu)
2202 				c = (thread__tid(thread) == 0) ? 'i' : 's';
2203 			else
2204 				c = ' ';
2205 			printf("%c", c);
2206 		}
2207 		printf(" ");
2208 	}
2209 
2210 	printf(" %-*s ", comm_width, timehist_get_commstr(thread));
2211 
2212 	if (sched->show_prio)
2213 		printf(" %-*s ", MAX_PRIO_STR_LEN, timehist_get_priostr(evsel, thread, sample));
2214 
2215 	wait_time = tr->dt_sleep + tr->dt_iowait + tr->dt_preempt;
2216 	print_sched_time(wait_time, 6);
2217 
2218 	print_sched_time(tr->dt_delay, 6);
2219 	print_sched_time(tr->dt_run, 6);
2220 
2221 	if (sched->show_state)
2222 		printf(" %5c ", thread__tid(thread) == 0 ? 'I' : state);
2223 
2224 	if (sched->show_next) {
2225 		snprintf(nstr, sizeof(nstr), "next: %s[%d]", next_comm, next_pid);
2226 		printf(" %-*s", comm_width, nstr);
2227 	}
2228 
2229 	if (sched->show_wakeups && !sched->show_next)
2230 		printf("  %-*s", comm_width, "");
2231 
2232 	if (thread__tid(thread) == 0)
2233 		goto out;
2234 
2235 	if (sched->show_callchain)
2236 		printf("  ");
2237 
2238 	sample__fprintf_sym(sample, al, 0,
2239 			    EVSEL__PRINT_SYM | EVSEL__PRINT_ONELINE |
2240 			    EVSEL__PRINT_CALLCHAIN_ARROW |
2241 			    EVSEL__PRINT_SKIP_IGNORED,
2242 			    get_tls_callchain_cursor(), symbol_conf.bt_stop_list,  stdout);
2243 
2244 out:
2245 	printf("\n");
2246 }
2247 
2248 /*
2249  * Explanation of delta-time stats:
2250  *
2251  *            t = time of current schedule out event
2252  *        tprev = time of previous sched out event
2253  *                also time of schedule-in event for current task
2254  *    last_time = time of last sched change event for current task
2255  *                (i.e, time process was last scheduled out)
2256  * ready_to_run = time of wakeup for current task
2257  *
2258  * -----|------------|------------|------------|------
2259  *    last         ready        tprev          t
2260  *    time         to run
2261  *
2262  *      |-------- dt_wait --------|
2263  *                   |- dt_delay -|-- dt_run --|
2264  *
2265  *   dt_run = run time of current task
2266  *  dt_wait = time between last schedule out event for task and tprev
2267  *            represents time spent off the cpu
2268  * dt_delay = time between wakeup and schedule-in of task
2269  */
2270 
timehist_update_runtime_stats(struct thread_runtime * r,u64 t,u64 tprev)2271 static void timehist_update_runtime_stats(struct thread_runtime *r,
2272 					 u64 t, u64 tprev)
2273 {
2274 	r->dt_delay   = 0;
2275 	r->dt_sleep   = 0;
2276 	r->dt_iowait  = 0;
2277 	r->dt_preempt = 0;
2278 	r->dt_run     = 0;
2279 
2280 	if (tprev) {
2281 		r->dt_run = t - tprev;
2282 		if (r->ready_to_run) {
2283 			if (r->ready_to_run > tprev)
2284 				pr_debug("time travel: wakeup time for task > previous sched_switch event\n");
2285 			else
2286 				r->dt_delay = tprev - r->ready_to_run;
2287 		}
2288 
2289 		if (r->last_time > tprev)
2290 			pr_debug("time travel: last sched out time for task > previous sched_switch event\n");
2291 		else if (r->last_time) {
2292 			u64 dt_wait = tprev - r->last_time;
2293 
2294 			if (r->last_state == 'R')
2295 				r->dt_preempt = dt_wait;
2296 			else if (r->last_state == 'D')
2297 				r->dt_iowait = dt_wait;
2298 			else
2299 				r->dt_sleep = dt_wait;
2300 		}
2301 	}
2302 
2303 	update_stats(&r->run_stats, r->dt_run);
2304 
2305 	r->total_run_time     += r->dt_run;
2306 	r->total_delay_time   += r->dt_delay;
2307 	r->total_sleep_time   += r->dt_sleep;
2308 	r->total_iowait_time  += r->dt_iowait;
2309 	r->total_preempt_time += r->dt_preempt;
2310 }
2311 
is_idle_sample(struct perf_sample * sample,struct evsel * evsel)2312 static bool is_idle_sample(struct perf_sample *sample,
2313 			   struct evsel *evsel)
2314 {
2315 	/* pid 0 == swapper == idle task */
2316 	if (evsel__name_is(evsel, "sched:sched_switch"))
2317 		return evsel__intval(evsel, sample, "prev_pid") == 0;
2318 
2319 	return sample->pid == 0;
2320 }
2321 
save_task_callchain(struct perf_sched * sched,struct perf_sample * sample,struct evsel * evsel,struct machine * machine)2322 static void save_task_callchain(struct perf_sched *sched,
2323 				struct perf_sample *sample,
2324 				struct evsel *evsel,
2325 				struct machine *machine)
2326 {
2327 	struct callchain_cursor *cursor;
2328 	struct thread *thread;
2329 
2330 	/* want main thread for process - has maps */
2331 	thread = machine__findnew_thread(machine, sample->pid, sample->pid);
2332 	if (thread == NULL) {
2333 		pr_debug("Failed to get thread for pid %d.\n", sample->pid);
2334 		return;
2335 	}
2336 
2337 	if (!sched->show_callchain || sample->callchain == NULL)
2338 		return;
2339 
2340 	cursor = get_tls_callchain_cursor();
2341 
2342 	if (thread__resolve_callchain(thread, cursor, evsel, sample,
2343 				      NULL, NULL, sched->max_stack + 2) != 0) {
2344 		if (verbose > 0)
2345 			pr_err("Failed to resolve callchain. Skipping\n");
2346 
2347 		return;
2348 	}
2349 
2350 	callchain_cursor_commit(cursor);
2351 
2352 	while (true) {
2353 		struct callchain_cursor_node *node;
2354 		struct symbol *sym;
2355 
2356 		node = callchain_cursor_current(cursor);
2357 		if (node == NULL)
2358 			break;
2359 
2360 		sym = node->ms.sym;
2361 		if (sym) {
2362 			if (!strcmp(sym->name, "schedule") ||
2363 			    !strcmp(sym->name, "__schedule") ||
2364 			    !strcmp(sym->name, "preempt_schedule"))
2365 				sym->ignore = 1;
2366 		}
2367 
2368 		callchain_cursor_advance(cursor);
2369 	}
2370 }
2371 
init_idle_thread(struct thread * thread)2372 static int init_idle_thread(struct thread *thread)
2373 {
2374 	struct idle_thread_runtime *itr;
2375 
2376 	thread__set_comm(thread, idle_comm, 0);
2377 
2378 	itr = zalloc(sizeof(*itr));
2379 	if (itr == NULL)
2380 		return -ENOMEM;
2381 
2382 	init_prio(&itr->tr);
2383 	init_stats(&itr->tr.run_stats);
2384 	callchain_init(&itr->callchain);
2385 	callchain_cursor_reset(&itr->cursor);
2386 	thread__set_priv(thread, itr);
2387 
2388 	return 0;
2389 }
2390 
2391 /*
2392  * Track idle stats per cpu by maintaining a local thread
2393  * struct for the idle task on each cpu.
2394  */
init_idle_threads(int ncpu)2395 static int init_idle_threads(int ncpu)
2396 {
2397 	int i, ret;
2398 
2399 	idle_threads = zalloc(ncpu * sizeof(struct thread *));
2400 	if (!idle_threads)
2401 		return -ENOMEM;
2402 
2403 	idle_max_cpu = ncpu;
2404 
2405 	/* allocate the actual thread struct if needed */
2406 	for (i = 0; i < ncpu; ++i) {
2407 		idle_threads[i] = thread__new(0, 0);
2408 		if (idle_threads[i] == NULL)
2409 			return -ENOMEM;
2410 
2411 		ret = init_idle_thread(idle_threads[i]);
2412 		if (ret < 0)
2413 			return ret;
2414 	}
2415 
2416 	return 0;
2417 }
2418 
free_idle_threads(void)2419 static void free_idle_threads(void)
2420 {
2421 	int i;
2422 
2423 	if (idle_threads == NULL)
2424 		return;
2425 
2426 	for (i = 0; i < idle_max_cpu; ++i) {
2427 		if ((idle_threads[i]))
2428 			thread__delete(idle_threads[i]);
2429 	}
2430 
2431 	free(idle_threads);
2432 }
2433 
get_idle_thread(int cpu)2434 static struct thread *get_idle_thread(int cpu)
2435 {
2436 	/*
2437 	 * expand/allocate array of pointers to local thread
2438 	 * structs if needed
2439 	 */
2440 	if ((cpu >= idle_max_cpu) || (idle_threads == NULL)) {
2441 		int i, j = __roundup_pow_of_two(cpu+1);
2442 		void *p;
2443 
2444 		p = realloc(idle_threads, j * sizeof(struct thread *));
2445 		if (!p)
2446 			return NULL;
2447 
2448 		idle_threads = (struct thread **) p;
2449 		for (i = idle_max_cpu; i < j; ++i)
2450 			idle_threads[i] = NULL;
2451 
2452 		idle_max_cpu = j;
2453 	}
2454 
2455 	/* allocate a new thread struct if needed */
2456 	if (idle_threads[cpu] == NULL) {
2457 		idle_threads[cpu] = thread__new(0, 0);
2458 
2459 		if (idle_threads[cpu]) {
2460 			if (init_idle_thread(idle_threads[cpu]) < 0)
2461 				return NULL;
2462 		}
2463 	}
2464 
2465 	return idle_threads[cpu];
2466 }
2467 
save_idle_callchain(struct perf_sched * sched,struct idle_thread_runtime * itr,struct perf_sample * sample)2468 static void save_idle_callchain(struct perf_sched *sched,
2469 				struct idle_thread_runtime *itr,
2470 				struct perf_sample *sample)
2471 {
2472 	struct callchain_cursor *cursor;
2473 
2474 	if (!sched->show_callchain || sample->callchain == NULL)
2475 		return;
2476 
2477 	cursor = get_tls_callchain_cursor();
2478 	if (cursor == NULL)
2479 		return;
2480 
2481 	callchain_cursor__copy(&itr->cursor, cursor);
2482 }
2483 
timehist_get_thread(struct perf_sched * sched,struct perf_sample * sample,struct machine * machine,struct evsel * evsel)2484 static struct thread *timehist_get_thread(struct perf_sched *sched,
2485 					  struct perf_sample *sample,
2486 					  struct machine *machine,
2487 					  struct evsel *evsel)
2488 {
2489 	struct thread *thread;
2490 
2491 	if (is_idle_sample(sample, evsel)) {
2492 		thread = get_idle_thread(sample->cpu);
2493 		if (thread == NULL)
2494 			pr_err("Failed to get idle thread for cpu %d.\n", sample->cpu);
2495 
2496 	} else {
2497 		/* there were samples with tid 0 but non-zero pid */
2498 		thread = machine__findnew_thread(machine, sample->pid,
2499 						 sample->tid ?: sample->pid);
2500 		if (thread == NULL) {
2501 			pr_debug("Failed to get thread for tid %d. skipping sample.\n",
2502 				 sample->tid);
2503 		}
2504 
2505 		save_task_callchain(sched, sample, evsel, machine);
2506 		if (sched->idle_hist) {
2507 			struct thread *idle;
2508 			struct idle_thread_runtime *itr;
2509 
2510 			idle = get_idle_thread(sample->cpu);
2511 			if (idle == NULL) {
2512 				pr_err("Failed to get idle thread for cpu %d.\n", sample->cpu);
2513 				return NULL;
2514 			}
2515 
2516 			itr = thread__priv(idle);
2517 			if (itr == NULL)
2518 				return NULL;
2519 
2520 			itr->last_thread = thread;
2521 
2522 			/* copy task callchain when entering to idle */
2523 			if (evsel__intval(evsel, sample, "next_pid") == 0)
2524 				save_idle_callchain(sched, itr, sample);
2525 		}
2526 	}
2527 
2528 	return thread;
2529 }
2530 
timehist_skip_sample(struct perf_sched * sched,struct thread * thread,struct evsel * evsel,struct perf_sample * sample)2531 static bool timehist_skip_sample(struct perf_sched *sched,
2532 				 struct thread *thread,
2533 				 struct evsel *evsel,
2534 				 struct perf_sample *sample)
2535 {
2536 	bool rc = false;
2537 	int prio = -1;
2538 	struct thread_runtime *tr = NULL;
2539 
2540 	if (thread__is_filtered(thread)) {
2541 		rc = true;
2542 		sched->skipped_samples++;
2543 	}
2544 
2545 	if (sched->prio_str) {
2546 		/*
2547 		 * Because priority may be changed during task execution,
2548 		 * first read priority from prev sched_in event for current task.
2549 		 * If prev sched_in event is not saved, then read priority from
2550 		 * current task sched_out event.
2551 		 */
2552 		tr = thread__get_runtime(thread);
2553 		if (tr && tr->prio != -1)
2554 			prio = tr->prio;
2555 		else if (evsel__name_is(evsel, "sched:sched_switch"))
2556 			prio = evsel__intval(evsel, sample, "prev_prio");
2557 
2558 		if (prio != -1 && !test_bit(prio, sched->prio_bitmap)) {
2559 			rc = true;
2560 			sched->skipped_samples++;
2561 		}
2562 	}
2563 
2564 	if (sched->idle_hist) {
2565 		if (!evsel__name_is(evsel, "sched:sched_switch"))
2566 			rc = true;
2567 		else if (evsel__intval(evsel, sample, "prev_pid") != 0 &&
2568 			 evsel__intval(evsel, sample, "next_pid") != 0)
2569 			rc = true;
2570 	}
2571 
2572 	return rc;
2573 }
2574 
timehist_print_wakeup_event(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct machine * machine,struct thread * awakened)2575 static void timehist_print_wakeup_event(struct perf_sched *sched,
2576 					struct evsel *evsel,
2577 					struct perf_sample *sample,
2578 					struct machine *machine,
2579 					struct thread *awakened)
2580 {
2581 	struct thread *thread;
2582 	char tstr[64];
2583 
2584 	thread = machine__findnew_thread(machine, sample->pid, sample->tid);
2585 	if (thread == NULL)
2586 		return;
2587 
2588 	/* show wakeup unless both awakee and awaker are filtered */
2589 	if (timehist_skip_sample(sched, thread, evsel, sample) &&
2590 	    timehist_skip_sample(sched, awakened, evsel, sample)) {
2591 		return;
2592 	}
2593 
2594 	timestamp__scnprintf_usec(sample->time, tstr, sizeof(tstr));
2595 	printf("%15s [%04d] ", tstr, sample->cpu);
2596 	if (sched->show_cpu_visual)
2597 		printf(" %*s ", sched->max_cpu.cpu + 1, "");
2598 
2599 	printf(" %-*s ", comm_width, timehist_get_commstr(thread));
2600 
2601 	/* dt spacer */
2602 	printf("  %9s  %9s  %9s ", "", "", "");
2603 
2604 	printf("awakened: %s", timehist_get_commstr(awakened));
2605 
2606 	printf("\n");
2607 }
2608 
timehist_sched_wakeup_ignore(const struct perf_tool * tool __maybe_unused,union perf_event * event __maybe_unused,struct evsel * evsel __maybe_unused,struct perf_sample * sample __maybe_unused,struct machine * machine __maybe_unused)2609 static int timehist_sched_wakeup_ignore(const struct perf_tool *tool __maybe_unused,
2610 					union perf_event *event __maybe_unused,
2611 					struct evsel *evsel __maybe_unused,
2612 					struct perf_sample *sample __maybe_unused,
2613 					struct machine *machine __maybe_unused)
2614 {
2615 	return 0;
2616 }
2617 
timehist_sched_wakeup_event(const struct perf_tool * tool,union perf_event * event __maybe_unused,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)2618 static int timehist_sched_wakeup_event(const struct perf_tool *tool,
2619 				       union perf_event *event __maybe_unused,
2620 				       struct evsel *evsel,
2621 				       struct perf_sample *sample,
2622 				       struct machine *machine)
2623 {
2624 	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
2625 	struct thread *thread;
2626 	struct thread_runtime *tr = NULL;
2627 	/* want pid of awakened task not pid in sample */
2628 	const u32 pid = evsel__intval(evsel, sample, "pid");
2629 
2630 	thread = machine__findnew_thread(machine, 0, pid);
2631 	if (thread == NULL)
2632 		return -1;
2633 
2634 	tr = thread__get_runtime(thread);
2635 	if (tr == NULL)
2636 		return -1;
2637 
2638 	if (tr->ready_to_run == 0)
2639 		tr->ready_to_run = sample->time;
2640 
2641 	/* show wakeups if requested */
2642 	if (sched->show_wakeups &&
2643 	    !perf_time__skip_sample(&sched->ptime, sample->time))
2644 		timehist_print_wakeup_event(sched, evsel, sample, machine, thread);
2645 
2646 	return 0;
2647 }
2648 
timehist_print_migration_event(struct perf_sched * sched,struct evsel * evsel,struct perf_sample * sample,struct machine * machine,struct thread * migrated)2649 static void timehist_print_migration_event(struct perf_sched *sched,
2650 					struct evsel *evsel,
2651 					struct perf_sample *sample,
2652 					struct machine *machine,
2653 					struct thread *migrated)
2654 {
2655 	struct thread *thread;
2656 	char tstr[64];
2657 	u32 max_cpus;
2658 	u32 ocpu, dcpu;
2659 
2660 	if (sched->summary_only)
2661 		return;
2662 
2663 	max_cpus = sched->max_cpu.cpu + 1;
2664 	ocpu = evsel__intval(evsel, sample, "orig_cpu");
2665 	dcpu = evsel__intval(evsel, sample, "dest_cpu");
2666 
2667 	thread = machine__findnew_thread(machine, sample->pid, sample->tid);
2668 	if (thread == NULL)
2669 		return;
2670 
2671 	if (timehist_skip_sample(sched, thread, evsel, sample) &&
2672 	    timehist_skip_sample(sched, migrated, evsel, sample)) {
2673 		return;
2674 	}
2675 
2676 	timestamp__scnprintf_usec(sample->time, tstr, sizeof(tstr));
2677 	printf("%15s [%04d] ", tstr, sample->cpu);
2678 
2679 	if (sched->show_cpu_visual) {
2680 		u32 i;
2681 		char c;
2682 
2683 		printf("  ");
2684 		for (i = 0; i < max_cpus; ++i) {
2685 			c = (i == sample->cpu) ? 'm' : ' ';
2686 			printf("%c", c);
2687 		}
2688 		printf("  ");
2689 	}
2690 
2691 	printf(" %-*s ", comm_width, timehist_get_commstr(thread));
2692 
2693 	/* dt spacer */
2694 	printf("  %9s  %9s  %9s ", "", "", "");
2695 
2696 	printf("migrated: %s", timehist_get_commstr(migrated));
2697 	printf(" cpu %d => %d", ocpu, dcpu);
2698 
2699 	printf("\n");
2700 }
2701 
timehist_migrate_task_event(const struct perf_tool * tool,union perf_event * event __maybe_unused,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)2702 static int timehist_migrate_task_event(const struct perf_tool *tool,
2703 				       union perf_event *event __maybe_unused,
2704 				       struct evsel *evsel,
2705 				       struct perf_sample *sample,
2706 				       struct machine *machine)
2707 {
2708 	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
2709 	struct thread *thread;
2710 	struct thread_runtime *tr = NULL;
2711 	/* want pid of migrated task not pid in sample */
2712 	const u32 pid = evsel__intval(evsel, sample, "pid");
2713 
2714 	thread = machine__findnew_thread(machine, 0, pid);
2715 	if (thread == NULL)
2716 		return -1;
2717 
2718 	tr = thread__get_runtime(thread);
2719 	if (tr == NULL)
2720 		return -1;
2721 
2722 	tr->migrations++;
2723 
2724 	/* show migrations if requested */
2725 	timehist_print_migration_event(sched, evsel, sample, machine, thread);
2726 
2727 	return 0;
2728 }
2729 
timehist_update_task_prio(struct evsel * evsel,struct perf_sample * sample,struct machine * machine)2730 static void timehist_update_task_prio(struct evsel *evsel,
2731 				      struct perf_sample *sample,
2732 				      struct machine *machine)
2733 {
2734 	struct thread *thread;
2735 	struct thread_runtime *tr = NULL;
2736 	const u32 next_pid = evsel__intval(evsel, sample, "next_pid");
2737 	const u32 next_prio = evsel__intval(evsel, sample, "next_prio");
2738 
2739 	if (next_pid == 0)
2740 		thread = get_idle_thread(sample->cpu);
2741 	else
2742 		thread = machine__findnew_thread(machine, -1, next_pid);
2743 
2744 	if (thread == NULL)
2745 		return;
2746 
2747 	tr = thread__get_runtime(thread);
2748 	if (tr == NULL)
2749 		return;
2750 
2751 	tr->prio = next_prio;
2752 }
2753 
timehist_sched_change_event(const struct perf_tool * tool,union perf_event * event,struct evsel * evsel,struct perf_sample * sample,struct machine * machine)2754 static int timehist_sched_change_event(const struct perf_tool *tool,
2755 				       union perf_event *event,
2756 				       struct evsel *evsel,
2757 				       struct perf_sample *sample,
2758 				       struct machine *machine)
2759 {
2760 	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
2761 	struct perf_time_interval *ptime = &sched->ptime;
2762 	struct addr_location al;
2763 	struct thread *thread;
2764 	struct thread_runtime *tr = NULL;
2765 	u64 tprev, t = sample->time;
2766 	int rc = 0;
2767 	const char state = evsel__taskstate(evsel, sample, "prev_state");
2768 
2769 	addr_location__init(&al);
2770 	if (machine__resolve(machine, &al, sample) < 0) {
2771 		pr_err("problem processing %d event. skipping it\n",
2772 		       event->header.type);
2773 		rc = -1;
2774 		goto out;
2775 	}
2776 
2777 	if (sched->show_prio || sched->prio_str)
2778 		timehist_update_task_prio(evsel, sample, machine);
2779 
2780 	thread = timehist_get_thread(sched, sample, machine, evsel);
2781 	if (thread == NULL) {
2782 		rc = -1;
2783 		goto out;
2784 	}
2785 
2786 	if (timehist_skip_sample(sched, thread, evsel, sample))
2787 		goto out;
2788 
2789 	tr = thread__get_runtime(thread);
2790 	if (tr == NULL) {
2791 		rc = -1;
2792 		goto out;
2793 	}
2794 
2795 	tprev = evsel__get_time(evsel, sample->cpu);
2796 
2797 	/*
2798 	 * If start time given:
2799 	 * - sample time is under window user cares about - skip sample
2800 	 * - tprev is under window user cares about  - reset to start of window
2801 	 */
2802 	if (ptime->start && ptime->start > t)
2803 		goto out;
2804 
2805 	if (tprev && ptime->start > tprev)
2806 		tprev = ptime->start;
2807 
2808 	/*
2809 	 * If end time given:
2810 	 * - previous sched event is out of window - we are done
2811 	 * - sample time is beyond window user cares about - reset it
2812 	 *   to close out stats for time window interest
2813 	 * - If tprev is 0, that is, sched_in event for current task is
2814 	 *   not recorded, cannot determine whether sched_in event is
2815 	 *   within time window interest - ignore it
2816 	 */
2817 	if (ptime->end) {
2818 		if (!tprev || tprev > ptime->end)
2819 			goto out;
2820 
2821 		if (t > ptime->end)
2822 			t = ptime->end;
2823 	}
2824 
2825 	if (!sched->idle_hist || thread__tid(thread) == 0) {
2826 		if (!cpu_list || test_bit(sample->cpu, cpu_bitmap))
2827 			timehist_update_runtime_stats(tr, t, tprev);
2828 
2829 		if (sched->idle_hist) {
2830 			struct idle_thread_runtime *itr = (void *)tr;
2831 			struct thread_runtime *last_tr;
2832 
2833 			if (itr->last_thread == NULL)
2834 				goto out;
2835 
2836 			/* add current idle time as last thread's runtime */
2837 			last_tr = thread__get_runtime(itr->last_thread);
2838 			if (last_tr == NULL)
2839 				goto out;
2840 
2841 			timehist_update_runtime_stats(last_tr, t, tprev);
2842 			/*
2843 			 * remove delta time of last thread as it's not updated
2844 			 * and otherwise it will show an invalid value next
2845 			 * time.  we only care total run time and run stat.
2846 			 */
2847 			last_tr->dt_run = 0;
2848 			last_tr->dt_delay = 0;
2849 			last_tr->dt_sleep = 0;
2850 			last_tr->dt_iowait = 0;
2851 			last_tr->dt_preempt = 0;
2852 
2853 			if (itr->cursor.nr)
2854 				callchain_append(&itr->callchain, &itr->cursor, t - tprev);
2855 
2856 			itr->last_thread = NULL;
2857 		}
2858 
2859 		if (!sched->summary_only)
2860 			timehist_print_sample(sched, evsel, sample, &al, thread, t, state);
2861 	}
2862 
2863 out:
2864 	if (sched->hist_time.start == 0 && t >= ptime->start)
2865 		sched->hist_time.start = t;
2866 	if (ptime->end == 0 || t <= ptime->end)
2867 		sched->hist_time.end = t;
2868 
2869 	if (tr) {
2870 		/* time of this sched_switch event becomes last time task seen */
2871 		tr->last_time = sample->time;
2872 
2873 		/* last state is used to determine where to account wait time */
2874 		tr->last_state = state;
2875 
2876 		/* sched out event for task so reset ready to run time */
2877 		if (state == 'R')
2878 			tr->ready_to_run = t;
2879 		else
2880 			tr->ready_to_run = 0;
2881 	}
2882 
2883 	evsel__save_time(evsel, sample->time, sample->cpu);
2884 
2885 	addr_location__exit(&al);
2886 	return rc;
2887 }
2888 
timehist_sched_switch_event(const struct perf_tool * tool,union perf_event * event,struct evsel * evsel,struct perf_sample * sample,struct machine * machine __maybe_unused)2889 static int timehist_sched_switch_event(const struct perf_tool *tool,
2890 			     union perf_event *event,
2891 			     struct evsel *evsel,
2892 			     struct perf_sample *sample,
2893 			     struct machine *machine __maybe_unused)
2894 {
2895 	return timehist_sched_change_event(tool, event, evsel, sample, machine);
2896 }
2897 
process_lost(const struct perf_tool * tool __maybe_unused,union perf_event * event,struct perf_sample * sample,struct machine * machine __maybe_unused)2898 static int process_lost(const struct perf_tool *tool __maybe_unused,
2899 			union perf_event *event,
2900 			struct perf_sample *sample,
2901 			struct machine *machine __maybe_unused)
2902 {
2903 	char tstr[64];
2904 
2905 	timestamp__scnprintf_usec(sample->time, tstr, sizeof(tstr));
2906 	printf("%15s ", tstr);
2907 	printf("lost %" PRI_lu64 " events on cpu %d\n", event->lost.lost, sample->cpu);
2908 
2909 	return 0;
2910 }
2911 
2912 
print_thread_runtime(struct thread * t,struct thread_runtime * r)2913 static void print_thread_runtime(struct thread *t,
2914 				 struct thread_runtime *r)
2915 {
2916 	double mean = avg_stats(&r->run_stats);
2917 	float stddev;
2918 
2919 	printf("%*s   %5d  %9" PRIu64 " ",
2920 	       comm_width, timehist_get_commstr(t), thread__ppid(t),
2921 	       (u64) r->run_stats.n);
2922 
2923 	print_sched_time(r->total_run_time, 8);
2924 	stddev = rel_stddev_stats(stddev_stats(&r->run_stats), mean);
2925 	print_sched_time(r->run_stats.min, 6);
2926 	printf(" ");
2927 	print_sched_time((u64) mean, 6);
2928 	printf(" ");
2929 	print_sched_time(r->run_stats.max, 6);
2930 	printf("  ");
2931 	printf("%5.2f", stddev);
2932 	printf("   %5" PRIu64, r->migrations);
2933 	printf("\n");
2934 }
2935 
print_thread_waittime(struct thread * t,struct thread_runtime * r)2936 static void print_thread_waittime(struct thread *t,
2937 				  struct thread_runtime *r)
2938 {
2939 	printf("%*s   %5d  %9" PRIu64 " ",
2940 	       comm_width, timehist_get_commstr(t), thread__ppid(t),
2941 	       (u64) r->run_stats.n);
2942 
2943 	print_sched_time(r->total_run_time, 8);
2944 	print_sched_time(r->total_sleep_time, 6);
2945 	printf(" ");
2946 	print_sched_time(r->total_iowait_time, 6);
2947 	printf(" ");
2948 	print_sched_time(r->total_preempt_time, 6);
2949 	printf(" ");
2950 	print_sched_time(r->total_delay_time, 6);
2951 	printf("\n");
2952 }
2953 
2954 struct total_run_stats {
2955 	struct perf_sched *sched;
2956 	u64  sched_count;
2957 	u64  task_count;
2958 	u64  total_run_time;
2959 };
2960 
show_thread_runtime(struct thread * t,void * priv)2961 static int show_thread_runtime(struct thread *t, void *priv)
2962 {
2963 	struct total_run_stats *stats = priv;
2964 	struct thread_runtime *r;
2965 
2966 	if (thread__is_filtered(t))
2967 		return 0;
2968 
2969 	r = thread__priv(t);
2970 	if (r && r->run_stats.n) {
2971 		stats->task_count++;
2972 		stats->sched_count += r->run_stats.n;
2973 		stats->total_run_time += r->total_run_time;
2974 
2975 		if (stats->sched->show_state)
2976 			print_thread_waittime(t, r);
2977 		else
2978 			print_thread_runtime(t, r);
2979 	}
2980 
2981 	return 0;
2982 }
2983 
callchain__fprintf_folded(FILE * fp,struct callchain_node * node)2984 static size_t callchain__fprintf_folded(FILE *fp, struct callchain_node *node)
2985 {
2986 	const char *sep = " <- ";
2987 	struct callchain_list *chain;
2988 	size_t ret = 0;
2989 	char bf[1024];
2990 	bool first;
2991 
2992 	if (node == NULL)
2993 		return 0;
2994 
2995 	ret = callchain__fprintf_folded(fp, node->parent);
2996 	first = (ret == 0);
2997 
2998 	list_for_each_entry(chain, &node->val, list) {
2999 		if (chain->ip >= PERF_CONTEXT_MAX)
3000 			continue;
3001 		if (chain->ms.sym && chain->ms.sym->ignore)
3002 			continue;
3003 		ret += fprintf(fp, "%s%s", first ? "" : sep,
3004 			       callchain_list__sym_name(chain, bf, sizeof(bf),
3005 							false));
3006 		first = false;
3007 	}
3008 
3009 	return ret;
3010 }
3011 
timehist_print_idlehist_callchain(struct rb_root_cached * root)3012 static size_t timehist_print_idlehist_callchain(struct rb_root_cached *root)
3013 {
3014 	size_t ret = 0;
3015 	FILE *fp = stdout;
3016 	struct callchain_node *chain;
3017 	struct rb_node *rb_node = rb_first_cached(root);
3018 
3019 	printf("  %16s  %8s  %s\n", "Idle time (msec)", "Count", "Callchains");
3020 	printf("  %.16s  %.8s  %.50s\n", graph_dotted_line, graph_dotted_line,
3021 	       graph_dotted_line);
3022 
3023 	while (rb_node) {
3024 		chain = rb_entry(rb_node, struct callchain_node, rb_node);
3025 		rb_node = rb_next(rb_node);
3026 
3027 		ret += fprintf(fp, "  ");
3028 		print_sched_time(chain->hit, 12);
3029 		ret += 16;  /* print_sched_time returns 2nd arg + 4 */
3030 		ret += fprintf(fp, " %8d  ", chain->count);
3031 		ret += callchain__fprintf_folded(fp, chain);
3032 		ret += fprintf(fp, "\n");
3033 	}
3034 
3035 	return ret;
3036 }
3037 
timehist_print_summary(struct perf_sched * sched,struct perf_session * session)3038 static void timehist_print_summary(struct perf_sched *sched,
3039 				   struct perf_session *session)
3040 {
3041 	struct machine *m = &session->machines.host;
3042 	struct total_run_stats totals;
3043 	u64 task_count;
3044 	struct thread *t;
3045 	struct thread_runtime *r;
3046 	int i;
3047 	u64 hist_time = sched->hist_time.end - sched->hist_time.start;
3048 
3049 	memset(&totals, 0, sizeof(totals));
3050 	totals.sched = sched;
3051 
3052 	if (sched->idle_hist) {
3053 		printf("\nIdle-time summary\n");
3054 		printf("%*s  parent  sched-out  ", comm_width, "comm");
3055 		printf("  idle-time   min-idle    avg-idle    max-idle  stddev  migrations\n");
3056 	} else if (sched->show_state) {
3057 		printf("\nWait-time summary\n");
3058 		printf("%*s  parent   sched-in  ", comm_width, "comm");
3059 		printf("   run-time      sleep      iowait     preempt       delay\n");
3060 	} else {
3061 		printf("\nRuntime summary\n");
3062 		printf("%*s  parent   sched-in  ", comm_width, "comm");
3063 		printf("   run-time    min-run     avg-run     max-run  stddev  migrations\n");
3064 	}
3065 	printf("%*s            (count)  ", comm_width, "");
3066 	printf("     (msec)     (msec)      (msec)      (msec)       %s\n",
3067 	       sched->show_state ? "(msec)" : "%");
3068 	printf("%.117s\n", graph_dotted_line);
3069 
3070 	machine__for_each_thread(m, show_thread_runtime, &totals);
3071 	task_count = totals.task_count;
3072 	if (!task_count)
3073 		printf("<no still running tasks>\n");
3074 
3075 	/* CPU idle stats not tracked when samples were skipped */
3076 	if (sched->skipped_samples && !sched->idle_hist)
3077 		return;
3078 
3079 	printf("\nIdle stats:\n");
3080 	for (i = 0; i < idle_max_cpu; ++i) {
3081 		if (cpu_list && !test_bit(i, cpu_bitmap))
3082 			continue;
3083 
3084 		t = idle_threads[i];
3085 		if (!t)
3086 			continue;
3087 
3088 		r = thread__priv(t);
3089 		if (r && r->run_stats.n) {
3090 			totals.sched_count += r->run_stats.n;
3091 			printf("    CPU %2d idle for ", i);
3092 			print_sched_time(r->total_run_time, 6);
3093 			printf(" msec  (%6.2f%%)\n", 100.0 * r->total_run_time / hist_time);
3094 		} else
3095 			printf("    CPU %2d idle entire time window\n", i);
3096 	}
3097 
3098 	if (sched->idle_hist && sched->show_callchain) {
3099 		callchain_param.mode  = CHAIN_FOLDED;
3100 		callchain_param.value = CCVAL_PERIOD;
3101 
3102 		callchain_register_param(&callchain_param);
3103 
3104 		printf("\nIdle stats by callchain:\n");
3105 		for (i = 0; i < idle_max_cpu; ++i) {
3106 			struct idle_thread_runtime *itr;
3107 
3108 			t = idle_threads[i];
3109 			if (!t)
3110 				continue;
3111 
3112 			itr = thread__priv(t);
3113 			if (itr == NULL)
3114 				continue;
3115 
3116 			callchain_param.sort(&itr->sorted_root.rb_root, &itr->callchain,
3117 					     0, &callchain_param);
3118 
3119 			printf("  CPU %2d:", i);
3120 			print_sched_time(itr->tr.total_run_time, 6);
3121 			printf(" msec\n");
3122 			timehist_print_idlehist_callchain(&itr->sorted_root);
3123 			printf("\n");
3124 		}
3125 	}
3126 
3127 	printf("\n"
3128 	       "    Total number of unique tasks: %" PRIu64 "\n"
3129 	       "Total number of context switches: %" PRIu64 "\n",
3130 	       totals.task_count, totals.sched_count);
3131 
3132 	printf("           Total run time (msec): ");
3133 	print_sched_time(totals.total_run_time, 2);
3134 	printf("\n");
3135 
3136 	printf("    Total scheduling time (msec): ");
3137 	print_sched_time(hist_time, 2);
3138 	printf(" (x %d)\n", sched->max_cpu.cpu);
3139 }
3140 
3141 typedef int (*sched_handler)(const struct perf_tool *tool,
3142 			  union perf_event *event,
3143 			  struct evsel *evsel,
3144 			  struct perf_sample *sample,
3145 			  struct machine *machine);
3146 
perf_timehist__process_sample(const struct perf_tool * tool,union perf_event * event,struct perf_sample * sample,struct evsel * evsel,struct machine * machine)3147 static int perf_timehist__process_sample(const struct perf_tool *tool,
3148 					 union perf_event *event,
3149 					 struct perf_sample *sample,
3150 					 struct evsel *evsel,
3151 					 struct machine *machine)
3152 {
3153 	struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
3154 	int err = 0;
3155 	struct perf_cpu this_cpu = {
3156 		.cpu = sample->cpu,
3157 	};
3158 
3159 	if (this_cpu.cpu > sched->max_cpu.cpu)
3160 		sched->max_cpu = this_cpu;
3161 
3162 	if (evsel->handler != NULL) {
3163 		sched_handler f = evsel->handler;
3164 
3165 		err = f(tool, event, evsel, sample, machine);
3166 	}
3167 
3168 	return err;
3169 }
3170 
timehist_check_attr(struct perf_sched * sched,struct evlist * evlist)3171 static int timehist_check_attr(struct perf_sched *sched,
3172 			       struct evlist *evlist)
3173 {
3174 	struct evsel *evsel;
3175 	struct evsel_runtime *er;
3176 
3177 	list_for_each_entry(evsel, &evlist->core.entries, core.node) {
3178 		er = evsel__get_runtime(evsel);
3179 		if (er == NULL) {
3180 			pr_err("Failed to allocate memory for evsel runtime data\n");
3181 			return -1;
3182 		}
3183 
3184 		/* only need to save callchain related to sched_switch event */
3185 		if (sched->show_callchain &&
3186 		    evsel__name_is(evsel, "sched:sched_switch") &&
3187 		    !evsel__has_callchain(evsel)) {
3188 			pr_info("Samples of sched_switch event do not have callchains.\n");
3189 			sched->show_callchain = 0;
3190 			symbol_conf.use_callchain = 0;
3191 		}
3192 	}
3193 
3194 	return 0;
3195 }
3196 
timehist_parse_prio_str(struct perf_sched * sched)3197 static int timehist_parse_prio_str(struct perf_sched *sched)
3198 {
3199 	char *p;
3200 	unsigned long start_prio, end_prio;
3201 	const char *str = sched->prio_str;
3202 
3203 	if (!str)
3204 		return 0;
3205 
3206 	while (isdigit(*str)) {
3207 		p = NULL;
3208 		start_prio = strtoul(str, &p, 0);
3209 		if (start_prio >= MAX_PRIO || (*p != '\0' && *p != ',' && *p != '-'))
3210 			return -1;
3211 
3212 		if (*p == '-') {
3213 			str = ++p;
3214 			p = NULL;
3215 			end_prio = strtoul(str, &p, 0);
3216 
3217 			if (end_prio >= MAX_PRIO || (*p != '\0' && *p != ','))
3218 				return -1;
3219 
3220 			if (end_prio < start_prio)
3221 				return -1;
3222 		} else {
3223 			end_prio = start_prio;
3224 		}
3225 
3226 		for (; start_prio <= end_prio; start_prio++)
3227 			__set_bit(start_prio, sched->prio_bitmap);
3228 
3229 		if (*p)
3230 			++p;
3231 
3232 		str = p;
3233 	}
3234 
3235 	return 0;
3236 }
3237 
perf_sched__timehist(struct perf_sched * sched)3238 static int perf_sched__timehist(struct perf_sched *sched)
3239 {
3240 	struct evsel_str_handler handlers[] = {
3241 		{ "sched:sched_switch",       timehist_sched_switch_event, },
3242 		{ "sched:sched_wakeup",	      timehist_sched_wakeup_event, },
3243 		{ "sched:sched_waking",       timehist_sched_wakeup_event, },
3244 		{ "sched:sched_wakeup_new",   timehist_sched_wakeup_event, },
3245 	};
3246 	const struct evsel_str_handler migrate_handlers[] = {
3247 		{ "sched:sched_migrate_task", timehist_migrate_task_event, },
3248 	};
3249 	struct perf_data data = {
3250 		.path  = input_name,
3251 		.mode  = PERF_DATA_MODE_READ,
3252 		.force = sched->force,
3253 	};
3254 
3255 	struct perf_session *session;
3256 	struct evlist *evlist;
3257 	int err = -1;
3258 
3259 	/*
3260 	 * event handlers for timehist option
3261 	 */
3262 	sched->tool.sample	 = perf_timehist__process_sample;
3263 	sched->tool.mmap	 = perf_event__process_mmap;
3264 	sched->tool.comm	 = perf_event__process_comm;
3265 	sched->tool.exit	 = perf_event__process_exit;
3266 	sched->tool.fork	 = perf_event__process_fork;
3267 	sched->tool.lost	 = process_lost;
3268 	sched->tool.attr	 = perf_event__process_attr;
3269 	sched->tool.tracing_data = perf_event__process_tracing_data;
3270 	sched->tool.build_id	 = perf_event__process_build_id;
3271 
3272 	sched->tool.ordering_requires_timestamps = true;
3273 
3274 	symbol_conf.use_callchain = sched->show_callchain;
3275 
3276 	session = perf_session__new(&data, &sched->tool);
3277 	if (IS_ERR(session))
3278 		return PTR_ERR(session);
3279 
3280 	if (cpu_list) {
3281 		err = perf_session__cpu_bitmap(session, cpu_list, cpu_bitmap);
3282 		if (err < 0)
3283 			goto out;
3284 	}
3285 
3286 	evlist = session->evlist;
3287 
3288 	symbol__init(&session->header.env);
3289 
3290 	if (perf_time__parse_str(&sched->ptime, sched->time_str) != 0) {
3291 		pr_err("Invalid time string\n");
3292 		err = -EINVAL;
3293 		goto out;
3294 	}
3295 
3296 	if (timehist_check_attr(sched, evlist) != 0)
3297 		goto out;
3298 
3299 	if (timehist_parse_prio_str(sched) != 0) {
3300 		pr_err("Invalid prio string\n");
3301 		goto out;
3302 	}
3303 
3304 	setup_pager();
3305 
3306 	evsel__set_priv_destructor(timehist__evsel_priv_destructor);
3307 
3308 	/* prefer sched_waking if it is captured */
3309 	if (evlist__find_tracepoint_by_name(session->evlist, "sched:sched_waking"))
3310 		handlers[1].handler = timehist_sched_wakeup_ignore;
3311 
3312 	/* setup per-evsel handlers */
3313 	if (perf_session__set_tracepoints_handlers(session, handlers))
3314 		goto out;
3315 
3316 	/* sched_switch event at a minimum needs to exist */
3317 	if (!evlist__find_tracepoint_by_name(session->evlist, "sched:sched_switch")) {
3318 		pr_err("No sched_switch events found. Have you run 'perf sched record'?\n");
3319 		goto out;
3320 	}
3321 
3322 	if (sched->show_migrations &&
3323 	    perf_session__set_tracepoints_handlers(session, migrate_handlers))
3324 		goto out;
3325 
3326 	/* pre-allocate struct for per-CPU idle stats */
3327 	sched->max_cpu.cpu = session->header.env.nr_cpus_online;
3328 	if (sched->max_cpu.cpu == 0)
3329 		sched->max_cpu.cpu = 4;
3330 	if (init_idle_threads(sched->max_cpu.cpu))
3331 		goto out;
3332 
3333 	/* summary_only implies summary option, but don't overwrite summary if set */
3334 	if (sched->summary_only)
3335 		sched->summary = sched->summary_only;
3336 
3337 	if (!sched->summary_only)
3338 		timehist_header(sched);
3339 
3340 	err = perf_session__process_events(session);
3341 	if (err) {
3342 		pr_err("Failed to process events, error %d", err);
3343 		goto out;
3344 	}
3345 
3346 	sched->nr_events      = evlist->stats.nr_events[0];
3347 	sched->nr_lost_events = evlist->stats.total_lost;
3348 	sched->nr_lost_chunks = evlist->stats.nr_events[PERF_RECORD_LOST];
3349 
3350 	if (sched->summary)
3351 		timehist_print_summary(sched, session);
3352 
3353 out:
3354 	free_idle_threads();
3355 	perf_session__delete(session);
3356 
3357 	return err;
3358 }
3359 
3360 
print_bad_events(struct perf_sched * sched)3361 static void print_bad_events(struct perf_sched *sched)
3362 {
3363 	if (sched->nr_unordered_timestamps && sched->nr_timestamps) {
3364 		printf("  INFO: %.3f%% unordered timestamps (%ld out of %ld)\n",
3365 			(double)sched->nr_unordered_timestamps/(double)sched->nr_timestamps*100.0,
3366 			sched->nr_unordered_timestamps, sched->nr_timestamps);
3367 	}
3368 	if (sched->nr_lost_events && sched->nr_events) {
3369 		printf("  INFO: %.3f%% lost events (%ld out of %ld, in %ld chunks)\n",
3370 			(double)sched->nr_lost_events/(double)sched->nr_events * 100.0,
3371 			sched->nr_lost_events, sched->nr_events, sched->nr_lost_chunks);
3372 	}
3373 	if (sched->nr_context_switch_bugs && sched->nr_timestamps) {
3374 		printf("  INFO: %.3f%% context switch bugs (%ld out of %ld)",
3375 			(double)sched->nr_context_switch_bugs/(double)sched->nr_timestamps*100.0,
3376 			sched->nr_context_switch_bugs, sched->nr_timestamps);
3377 		if (sched->nr_lost_events)
3378 			printf(" (due to lost events?)");
3379 		printf("\n");
3380 	}
3381 }
3382 
__merge_work_atoms(struct rb_root_cached * root,struct work_atoms * data)3383 static void __merge_work_atoms(struct rb_root_cached *root, struct work_atoms *data)
3384 {
3385 	struct rb_node **new = &(root->rb_root.rb_node), *parent = NULL;
3386 	struct work_atoms *this;
3387 	const char *comm = thread__comm_str(data->thread), *this_comm;
3388 	bool leftmost = true;
3389 
3390 	while (*new) {
3391 		int cmp;
3392 
3393 		this = container_of(*new, struct work_atoms, node);
3394 		parent = *new;
3395 
3396 		this_comm = thread__comm_str(this->thread);
3397 		cmp = strcmp(comm, this_comm);
3398 		if (cmp > 0) {
3399 			new = &((*new)->rb_left);
3400 		} else if (cmp < 0) {
3401 			new = &((*new)->rb_right);
3402 			leftmost = false;
3403 		} else {
3404 			this->num_merged++;
3405 			this->total_runtime += data->total_runtime;
3406 			this->nb_atoms += data->nb_atoms;
3407 			this->total_lat += data->total_lat;
3408 			list_splice_init(&data->work_list, &this->work_list);
3409 			if (this->max_lat < data->max_lat) {
3410 				this->max_lat = data->max_lat;
3411 				this->max_lat_start = data->max_lat_start;
3412 				this->max_lat_end = data->max_lat_end;
3413 			}
3414 			free_work_atoms(data);
3415 			return;
3416 		}
3417 	}
3418 
3419 	data->num_merged++;
3420 	rb_link_node(&data->node, parent, new);
3421 	rb_insert_color_cached(&data->node, root, leftmost);
3422 }
3423 
perf_sched__merge_lat(struct perf_sched * sched)3424 static void perf_sched__merge_lat(struct perf_sched *sched)
3425 {
3426 	struct work_atoms *data;
3427 	struct rb_node *node;
3428 
3429 	if (sched->skip_merge)
3430 		return;
3431 
3432 	while ((node = rb_first_cached(&sched->atom_root))) {
3433 		rb_erase_cached(node, &sched->atom_root);
3434 		data = rb_entry(node, struct work_atoms, node);
3435 		__merge_work_atoms(&sched->merged_atom_root, data);
3436 	}
3437 }
3438 
setup_cpus_switch_event(struct perf_sched * sched)3439 static int setup_cpus_switch_event(struct perf_sched *sched)
3440 {
3441 	unsigned int i;
3442 
3443 	sched->cpu_last_switched = calloc(MAX_CPUS, sizeof(*(sched->cpu_last_switched)));
3444 	if (!sched->cpu_last_switched)
3445 		return -1;
3446 
3447 	sched->curr_pid = malloc(MAX_CPUS * sizeof(*(sched->curr_pid)));
3448 	if (!sched->curr_pid) {
3449 		zfree(&sched->cpu_last_switched);
3450 		return -1;
3451 	}
3452 
3453 	for (i = 0; i < MAX_CPUS; i++)
3454 		sched->curr_pid[i] = -1;
3455 
3456 	return 0;
3457 }
3458 
free_cpus_switch_event(struct perf_sched * sched)3459 static void free_cpus_switch_event(struct perf_sched *sched)
3460 {
3461 	zfree(&sched->curr_pid);
3462 	zfree(&sched->cpu_last_switched);
3463 }
3464 
perf_sched__lat(struct perf_sched * sched)3465 static int perf_sched__lat(struct perf_sched *sched)
3466 {
3467 	int rc = -1;
3468 	struct rb_node *next;
3469 
3470 	setup_pager();
3471 
3472 	if (setup_cpus_switch_event(sched))
3473 		return rc;
3474 
3475 	if (perf_sched__read_events(sched))
3476 		goto out_free_cpus_switch_event;
3477 
3478 	perf_sched__merge_lat(sched);
3479 	perf_sched__sort_lat(sched);
3480 
3481 	printf("\n -------------------------------------------------------------------------------------------------------------------------------------------\n");
3482 	printf("  Task                  |   Runtime ms  |  Count   | Avg delay ms    | Max delay ms    | Max delay start           | Max delay end          |\n");
3483 	printf(" -------------------------------------------------------------------------------------------------------------------------------------------\n");
3484 
3485 	next = rb_first_cached(&sched->sorted_atom_root);
3486 
3487 	while (next) {
3488 		struct work_atoms *work_list;
3489 
3490 		work_list = rb_entry(next, struct work_atoms, node);
3491 		output_lat_thread(sched, work_list);
3492 		next = rb_next(next);
3493 	}
3494 
3495 	printf(" -----------------------------------------------------------------------------------------------------------------\n");
3496 	printf("  TOTAL:                |%11.3f ms |%9" PRIu64 " |\n",
3497 		(double)sched->all_runtime / NSEC_PER_MSEC, sched->all_count);
3498 
3499 	printf(" ---------------------------------------------------\n");
3500 
3501 	print_bad_events(sched);
3502 	printf("\n");
3503 
3504 	rc = 0;
3505 
3506 	while ((next = rb_first_cached(&sched->sorted_atom_root))) {
3507 		struct work_atoms *data;
3508 
3509 		data = rb_entry(next, struct work_atoms, node);
3510 		rb_erase_cached(next, &sched->sorted_atom_root);
3511 		free_work_atoms(data);
3512 	}
3513 out_free_cpus_switch_event:
3514 	free_cpus_switch_event(sched);
3515 	return rc;
3516 }
3517 
setup_map_cpus(struct perf_sched * sched)3518 static int setup_map_cpus(struct perf_sched *sched)
3519 {
3520 	sched->max_cpu.cpu  = sysconf(_SC_NPROCESSORS_CONF);
3521 
3522 	if (sched->map.comp) {
3523 		sched->map.comp_cpus = zalloc(sched->max_cpu.cpu * sizeof(int));
3524 		if (!sched->map.comp_cpus)
3525 			return -1;
3526 	}
3527 
3528 	if (sched->map.cpus_str) {
3529 		sched->map.cpus = perf_cpu_map__new(sched->map.cpus_str);
3530 		if (!sched->map.cpus) {
3531 			pr_err("failed to get cpus map from %s\n", sched->map.cpus_str);
3532 			zfree(&sched->map.comp_cpus);
3533 			return -1;
3534 		}
3535 	}
3536 
3537 	return 0;
3538 }
3539 
setup_color_pids(struct perf_sched * sched)3540 static int setup_color_pids(struct perf_sched *sched)
3541 {
3542 	struct perf_thread_map *map;
3543 
3544 	if (!sched->map.color_pids_str)
3545 		return 0;
3546 
3547 	map = thread_map__new_by_tid_str(sched->map.color_pids_str);
3548 	if (!map) {
3549 		pr_err("failed to get thread map from %s\n", sched->map.color_pids_str);
3550 		return -1;
3551 	}
3552 
3553 	sched->map.color_pids = map;
3554 	return 0;
3555 }
3556 
setup_color_cpus(struct perf_sched * sched)3557 static int setup_color_cpus(struct perf_sched *sched)
3558 {
3559 	struct perf_cpu_map *map;
3560 
3561 	if (!sched->map.color_cpus_str)
3562 		return 0;
3563 
3564 	map = perf_cpu_map__new(sched->map.color_cpus_str);
3565 	if (!map) {
3566 		pr_err("failed to get thread map from %s\n", sched->map.color_cpus_str);
3567 		return -1;
3568 	}
3569 
3570 	sched->map.color_cpus = map;
3571 	return 0;
3572 }
3573 
perf_sched__map(struct perf_sched * sched)3574 static int perf_sched__map(struct perf_sched *sched)
3575 {
3576 	int rc = -1;
3577 
3578 	sched->curr_thread = calloc(MAX_CPUS, sizeof(*(sched->curr_thread)));
3579 	if (!sched->curr_thread)
3580 		return rc;
3581 
3582 	sched->curr_out_thread = calloc(MAX_CPUS, sizeof(*(sched->curr_out_thread)));
3583 	if (!sched->curr_out_thread)
3584 		goto out_free_curr_thread;
3585 
3586 	if (setup_cpus_switch_event(sched))
3587 		goto out_free_curr_out_thread;
3588 
3589 	if (setup_map_cpus(sched))
3590 		goto out_free_cpus_switch_event;
3591 
3592 	if (setup_color_pids(sched))
3593 		goto out_put_map_cpus;
3594 
3595 	if (setup_color_cpus(sched))
3596 		goto out_put_color_pids;
3597 
3598 	setup_pager();
3599 	if (perf_sched__read_events(sched))
3600 		goto out_put_color_cpus;
3601 
3602 	rc = 0;
3603 	print_bad_events(sched);
3604 
3605 out_put_color_cpus:
3606 	perf_cpu_map__put(sched->map.color_cpus);
3607 
3608 out_put_color_pids:
3609 	perf_thread_map__put(sched->map.color_pids);
3610 
3611 out_put_map_cpus:
3612 	zfree(&sched->map.comp_cpus);
3613 	perf_cpu_map__put(sched->map.cpus);
3614 
3615 out_free_cpus_switch_event:
3616 	free_cpus_switch_event(sched);
3617 
3618 out_free_curr_out_thread:
3619 	for (int i = 0; i < MAX_CPUS; i++)
3620 		thread__put(sched->curr_out_thread[i]);
3621 	zfree(&sched->curr_out_thread);
3622 
3623 out_free_curr_thread:
3624 	for (int i = 0; i < MAX_CPUS; i++)
3625 		thread__put(sched->curr_thread[i]);
3626 	zfree(&sched->curr_thread);
3627 	return rc;
3628 }
3629 
perf_sched__replay(struct perf_sched * sched)3630 static int perf_sched__replay(struct perf_sched *sched)
3631 {
3632 	int ret;
3633 	unsigned long i;
3634 
3635 	mutex_init(&sched->start_work_mutex);
3636 	mutex_init(&sched->work_done_wait_mutex);
3637 
3638 	ret = setup_cpus_switch_event(sched);
3639 	if (ret)
3640 		goto out_mutex_destroy;
3641 
3642 	calibrate_run_measurement_overhead(sched);
3643 	calibrate_sleep_measurement_overhead(sched);
3644 
3645 	test_calibrations(sched);
3646 
3647 	ret = perf_sched__read_events(sched);
3648 	if (ret)
3649 		goto out_free_cpus_switch_event;
3650 
3651 	printf("nr_run_events:        %ld\n", sched->nr_run_events);
3652 	printf("nr_sleep_events:      %ld\n", sched->nr_sleep_events);
3653 	printf("nr_wakeup_events:     %ld\n", sched->nr_wakeup_events);
3654 
3655 	if (sched->targetless_wakeups)
3656 		printf("target-less wakeups:  %ld\n", sched->targetless_wakeups);
3657 	if (sched->multitarget_wakeups)
3658 		printf("multi-target wakeups: %ld\n", sched->multitarget_wakeups);
3659 	if (sched->nr_run_events_optimized)
3660 		printf("run atoms optimized: %ld\n",
3661 			sched->nr_run_events_optimized);
3662 
3663 	print_task_traces(sched);
3664 	add_cross_task_wakeups(sched);
3665 
3666 	sched->thread_funcs_exit = false;
3667 	create_tasks(sched);
3668 	printf("------------------------------------------------------------\n");
3669 	if (sched->replay_repeat == 0)
3670 		sched->replay_repeat = UINT_MAX;
3671 
3672 	for (i = 0; i < sched->replay_repeat; i++)
3673 		run_one_test(sched);
3674 
3675 	sched->thread_funcs_exit = true;
3676 	destroy_tasks(sched);
3677 
3678 out_free_cpus_switch_event:
3679 	free_cpus_switch_event(sched);
3680 
3681 out_mutex_destroy:
3682 	mutex_destroy(&sched->start_work_mutex);
3683 	mutex_destroy(&sched->work_done_wait_mutex);
3684 	return ret;
3685 }
3686 
setup_sorting(struct perf_sched * sched,const struct option * options,const char * const usage_msg[])3687 static void setup_sorting(struct perf_sched *sched, const struct option *options,
3688 			  const char * const usage_msg[])
3689 {
3690 	char *tmp, *tok, *str = strdup(sched->sort_order);
3691 
3692 	for (tok = strtok_r(str, ", ", &tmp);
3693 			tok; tok = strtok_r(NULL, ", ", &tmp)) {
3694 		if (sort_dimension__add(tok, &sched->sort_list) < 0) {
3695 			usage_with_options_msg(usage_msg, options,
3696 					"Unknown --sort key: `%s'", tok);
3697 		}
3698 	}
3699 
3700 	free(str);
3701 
3702 	sort_dimension__add("pid", &sched->cmp_pid);
3703 }
3704 
schedstat_events_exposed(void)3705 static bool schedstat_events_exposed(void)
3706 {
3707 	/*
3708 	 * Select "sched:sched_stat_wait" event to check
3709 	 * whether schedstat tracepoints are exposed.
3710 	 */
3711 	return IS_ERR(trace_event__tp_format("sched", "sched_stat_wait")) ?
3712 		false : true;
3713 }
3714 
__cmd_record(int argc,const char ** argv)3715 static int __cmd_record(int argc, const char **argv)
3716 {
3717 	unsigned int rec_argc, i, j;
3718 	char **rec_argv;
3719 	const char **rec_argv_copy;
3720 	const char * const record_args[] = {
3721 		"record",
3722 		"-a",
3723 		"-R",
3724 		"-m", "1024",
3725 		"-c", "1",
3726 		"-e", "sched:sched_switch",
3727 		"-e", "sched:sched_stat_runtime",
3728 		"-e", "sched:sched_process_fork",
3729 		"-e", "sched:sched_wakeup_new",
3730 		"-e", "sched:sched_migrate_task",
3731 	};
3732 
3733 	/*
3734 	 * The tracepoints trace_sched_stat_{wait, sleep, iowait}
3735 	 * are not exposed to user if CONFIG_SCHEDSTATS is not set,
3736 	 * to prevent "perf sched record" execution failure, determine
3737 	 * whether to record schedstat events according to actual situation.
3738 	 */
3739 	const char * const schedstat_args[] = {
3740 		"-e", "sched:sched_stat_wait",
3741 		"-e", "sched:sched_stat_sleep",
3742 		"-e", "sched:sched_stat_iowait",
3743 	};
3744 	unsigned int schedstat_argc = schedstat_events_exposed() ?
3745 		ARRAY_SIZE(schedstat_args) : 0;
3746 
3747 	struct tep_event *waking_event;
3748 	int ret;
3749 
3750 	/*
3751 	 * +2 for either "-e", "sched:sched_wakeup" or
3752 	 * "-e", "sched:sched_waking"
3753 	 */
3754 	rec_argc = ARRAY_SIZE(record_args) + 2 + schedstat_argc + argc - 1;
3755 	rec_argv = calloc(rec_argc + 1, sizeof(char *));
3756 	if (rec_argv == NULL)
3757 		return -ENOMEM;
3758 	rec_argv_copy = calloc(rec_argc + 1, sizeof(char *));
3759 	if (rec_argv_copy == NULL) {
3760 		free(rec_argv);
3761 		return -ENOMEM;
3762 	}
3763 
3764 	for (i = 0; i < ARRAY_SIZE(record_args); i++)
3765 		rec_argv[i] = strdup(record_args[i]);
3766 
3767 	rec_argv[i++] = strdup("-e");
3768 	waking_event = trace_event__tp_format("sched", "sched_waking");
3769 	if (!IS_ERR(waking_event))
3770 		rec_argv[i++] = strdup("sched:sched_waking");
3771 	else
3772 		rec_argv[i++] = strdup("sched:sched_wakeup");
3773 
3774 	for (j = 0; j < schedstat_argc; j++)
3775 		rec_argv[i++] = strdup(schedstat_args[j]);
3776 
3777 	for (j = 1; j < (unsigned int)argc; j++, i++)
3778 		rec_argv[i] = strdup(argv[j]);
3779 
3780 	BUG_ON(i != rec_argc);
3781 
3782 	memcpy(rec_argv_copy, rec_argv, sizeof(char *) * rec_argc);
3783 	ret = cmd_record(rec_argc, rec_argv_copy);
3784 
3785 	for (i = 0; i < rec_argc; i++)
3786 		free(rec_argv[i]);
3787 	free(rec_argv);
3788 	free(rec_argv_copy);
3789 
3790 	return ret;
3791 }
3792 
cmd_sched(int argc,const char ** argv)3793 int cmd_sched(int argc, const char **argv)
3794 {
3795 	static const char default_sort_order[] = "avg, max, switch, runtime";
3796 	struct perf_sched sched = {
3797 		.cmp_pid	      = LIST_HEAD_INIT(sched.cmp_pid),
3798 		.sort_list	      = LIST_HEAD_INIT(sched.sort_list),
3799 		.sort_order	      = default_sort_order,
3800 		.replay_repeat	      = 10,
3801 		.profile_cpu	      = -1,
3802 		.next_shortname1      = 'A',
3803 		.next_shortname2      = '0',
3804 		.skip_merge           = 0,
3805 		.show_callchain	      = 1,
3806 		.max_stack            = 5,
3807 	};
3808 	const struct option sched_options[] = {
3809 	OPT_STRING('i', "input", &input_name, "file",
3810 		    "input file name"),
3811 	OPT_INCR('v', "verbose", &verbose,
3812 		    "be more verbose (show symbol address, etc)"),
3813 	OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
3814 		    "dump raw trace in ASCII"),
3815 	OPT_BOOLEAN('f', "force", &sched.force, "don't complain, do it"),
3816 	OPT_END()
3817 	};
3818 	const struct option latency_options[] = {
3819 	OPT_STRING('s', "sort", &sched.sort_order, "key[,key2...]",
3820 		   "sort by key(s): runtime, switch, avg, max"),
3821 	OPT_INTEGER('C', "CPU", &sched.profile_cpu,
3822 		    "CPU to profile on"),
3823 	OPT_BOOLEAN('p', "pids", &sched.skip_merge,
3824 		    "latency stats per pid instead of per comm"),
3825 	OPT_PARENT(sched_options)
3826 	};
3827 	const struct option replay_options[] = {
3828 	OPT_UINTEGER('r', "repeat", &sched.replay_repeat,
3829 		     "repeat the workload replay N times (0: infinite)"),
3830 	OPT_PARENT(sched_options)
3831 	};
3832 	const struct option map_options[] = {
3833 	OPT_BOOLEAN(0, "compact", &sched.map.comp,
3834 		    "map output in compact mode"),
3835 	OPT_STRING(0, "color-pids", &sched.map.color_pids_str, "pids",
3836 		   "highlight given pids in map"),
3837 	OPT_STRING(0, "color-cpus", &sched.map.color_cpus_str, "cpus",
3838                     "highlight given CPUs in map"),
3839 	OPT_STRING(0, "cpus", &sched.map.cpus_str, "cpus",
3840                     "display given CPUs in map"),
3841 	OPT_STRING(0, "task-name", &sched.map.task_name, "task",
3842 		"map output only for the given task name(s)."),
3843 	OPT_BOOLEAN(0, "fuzzy-name", &sched.map.fuzzy,
3844 		"given command name can be partially matched (fuzzy matching)"),
3845 	OPT_PARENT(sched_options)
3846 	};
3847 	const struct option timehist_options[] = {
3848 	OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
3849 		   "file", "vmlinux pathname"),
3850 	OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
3851 		   "file", "kallsyms pathname"),
3852 	OPT_BOOLEAN('g', "call-graph", &sched.show_callchain,
3853 		    "Display call chains if present (default on)"),
3854 	OPT_UINTEGER(0, "max-stack", &sched.max_stack,
3855 		   "Maximum number of functions to display backtrace."),
3856 	OPT_STRING(0, "symfs", &symbol_conf.symfs, "directory",
3857 		    "Look for files with symbols relative to this directory"),
3858 	OPT_BOOLEAN('s', "summary", &sched.summary_only,
3859 		    "Show only syscall summary with statistics"),
3860 	OPT_BOOLEAN('S', "with-summary", &sched.summary,
3861 		    "Show all syscalls and summary with statistics"),
3862 	OPT_BOOLEAN('w', "wakeups", &sched.show_wakeups, "Show wakeup events"),
3863 	OPT_BOOLEAN('n', "next", &sched.show_next, "Show next task"),
3864 	OPT_BOOLEAN('M', "migrations", &sched.show_migrations, "Show migration events"),
3865 	OPT_BOOLEAN('V', "cpu-visual", &sched.show_cpu_visual, "Add CPU visual"),
3866 	OPT_BOOLEAN('I', "idle-hist", &sched.idle_hist, "Show idle events only"),
3867 	OPT_STRING(0, "time", &sched.time_str, "str",
3868 		   "Time span for analysis (start,stop)"),
3869 	OPT_BOOLEAN(0, "state", &sched.show_state, "Show task state when sched-out"),
3870 	OPT_STRING('p', "pid", &symbol_conf.pid_list_str, "pid[,pid...]",
3871 		   "analyze events only for given process id(s)"),
3872 	OPT_STRING('t', "tid", &symbol_conf.tid_list_str, "tid[,tid...]",
3873 		   "analyze events only for given thread id(s)"),
3874 	OPT_STRING('C', "cpu", &cpu_list, "cpu", "list of cpus to profile"),
3875 	OPT_BOOLEAN(0, "show-prio", &sched.show_prio, "Show task priority"),
3876 	OPT_STRING(0, "prio", &sched.prio_str, "prio",
3877 		   "analyze events only for given task priority(ies)"),
3878 	OPT_PARENT(sched_options)
3879 	};
3880 
3881 	const char * const latency_usage[] = {
3882 		"perf sched latency [<options>]",
3883 		NULL
3884 	};
3885 	const char * const replay_usage[] = {
3886 		"perf sched replay [<options>]",
3887 		NULL
3888 	};
3889 	const char * const map_usage[] = {
3890 		"perf sched map [<options>]",
3891 		NULL
3892 	};
3893 	const char * const timehist_usage[] = {
3894 		"perf sched timehist [<options>]",
3895 		NULL
3896 	};
3897 	const char *const sched_subcommands[] = { "record", "latency", "map",
3898 						  "replay", "script",
3899 						  "timehist", NULL };
3900 	const char *sched_usage[] = {
3901 		NULL,
3902 		NULL
3903 	};
3904 	struct trace_sched_handler lat_ops  = {
3905 		.wakeup_event	    = latency_wakeup_event,
3906 		.switch_event	    = latency_switch_event,
3907 		.runtime_event	    = latency_runtime_event,
3908 		.migrate_task_event = latency_migrate_task_event,
3909 	};
3910 	struct trace_sched_handler map_ops  = {
3911 		.switch_event	    = map_switch_event,
3912 	};
3913 	struct trace_sched_handler replay_ops  = {
3914 		.wakeup_event	    = replay_wakeup_event,
3915 		.switch_event	    = replay_switch_event,
3916 		.fork_event	    = replay_fork_event,
3917 	};
3918 	int ret;
3919 
3920 	perf_tool__init(&sched.tool, /*ordered_events=*/true);
3921 	sched.tool.sample	 = perf_sched__process_tracepoint_sample;
3922 	sched.tool.comm		 = perf_sched__process_comm;
3923 	sched.tool.namespaces	 = perf_event__process_namespaces;
3924 	sched.tool.lost		 = perf_event__process_lost;
3925 	sched.tool.fork		 = perf_sched__process_fork_event;
3926 
3927 	argc = parse_options_subcommand(argc, argv, sched_options, sched_subcommands,
3928 					sched_usage, PARSE_OPT_STOP_AT_NON_OPTION);
3929 	if (!argc)
3930 		usage_with_options(sched_usage, sched_options);
3931 
3932 	thread__set_priv_destructor(free);
3933 
3934 	/*
3935 	 * Aliased to 'perf script' for now:
3936 	 */
3937 	if (!strcmp(argv[0], "script")) {
3938 		ret = cmd_script(argc, argv);
3939 	} else if (strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
3940 		ret = __cmd_record(argc, argv);
3941 	} else if (strlen(argv[0]) > 2 && strstarts("latency", argv[0])) {
3942 		sched.tp_handler = &lat_ops;
3943 		if (argc > 1) {
3944 			argc = parse_options(argc, argv, latency_options, latency_usage, 0);
3945 			if (argc)
3946 				usage_with_options(latency_usage, latency_options);
3947 		}
3948 		setup_sorting(&sched, latency_options, latency_usage);
3949 		ret = perf_sched__lat(&sched);
3950 	} else if (!strcmp(argv[0], "map")) {
3951 		if (argc) {
3952 			argc = parse_options(argc, argv, map_options, map_usage, 0);
3953 			if (argc)
3954 				usage_with_options(map_usage, map_options);
3955 
3956 			if (sched.map.task_name) {
3957 				sched.map.task_names = strlist__new(sched.map.task_name, NULL);
3958 				if (sched.map.task_names == NULL) {
3959 					fprintf(stderr, "Failed to parse task names\n");
3960 					ret = -1;
3961 					goto out;
3962 				}
3963 			}
3964 		}
3965 		sched.tp_handler = &map_ops;
3966 		setup_sorting(&sched, latency_options, latency_usage);
3967 		ret = perf_sched__map(&sched);
3968 	} else if (strlen(argv[0]) > 2 && strstarts("replay", argv[0])) {
3969 		sched.tp_handler = &replay_ops;
3970 		if (argc) {
3971 			argc = parse_options(argc, argv, replay_options, replay_usage, 0);
3972 			if (argc)
3973 				usage_with_options(replay_usage, replay_options);
3974 		}
3975 		ret = perf_sched__replay(&sched);
3976 	} else if (!strcmp(argv[0], "timehist")) {
3977 		if (argc) {
3978 			argc = parse_options(argc, argv, timehist_options,
3979 					     timehist_usage, 0);
3980 			if (argc)
3981 				usage_with_options(timehist_usage, timehist_options);
3982 		}
3983 		if ((sched.show_wakeups || sched.show_next) &&
3984 		    sched.summary_only) {
3985 			pr_err(" Error: -s and -[n|w] are mutually exclusive.\n");
3986 			parse_options_usage(timehist_usage, timehist_options, "s", true);
3987 			if (sched.show_wakeups)
3988 				parse_options_usage(NULL, timehist_options, "w", true);
3989 			if (sched.show_next)
3990 				parse_options_usage(NULL, timehist_options, "n", true);
3991 			ret = -EINVAL;
3992 			goto out;
3993 		}
3994 		ret = symbol__validate_sym_arguments();
3995 		if (!ret)
3996 			ret = perf_sched__timehist(&sched);
3997 	} else {
3998 		usage_with_options(sched_usage, sched_options);
3999 	}
4000 
4001 out:
4002 	/* free usage string allocated by parse_options_subcommand */
4003 	free((void *)sched_usage[0]);
4004 
4005 	return ret;
4006 }
4007