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