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