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