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