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