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