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"
20 #include <subcmd/parse-options.h>
21 #include "util/trace-event.h"
23 #include "util/debug.h"
25 #include <linux/kernel.h>
26 #include <linux/log2.h>
27 #include <sys/prctl.h>
28 #include <sys/resource.h>
31 #include <semaphore.h>
34 #include <api/fs/fs.h>
35 #include <linux/time64.h>
37 #define PR_SET_NAME 15 /* Set process name */
41 #define MAX_PID 1024000
50 unsigned long nr_events;
51 unsigned long curr_event;
52 struct sched_atom **atoms;
63 enum sched_event_type {
67 SCHED_EVENT_MIGRATION,
71 enum sched_event_type type;
77 struct task_desc *wakee;
80 #define TASK_STATE_TO_CHAR_STR "RSDTtZXxKWP"
82 /* task state bitmask, copied from include/linux/sched.h */
83 #define TASK_RUNNING 0
84 #define TASK_INTERRUPTIBLE 1
85 #define TASK_UNINTERRUPTIBLE 2
86 #define __TASK_STOPPED 4
87 #define __TASK_TRACED 8
88 /* in tsk->exit_state */
90 #define EXIT_ZOMBIE 32
91 #define EXIT_TRACE (EXIT_ZOMBIE | EXIT_DEAD)
92 /* in tsk->state again */
94 #define TASK_WAKEKILL 128
95 #define TASK_WAKING 256
96 #define TASK_PARKED 512
106 struct list_head list;
107 enum thread_state state;
115 struct list_head work_list;
116 struct thread *thread;
126 typedef int (*sort_fn_t)(struct work_atoms *, struct work_atoms *);
130 struct trace_sched_handler {
131 int (*switch_event)(struct perf_sched *sched, struct perf_evsel *evsel,
132 struct perf_sample *sample, struct machine *machine);
134 int (*runtime_event)(struct perf_sched *sched, struct perf_evsel *evsel,
135 struct perf_sample *sample, struct machine *machine);
137 int (*wakeup_event)(struct perf_sched *sched, struct perf_evsel *evsel,
138 struct perf_sample *sample, struct machine *machine);
140 /* PERF_RECORD_FORK event, not sched_process_fork tracepoint */
141 int (*fork_event)(struct perf_sched *sched, union perf_event *event,
142 struct machine *machine);
144 int (*migrate_task_event)(struct perf_sched *sched,
145 struct perf_evsel *evsel,
146 struct perf_sample *sample,
147 struct machine *machine);
150 #define COLOR_PIDS PERF_COLOR_BLUE
151 #define COLOR_CPUS PERF_COLOR_BG_RED
153 struct perf_sched_map {
154 DECLARE_BITMAP(comp_cpus_mask, MAX_CPUS);
157 struct thread_map *color_pids;
158 const char *color_pids_str;
159 struct cpu_map *color_cpus;
160 const char *color_cpus_str;
161 struct cpu_map *cpus;
162 const char *cpus_str;
166 struct perf_tool tool;
167 const char *sort_order;
168 unsigned long nr_tasks;
169 struct task_desc **pid_to_task;
170 struct task_desc **tasks;
171 const struct trace_sched_handler *tp_handler;
172 pthread_mutex_t start_work_mutex;
173 pthread_mutex_t work_done_wait_mutex;
176 * Track the current task - that way we can know whether there's any
177 * weird events, such as a task being switched away that is not current.
180 u32 curr_pid[MAX_CPUS];
181 struct thread *curr_thread[MAX_CPUS];
182 char next_shortname1;
183 char next_shortname2;
184 unsigned int replay_repeat;
185 unsigned long nr_run_events;
186 unsigned long nr_sleep_events;
187 unsigned long nr_wakeup_events;
188 unsigned long nr_sleep_corrections;
189 unsigned long nr_run_events_optimized;
190 unsigned long targetless_wakeups;
191 unsigned long multitarget_wakeups;
192 unsigned long nr_runs;
193 unsigned long nr_timestamps;
194 unsigned long nr_unordered_timestamps;
195 unsigned long nr_context_switch_bugs;
196 unsigned long nr_events;
197 unsigned long nr_lost_chunks;
198 unsigned long nr_lost_events;
199 u64 run_measurement_overhead;
200 u64 sleep_measurement_overhead;
203 u64 runavg_cpu_usage;
204 u64 parent_cpu_usage;
205 u64 runavg_parent_cpu_usage;
211 u64 cpu_last_switched[MAX_CPUS];
212 struct rb_root atom_root, sorted_atom_root, merged_atom_root;
213 struct list_head sort_list, cmp_pid;
216 struct perf_sched_map map;
218 /* options for timehist command */
223 unsigned int max_stack;
224 bool show_cpu_visual;
227 bool show_migrations;
230 const char *time_str;
231 struct perf_time_interval ptime;
232 struct perf_time_interval hist_time;
235 /* per thread run time data */
236 struct thread_runtime {
237 u64 last_time; /* time of previous sched in/out event */
238 u64 dt_run; /* run time */
239 u64 dt_sleep; /* time between CPU access by sleep (off cpu) */
240 u64 dt_iowait; /* time between CPU access by iowait (off cpu) */
241 u64 dt_preempt; /* time between CPU access by preempt (off cpu) */
242 u64 dt_delay; /* time between wakeup and sched-in */
243 u64 ready_to_run; /* time of wakeup */
245 struct stats run_stats;
247 u64 total_sleep_time;
248 u64 total_iowait_time;
249 u64 total_preempt_time;
250 u64 total_delay_time;
256 /* per event run time data */
257 struct evsel_runtime {
258 u64 *last_time; /* time this event was last seen per cpu */
259 u32 ncpu; /* highest cpu slot allocated */
262 /* per cpu idle time data */
263 struct idle_thread_runtime {
264 struct thread_runtime tr;
265 struct thread *last_thread;
266 struct rb_root sorted_root;
267 struct callchain_root callchain;
268 struct callchain_cursor cursor;
271 /* track idle times per cpu */
272 static struct thread **idle_threads;
273 static int idle_max_cpu;
274 static char idle_comm[] = "<idle>";
276 static u64 get_nsecs(void)
280 clock_gettime(CLOCK_MONOTONIC, &ts);
282 return ts.tv_sec * NSEC_PER_SEC + ts.tv_nsec;
285 static void burn_nsecs(struct perf_sched *sched, u64 nsecs)
287 u64 T0 = get_nsecs(), T1;
291 } while (T1 + sched->run_measurement_overhead < T0 + nsecs);
294 static void sleep_nsecs(u64 nsecs)
298 ts.tv_nsec = nsecs % 999999999;
299 ts.tv_sec = nsecs / 999999999;
301 nanosleep(&ts, NULL);
304 static void calibrate_run_measurement_overhead(struct perf_sched *sched)
306 u64 T0, T1, delta, min_delta = NSEC_PER_SEC;
309 for (i = 0; i < 10; i++) {
311 burn_nsecs(sched, 0);
314 min_delta = min(min_delta, delta);
316 sched->run_measurement_overhead = min_delta;
318 printf("run measurement overhead: %" PRIu64 " nsecs\n", min_delta);
321 static void calibrate_sleep_measurement_overhead(struct perf_sched *sched)
323 u64 T0, T1, delta, min_delta = NSEC_PER_SEC;
326 for (i = 0; i < 10; i++) {
331 min_delta = min(min_delta, delta);
334 sched->sleep_measurement_overhead = min_delta;
336 printf("sleep measurement overhead: %" PRIu64 " nsecs\n", min_delta);
339 static struct sched_atom *
340 get_new_event(struct task_desc *task, u64 timestamp)
342 struct sched_atom *event = zalloc(sizeof(*event));
343 unsigned long idx = task->nr_events;
346 event->timestamp = timestamp;
350 size = sizeof(struct sched_atom *) * task->nr_events;
351 task->atoms = realloc(task->atoms, size);
352 BUG_ON(!task->atoms);
354 task->atoms[idx] = event;
359 static struct sched_atom *last_event(struct task_desc *task)
361 if (!task->nr_events)
364 return task->atoms[task->nr_events - 1];
367 static void add_sched_event_run(struct perf_sched *sched, struct task_desc *task,
368 u64 timestamp, u64 duration)
370 struct sched_atom *event, *curr_event = last_event(task);
373 * optimize an existing RUN event by merging this one
376 if (curr_event && curr_event->type == SCHED_EVENT_RUN) {
377 sched->nr_run_events_optimized++;
378 curr_event->duration += duration;
382 event = get_new_event(task, timestamp);
384 event->type = SCHED_EVENT_RUN;
385 event->duration = duration;
387 sched->nr_run_events++;
390 static void add_sched_event_wakeup(struct perf_sched *sched, struct task_desc *task,
391 u64 timestamp, struct task_desc *wakee)
393 struct sched_atom *event, *wakee_event;
395 event = get_new_event(task, timestamp);
396 event->type = SCHED_EVENT_WAKEUP;
397 event->wakee = wakee;
399 wakee_event = last_event(wakee);
400 if (!wakee_event || wakee_event->type != SCHED_EVENT_SLEEP) {
401 sched->targetless_wakeups++;
404 if (wakee_event->wait_sem) {
405 sched->multitarget_wakeups++;
409 wakee_event->wait_sem = zalloc(sizeof(*wakee_event->wait_sem));
410 sem_init(wakee_event->wait_sem, 0, 0);
411 wakee_event->specific_wait = 1;
412 event->wait_sem = wakee_event->wait_sem;
414 sched->nr_wakeup_events++;
417 static void add_sched_event_sleep(struct perf_sched *sched, struct task_desc *task,
418 u64 timestamp, u64 task_state __maybe_unused)
420 struct sched_atom *event = get_new_event(task, timestamp);
422 event->type = SCHED_EVENT_SLEEP;
424 sched->nr_sleep_events++;
427 static struct task_desc *register_pid(struct perf_sched *sched,
428 unsigned long pid, const char *comm)
430 struct task_desc *task;
433 if (sched->pid_to_task == NULL) {
434 if (sysctl__read_int("kernel/pid_max", &pid_max) < 0)
436 BUG_ON((sched->pid_to_task = calloc(pid_max, sizeof(struct task_desc *))) == NULL);
438 if (pid >= (unsigned long)pid_max) {
439 BUG_ON((sched->pid_to_task = realloc(sched->pid_to_task, (pid + 1) *
440 sizeof(struct task_desc *))) == NULL);
441 while (pid >= (unsigned long)pid_max)
442 sched->pid_to_task[pid_max++] = NULL;
445 task = sched->pid_to_task[pid];
450 task = zalloc(sizeof(*task));
452 task->nr = sched->nr_tasks;
453 strcpy(task->comm, comm);
455 * every task starts in sleeping state - this gets ignored
456 * if there's no wakeup pointing to this sleep state:
458 add_sched_event_sleep(sched, task, 0, 0);
460 sched->pid_to_task[pid] = task;
462 sched->tasks = realloc(sched->tasks, sched->nr_tasks * sizeof(struct task_desc *));
463 BUG_ON(!sched->tasks);
464 sched->tasks[task->nr] = task;
467 printf("registered task #%ld, PID %ld (%s)\n", sched->nr_tasks, pid, comm);
473 static void print_task_traces(struct perf_sched *sched)
475 struct task_desc *task;
478 for (i = 0; i < sched->nr_tasks; i++) {
479 task = sched->tasks[i];
480 printf("task %6ld (%20s:%10ld), nr_events: %ld\n",
481 task->nr, task->comm, task->pid, task->nr_events);
485 static void add_cross_task_wakeups(struct perf_sched *sched)
487 struct task_desc *task1, *task2;
490 for (i = 0; i < sched->nr_tasks; i++) {
491 task1 = sched->tasks[i];
493 if (j == sched->nr_tasks)
495 task2 = sched->tasks[j];
496 add_sched_event_wakeup(sched, task1, 0, task2);
500 static void perf_sched__process_event(struct perf_sched *sched,
501 struct sched_atom *atom)
505 switch (atom->type) {
506 case SCHED_EVENT_RUN:
507 burn_nsecs(sched, atom->duration);
509 case SCHED_EVENT_SLEEP:
511 ret = sem_wait(atom->wait_sem);
514 case SCHED_EVENT_WAKEUP:
516 ret = sem_post(atom->wait_sem);
519 case SCHED_EVENT_MIGRATION:
526 static u64 get_cpu_usage_nsec_parent(void)
532 err = getrusage(RUSAGE_SELF, &ru);
535 sum = ru.ru_utime.tv_sec * NSEC_PER_SEC + ru.ru_utime.tv_usec * NSEC_PER_USEC;
536 sum += ru.ru_stime.tv_sec * NSEC_PER_SEC + ru.ru_stime.tv_usec * NSEC_PER_USEC;
541 static int self_open_counters(struct perf_sched *sched, unsigned long cur_task)
543 struct perf_event_attr attr;
544 char sbuf[STRERR_BUFSIZE], info[STRERR_BUFSIZE];
547 bool need_privilege = false;
549 memset(&attr, 0, sizeof(attr));
551 attr.type = PERF_TYPE_SOFTWARE;
552 attr.config = PERF_COUNT_SW_TASK_CLOCK;
555 fd = sys_perf_event_open(&attr, 0, -1, -1,
556 perf_event_open_cloexec_flag());
559 if (errno == EMFILE) {
561 BUG_ON(getrlimit(RLIMIT_NOFILE, &limit) == -1);
562 limit.rlim_cur += sched->nr_tasks - cur_task;
563 if (limit.rlim_cur > limit.rlim_max) {
564 limit.rlim_max = limit.rlim_cur;
565 need_privilege = true;
567 if (setrlimit(RLIMIT_NOFILE, &limit) == -1) {
568 if (need_privilege && errno == EPERM)
569 strcpy(info, "Need privilege\n");
573 strcpy(info, "Have a try with -f option\n");
575 pr_err("Error: sys_perf_event_open() syscall returned "
576 "with %d (%s)\n%s", fd,
577 str_error_r(errno, sbuf, sizeof(sbuf)), info);
583 static u64 get_cpu_usage_nsec_self(int fd)
588 ret = read(fd, &runtime, sizeof(runtime));
589 BUG_ON(ret != sizeof(runtime));
594 struct sched_thread_parms {
595 struct task_desc *task;
596 struct perf_sched *sched;
600 static void *thread_func(void *ctx)
602 struct sched_thread_parms *parms = ctx;
603 struct task_desc *this_task = parms->task;
604 struct perf_sched *sched = parms->sched;
605 u64 cpu_usage_0, cpu_usage_1;
606 unsigned long i, ret;
612 sprintf(comm2, ":%s", this_task->comm);
613 prctl(PR_SET_NAME, comm2);
617 ret = sem_post(&this_task->ready_for_work);
619 ret = pthread_mutex_lock(&sched->start_work_mutex);
621 ret = pthread_mutex_unlock(&sched->start_work_mutex);
624 cpu_usage_0 = get_cpu_usage_nsec_self(fd);
626 for (i = 0; i < this_task->nr_events; i++) {
627 this_task->curr_event = i;
628 perf_sched__process_event(sched, this_task->atoms[i]);
631 cpu_usage_1 = get_cpu_usage_nsec_self(fd);
632 this_task->cpu_usage = cpu_usage_1 - cpu_usage_0;
633 ret = sem_post(&this_task->work_done_sem);
636 ret = pthread_mutex_lock(&sched->work_done_wait_mutex);
638 ret = pthread_mutex_unlock(&sched->work_done_wait_mutex);
644 static void create_tasks(struct perf_sched *sched)
646 struct task_desc *task;
651 err = pthread_attr_init(&attr);
653 err = pthread_attr_setstacksize(&attr,
654 (size_t) max(16 * 1024, PTHREAD_STACK_MIN));
656 err = pthread_mutex_lock(&sched->start_work_mutex);
658 err = pthread_mutex_lock(&sched->work_done_wait_mutex);
660 for (i = 0; i < sched->nr_tasks; i++) {
661 struct sched_thread_parms *parms = malloc(sizeof(*parms));
662 BUG_ON(parms == NULL);
663 parms->task = task = sched->tasks[i];
664 parms->sched = sched;
665 parms->fd = self_open_counters(sched, i);
666 sem_init(&task->sleep_sem, 0, 0);
667 sem_init(&task->ready_for_work, 0, 0);
668 sem_init(&task->work_done_sem, 0, 0);
669 task->curr_event = 0;
670 err = pthread_create(&task->thread, &attr, thread_func, parms);
675 static void wait_for_tasks(struct perf_sched *sched)
677 u64 cpu_usage_0, cpu_usage_1;
678 struct task_desc *task;
679 unsigned long i, ret;
681 sched->start_time = get_nsecs();
682 sched->cpu_usage = 0;
683 pthread_mutex_unlock(&sched->work_done_wait_mutex);
685 for (i = 0; i < sched->nr_tasks; i++) {
686 task = sched->tasks[i];
687 ret = sem_wait(&task->ready_for_work);
689 sem_init(&task->ready_for_work, 0, 0);
691 ret = pthread_mutex_lock(&sched->work_done_wait_mutex);
694 cpu_usage_0 = get_cpu_usage_nsec_parent();
696 pthread_mutex_unlock(&sched->start_work_mutex);
698 for (i = 0; i < sched->nr_tasks; i++) {
699 task = sched->tasks[i];
700 ret = sem_wait(&task->work_done_sem);
702 sem_init(&task->work_done_sem, 0, 0);
703 sched->cpu_usage += task->cpu_usage;
707 cpu_usage_1 = get_cpu_usage_nsec_parent();
708 if (!sched->runavg_cpu_usage)
709 sched->runavg_cpu_usage = sched->cpu_usage;
710 sched->runavg_cpu_usage = (sched->runavg_cpu_usage * (sched->replay_repeat - 1) + sched->cpu_usage) / sched->replay_repeat;
712 sched->parent_cpu_usage = cpu_usage_1 - cpu_usage_0;
713 if (!sched->runavg_parent_cpu_usage)
714 sched->runavg_parent_cpu_usage = sched->parent_cpu_usage;
715 sched->runavg_parent_cpu_usage = (sched->runavg_parent_cpu_usage * (sched->replay_repeat - 1) +
716 sched->parent_cpu_usage)/sched->replay_repeat;
718 ret = pthread_mutex_lock(&sched->start_work_mutex);
721 for (i = 0; i < sched->nr_tasks; i++) {
722 task = sched->tasks[i];
723 sem_init(&task->sleep_sem, 0, 0);
724 task->curr_event = 0;
728 static void run_one_test(struct perf_sched *sched)
730 u64 T0, T1, delta, avg_delta, fluct;
733 wait_for_tasks(sched);
737 sched->sum_runtime += delta;
740 avg_delta = sched->sum_runtime / sched->nr_runs;
741 if (delta < avg_delta)
742 fluct = avg_delta - delta;
744 fluct = delta - avg_delta;
745 sched->sum_fluct += fluct;
747 sched->run_avg = delta;
748 sched->run_avg = (sched->run_avg * (sched->replay_repeat - 1) + delta) / sched->replay_repeat;
750 printf("#%-3ld: %0.3f, ", sched->nr_runs, (double)delta / NSEC_PER_MSEC);
752 printf("ravg: %0.2f, ", (double)sched->run_avg / NSEC_PER_MSEC);
754 printf("cpu: %0.2f / %0.2f",
755 (double)sched->cpu_usage / NSEC_PER_MSEC, (double)sched->runavg_cpu_usage / NSEC_PER_MSEC);
759 * rusage statistics done by the parent, these are less
760 * accurate than the sched->sum_exec_runtime based statistics:
762 printf(" [%0.2f / %0.2f]",
763 (double)sched->parent_cpu_usage / NSEC_PER_MSEC,
764 (double)sched->runavg_parent_cpu_usage / NSEC_PER_MSEC);
769 if (sched->nr_sleep_corrections)
770 printf(" (%ld sleep corrections)\n", sched->nr_sleep_corrections);
771 sched->nr_sleep_corrections = 0;
774 static void test_calibrations(struct perf_sched *sched)
779 burn_nsecs(sched, NSEC_PER_MSEC);
782 printf("the run test took %" PRIu64 " nsecs\n", T1 - T0);
785 sleep_nsecs(NSEC_PER_MSEC);
788 printf("the sleep test took %" PRIu64 " nsecs\n", T1 - T0);
792 replay_wakeup_event(struct perf_sched *sched,
793 struct perf_evsel *evsel, struct perf_sample *sample,
794 struct machine *machine __maybe_unused)
796 const char *comm = perf_evsel__strval(evsel, sample, "comm");
797 const u32 pid = perf_evsel__intval(evsel, sample, "pid");
798 struct task_desc *waker, *wakee;
801 printf("sched_wakeup event %p\n", evsel);
803 printf(" ... pid %d woke up %s/%d\n", sample->tid, comm, pid);
806 waker = register_pid(sched, sample->tid, "<unknown>");
807 wakee = register_pid(sched, pid, comm);
809 add_sched_event_wakeup(sched, waker, sample->time, wakee);
813 static int replay_switch_event(struct perf_sched *sched,
814 struct perf_evsel *evsel,
815 struct perf_sample *sample,
816 struct machine *machine __maybe_unused)
818 const char *prev_comm = perf_evsel__strval(evsel, sample, "prev_comm"),
819 *next_comm = perf_evsel__strval(evsel, sample, "next_comm");
820 const u32 prev_pid = perf_evsel__intval(evsel, sample, "prev_pid"),
821 next_pid = perf_evsel__intval(evsel, sample, "next_pid");
822 const u64 prev_state = perf_evsel__intval(evsel, sample, "prev_state");
823 struct task_desc *prev, __maybe_unused *next;
824 u64 timestamp0, timestamp = sample->time;
825 int cpu = sample->cpu;
829 printf("sched_switch event %p\n", evsel);
831 if (cpu >= MAX_CPUS || cpu < 0)
834 timestamp0 = sched->cpu_last_switched[cpu];
836 delta = timestamp - timestamp0;
841 pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
845 pr_debug(" ... switch from %s/%d to %s/%d [ran %" PRIu64 " nsecs]\n",
846 prev_comm, prev_pid, next_comm, next_pid, delta);
848 prev = register_pid(sched, prev_pid, prev_comm);
849 next = register_pid(sched, next_pid, next_comm);
851 sched->cpu_last_switched[cpu] = timestamp;
853 add_sched_event_run(sched, prev, timestamp, delta);
854 add_sched_event_sleep(sched, prev, timestamp, prev_state);
859 static int replay_fork_event(struct perf_sched *sched,
860 union perf_event *event,
861 struct machine *machine)
863 struct thread *child, *parent;
865 child = machine__findnew_thread(machine, event->fork.pid,
867 parent = machine__findnew_thread(machine, event->fork.ppid,
870 if (child == NULL || parent == NULL) {
871 pr_debug("thread does not exist on fork event: child %p, parent %p\n",
877 printf("fork event\n");
878 printf("... parent: %s/%d\n", thread__comm_str(parent), parent->tid);
879 printf("... child: %s/%d\n", thread__comm_str(child), child->tid);
882 register_pid(sched, parent->tid, thread__comm_str(parent));
883 register_pid(sched, child->tid, thread__comm_str(child));
890 struct sort_dimension {
893 struct list_head list;
897 thread_lat_cmp(struct list_head *list, struct work_atoms *l, struct work_atoms *r)
899 struct sort_dimension *sort;
902 BUG_ON(list_empty(list));
904 list_for_each_entry(sort, list, list) {
905 ret = sort->cmp(l, r);
913 static struct work_atoms *
914 thread_atoms_search(struct rb_root *root, struct thread *thread,
915 struct list_head *sort_list)
917 struct rb_node *node = root->rb_node;
918 struct work_atoms key = { .thread = thread };
921 struct work_atoms *atoms;
924 atoms = container_of(node, struct work_atoms, node);
926 cmp = thread_lat_cmp(sort_list, &key, atoms);
928 node = node->rb_left;
930 node = node->rb_right;
932 BUG_ON(thread != atoms->thread);
940 __thread_latency_insert(struct rb_root *root, struct work_atoms *data,
941 struct list_head *sort_list)
943 struct rb_node **new = &(root->rb_node), *parent = NULL;
946 struct work_atoms *this;
949 this = container_of(*new, struct work_atoms, node);
952 cmp = thread_lat_cmp(sort_list, data, this);
955 new = &((*new)->rb_left);
957 new = &((*new)->rb_right);
960 rb_link_node(&data->node, parent, new);
961 rb_insert_color(&data->node, root);
964 static int thread_atoms_insert(struct perf_sched *sched, struct thread *thread)
966 struct work_atoms *atoms = zalloc(sizeof(*atoms));
968 pr_err("No memory at %s\n", __func__);
972 atoms->thread = thread__get(thread);
973 INIT_LIST_HEAD(&atoms->work_list);
974 __thread_latency_insert(&sched->atom_root, atoms, &sched->cmp_pid);
978 static char sched_out_state(u64 prev_state)
980 const char *str = TASK_STATE_TO_CHAR_STR;
982 return str[prev_state];
986 add_sched_out_event(struct work_atoms *atoms,
990 struct work_atom *atom = zalloc(sizeof(*atom));
992 pr_err("Non memory at %s", __func__);
996 atom->sched_out_time = timestamp;
998 if (run_state == 'R') {
999 atom->state = THREAD_WAIT_CPU;
1000 atom->wake_up_time = atom->sched_out_time;
1003 list_add_tail(&atom->list, &atoms->work_list);
1008 add_runtime_event(struct work_atoms *atoms, u64 delta,
1009 u64 timestamp __maybe_unused)
1011 struct work_atom *atom;
1013 BUG_ON(list_empty(&atoms->work_list));
1015 atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1017 atom->runtime += delta;
1018 atoms->total_runtime += delta;
1022 add_sched_in_event(struct work_atoms *atoms, u64 timestamp)
1024 struct work_atom *atom;
1027 if (list_empty(&atoms->work_list))
1030 atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1032 if (atom->state != THREAD_WAIT_CPU)
1035 if (timestamp < atom->wake_up_time) {
1036 atom->state = THREAD_IGNORE;
1040 atom->state = THREAD_SCHED_IN;
1041 atom->sched_in_time = timestamp;
1043 delta = atom->sched_in_time - atom->wake_up_time;
1044 atoms->total_lat += delta;
1045 if (delta > atoms->max_lat) {
1046 atoms->max_lat = delta;
1047 atoms->max_lat_at = timestamp;
1052 static int latency_switch_event(struct perf_sched *sched,
1053 struct perf_evsel *evsel,
1054 struct perf_sample *sample,
1055 struct machine *machine)
1057 const u32 prev_pid = perf_evsel__intval(evsel, sample, "prev_pid"),
1058 next_pid = perf_evsel__intval(evsel, sample, "next_pid");
1059 const u64 prev_state = perf_evsel__intval(evsel, sample, "prev_state");
1060 struct work_atoms *out_events, *in_events;
1061 struct thread *sched_out, *sched_in;
1062 u64 timestamp0, timestamp = sample->time;
1063 int cpu = sample->cpu, err = -1;
1066 BUG_ON(cpu >= MAX_CPUS || cpu < 0);
1068 timestamp0 = sched->cpu_last_switched[cpu];
1069 sched->cpu_last_switched[cpu] = timestamp;
1071 delta = timestamp - timestamp0;
1076 pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
1080 sched_out = machine__findnew_thread(machine, -1, prev_pid);
1081 sched_in = machine__findnew_thread(machine, -1, next_pid);
1082 if (sched_out == NULL || sched_in == NULL)
1085 out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
1087 if (thread_atoms_insert(sched, sched_out))
1089 out_events = thread_atoms_search(&sched->atom_root, sched_out, &sched->cmp_pid);
1091 pr_err("out-event: Internal tree error");
1095 if (add_sched_out_event(out_events, sched_out_state(prev_state), timestamp))
1098 in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
1100 if (thread_atoms_insert(sched, sched_in))
1102 in_events = thread_atoms_search(&sched->atom_root, sched_in, &sched->cmp_pid);
1104 pr_err("in-event: Internal tree error");
1108 * Take came in we have not heard about yet,
1109 * add in an initial atom in runnable state:
1111 if (add_sched_out_event(in_events, 'R', timestamp))
1114 add_sched_in_event(in_events, timestamp);
1117 thread__put(sched_out);
1118 thread__put(sched_in);
1122 static int latency_runtime_event(struct perf_sched *sched,
1123 struct perf_evsel *evsel,
1124 struct perf_sample *sample,
1125 struct machine *machine)
1127 const u32 pid = perf_evsel__intval(evsel, sample, "pid");
1128 const u64 runtime = perf_evsel__intval(evsel, sample, "runtime");
1129 struct thread *thread = machine__findnew_thread(machine, -1, pid);
1130 struct work_atoms *atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
1131 u64 timestamp = sample->time;
1132 int cpu = sample->cpu, err = -1;
1137 BUG_ON(cpu >= MAX_CPUS || cpu < 0);
1139 if (thread_atoms_insert(sched, thread))
1141 atoms = thread_atoms_search(&sched->atom_root, thread, &sched->cmp_pid);
1143 pr_err("in-event: Internal tree error");
1146 if (add_sched_out_event(atoms, 'R', timestamp))
1150 add_runtime_event(atoms, runtime, timestamp);
1153 thread__put(thread);
1157 static int latency_wakeup_event(struct perf_sched *sched,
1158 struct perf_evsel *evsel,
1159 struct perf_sample *sample,
1160 struct machine *machine)
1162 const u32 pid = perf_evsel__intval(evsel, sample, "pid");
1163 struct work_atoms *atoms;
1164 struct work_atom *atom;
1165 struct thread *wakee;
1166 u64 timestamp = sample->time;
1169 wakee = machine__findnew_thread(machine, -1, pid);
1172 atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
1174 if (thread_atoms_insert(sched, wakee))
1176 atoms = thread_atoms_search(&sched->atom_root, wakee, &sched->cmp_pid);
1178 pr_err("wakeup-event: Internal tree error");
1181 if (add_sched_out_event(atoms, 'S', timestamp))
1185 BUG_ON(list_empty(&atoms->work_list));
1187 atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1190 * As we do not guarantee the wakeup event happens when
1191 * task is out of run queue, also may happen when task is
1192 * on run queue and wakeup only change ->state to TASK_RUNNING,
1193 * then we should not set the ->wake_up_time when wake up a
1194 * task which is on run queue.
1196 * You WILL be missing events if you've recorded only
1197 * one CPU, or are only looking at only one, so don't
1198 * skip in this case.
1200 if (sched->profile_cpu == -1 && atom->state != THREAD_SLEEPING)
1203 sched->nr_timestamps++;
1204 if (atom->sched_out_time > timestamp) {
1205 sched->nr_unordered_timestamps++;
1209 atom->state = THREAD_WAIT_CPU;
1210 atom->wake_up_time = timestamp;
1218 static int latency_migrate_task_event(struct perf_sched *sched,
1219 struct perf_evsel *evsel,
1220 struct perf_sample *sample,
1221 struct machine *machine)
1223 const u32 pid = perf_evsel__intval(evsel, sample, "pid");
1224 u64 timestamp = sample->time;
1225 struct work_atoms *atoms;
1226 struct work_atom *atom;
1227 struct thread *migrant;
1231 * Only need to worry about migration when profiling one CPU.
1233 if (sched->profile_cpu == -1)
1236 migrant = machine__findnew_thread(machine, -1, pid);
1237 if (migrant == NULL)
1239 atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
1241 if (thread_atoms_insert(sched, migrant))
1243 register_pid(sched, migrant->tid, thread__comm_str(migrant));
1244 atoms = thread_atoms_search(&sched->atom_root, migrant, &sched->cmp_pid);
1246 pr_err("migration-event: Internal tree error");
1249 if (add_sched_out_event(atoms, 'R', timestamp))
1253 BUG_ON(list_empty(&atoms->work_list));
1255 atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1256 atom->sched_in_time = atom->sched_out_time = atom->wake_up_time = timestamp;
1258 sched->nr_timestamps++;
1260 if (atom->sched_out_time > timestamp)
1261 sched->nr_unordered_timestamps++;
1264 thread__put(migrant);
1268 static void output_lat_thread(struct perf_sched *sched, struct work_atoms *work_list)
1273 char max_lat_at[32];
1275 if (!work_list->nb_atoms)
1278 * Ignore idle threads:
1280 if (!strcmp(thread__comm_str(work_list->thread), "swapper"))
1283 sched->all_runtime += work_list->total_runtime;
1284 sched->all_count += work_list->nb_atoms;
1286 if (work_list->num_merged > 1)
1287 ret = printf(" %s:(%d) ", thread__comm_str(work_list->thread), work_list->num_merged);
1289 ret = printf(" %s:%d ", thread__comm_str(work_list->thread), work_list->thread->tid);
1291 for (i = 0; i < 24 - ret; i++)
1294 avg = work_list->total_lat / work_list->nb_atoms;
1295 timestamp__scnprintf_usec(work_list->max_lat_at, max_lat_at, sizeof(max_lat_at));
1297 printf("|%11.3f ms |%9" PRIu64 " | avg:%9.3f ms | max:%9.3f ms | max at: %13s s\n",
1298 (double)work_list->total_runtime / NSEC_PER_MSEC,
1299 work_list->nb_atoms, (double)avg / NSEC_PER_MSEC,
1300 (double)work_list->max_lat / NSEC_PER_MSEC,
1304 static int pid_cmp(struct work_atoms *l, struct work_atoms *r)
1306 if (l->thread == r->thread)
1308 if (l->thread->tid < r->thread->tid)
1310 if (l->thread->tid > r->thread->tid)
1312 return (int)(l->thread - r->thread);
1315 static int avg_cmp(struct work_atoms *l, struct work_atoms *r)
1325 avgl = l->total_lat / l->nb_atoms;
1326 avgr = r->total_lat / r->nb_atoms;
1336 static int max_cmp(struct work_atoms *l, struct work_atoms *r)
1338 if (l->max_lat < r->max_lat)
1340 if (l->max_lat > r->max_lat)
1346 static int switch_cmp(struct work_atoms *l, struct work_atoms *r)
1348 if (l->nb_atoms < r->nb_atoms)
1350 if (l->nb_atoms > r->nb_atoms)
1356 static int runtime_cmp(struct work_atoms *l, struct work_atoms *r)
1358 if (l->total_runtime < r->total_runtime)
1360 if (l->total_runtime > r->total_runtime)
1366 static int sort_dimension__add(const char *tok, struct list_head *list)
1369 static struct sort_dimension avg_sort_dimension = {
1373 static struct sort_dimension max_sort_dimension = {
1377 static struct sort_dimension pid_sort_dimension = {
1381 static struct sort_dimension runtime_sort_dimension = {
1385 static struct sort_dimension switch_sort_dimension = {
1389 struct sort_dimension *available_sorts[] = {
1390 &pid_sort_dimension,
1391 &avg_sort_dimension,
1392 &max_sort_dimension,
1393 &switch_sort_dimension,
1394 &runtime_sort_dimension,
1397 for (i = 0; i < ARRAY_SIZE(available_sorts); i++) {
1398 if (!strcmp(available_sorts[i]->name, tok)) {
1399 list_add_tail(&available_sorts[i]->list, list);
1408 static void perf_sched__sort_lat(struct perf_sched *sched)
1410 struct rb_node *node;
1411 struct rb_root *root = &sched->atom_root;
1414 struct work_atoms *data;
1415 node = rb_first(root);
1419 rb_erase(node, root);
1420 data = rb_entry(node, struct work_atoms, node);
1421 __thread_latency_insert(&sched->sorted_atom_root, data, &sched->sort_list);
1423 if (root == &sched->atom_root) {
1424 root = &sched->merged_atom_root;
1429 static int process_sched_wakeup_event(struct perf_tool *tool,
1430 struct perf_evsel *evsel,
1431 struct perf_sample *sample,
1432 struct machine *machine)
1434 struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1436 if (sched->tp_handler->wakeup_event)
1437 return sched->tp_handler->wakeup_event(sched, evsel, sample, machine);
1447 static bool thread__has_color(struct thread *thread)
1449 union map_priv priv = {
1450 .ptr = thread__priv(thread),
1456 static struct thread*
1457 map__findnew_thread(struct perf_sched *sched, struct machine *machine, pid_t pid, pid_t tid)
1459 struct thread *thread = machine__findnew_thread(machine, pid, tid);
1460 union map_priv priv = {
1464 if (!sched->map.color_pids || !thread || thread__priv(thread))
1467 if (thread_map__has(sched->map.color_pids, tid))
1470 thread__set_priv(thread, priv.ptr);
1474 static int map_switch_event(struct perf_sched *sched, struct perf_evsel *evsel,
1475 struct perf_sample *sample, struct machine *machine)
1477 const u32 next_pid = perf_evsel__intval(evsel, sample, "next_pid");
1478 struct thread *sched_in;
1480 u64 timestamp0, timestamp = sample->time;
1482 int i, this_cpu = sample->cpu;
1484 bool new_cpu = false;
1485 const char *color = PERF_COLOR_NORMAL;
1486 char stimestamp[32];
1488 BUG_ON(this_cpu >= MAX_CPUS || this_cpu < 0);
1490 if (this_cpu > sched->max_cpu)
1491 sched->max_cpu = this_cpu;
1493 if (sched->map.comp) {
1494 cpus_nr = bitmap_weight(sched->map.comp_cpus_mask, MAX_CPUS);
1495 if (!test_and_set_bit(this_cpu, sched->map.comp_cpus_mask)) {
1496 sched->map.comp_cpus[cpus_nr++] = this_cpu;
1500 cpus_nr = sched->max_cpu;
1502 timestamp0 = sched->cpu_last_switched[this_cpu];
1503 sched->cpu_last_switched[this_cpu] = timestamp;
1505 delta = timestamp - timestamp0;
1510 pr_err("hm, delta: %" PRIu64 " < 0 ?\n", delta);
1514 sched_in = map__findnew_thread(sched, machine, -1, next_pid);
1515 if (sched_in == NULL)
1518 sched->curr_thread[this_cpu] = thread__get(sched_in);
1523 if (!sched_in->shortname[0]) {
1524 if (!strcmp(thread__comm_str(sched_in), "swapper")) {
1526 * Don't allocate a letter-number for swapper:0
1527 * as a shortname. Instead, we use '.' for it.
1529 sched_in->shortname[0] = '.';
1530 sched_in->shortname[1] = ' ';
1532 sched_in->shortname[0] = sched->next_shortname1;
1533 sched_in->shortname[1] = sched->next_shortname2;
1535 if (sched->next_shortname1 < 'Z') {
1536 sched->next_shortname1++;
1538 sched->next_shortname1 = 'A';
1539 if (sched->next_shortname2 < '9')
1540 sched->next_shortname2++;
1542 sched->next_shortname2 = '0';
1548 for (i = 0; i < cpus_nr; i++) {
1549 int cpu = sched->map.comp ? sched->map.comp_cpus[i] : i;
1550 struct thread *curr_thread = sched->curr_thread[cpu];
1551 const char *pid_color = color;
1552 const char *cpu_color = color;
1554 if (curr_thread && thread__has_color(curr_thread))
1555 pid_color = COLOR_PIDS;
1557 if (sched->map.cpus && !cpu_map__has(sched->map.cpus, cpu))
1560 if (sched->map.color_cpus && cpu_map__has(sched->map.color_cpus, cpu))
1561 cpu_color = COLOR_CPUS;
1563 if (cpu != this_cpu)
1564 color_fprintf(stdout, color, " ");
1566 color_fprintf(stdout, cpu_color, "*");
1568 if (sched->curr_thread[cpu])
1569 color_fprintf(stdout, pid_color, "%2s ", sched->curr_thread[cpu]->shortname);
1571 color_fprintf(stdout, color, " ");
1574 if (sched->map.cpus && !cpu_map__has(sched->map.cpus, this_cpu))
1577 timestamp__scnprintf_usec(timestamp, stimestamp, sizeof(stimestamp));
1578 color_fprintf(stdout, color, " %12s secs ", stimestamp);
1579 if (new_shortname || (verbose > 0 && sched_in->tid)) {
1580 const char *pid_color = color;
1582 if (thread__has_color(sched_in))
1583 pid_color = COLOR_PIDS;
1585 color_fprintf(stdout, pid_color, "%s => %s:%d",
1586 sched_in->shortname, thread__comm_str(sched_in), sched_in->tid);
1589 if (sched->map.comp && new_cpu)
1590 color_fprintf(stdout, color, " (CPU %d)", this_cpu);
1593 color_fprintf(stdout, color, "\n");
1595 thread__put(sched_in);
1600 static int process_sched_switch_event(struct perf_tool *tool,
1601 struct perf_evsel *evsel,
1602 struct perf_sample *sample,
1603 struct machine *machine)
1605 struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1606 int this_cpu = sample->cpu, err = 0;
1607 u32 prev_pid = perf_evsel__intval(evsel, sample, "prev_pid"),
1608 next_pid = perf_evsel__intval(evsel, sample, "next_pid");
1610 if (sched->curr_pid[this_cpu] != (u32)-1) {
1612 * Are we trying to switch away a PID that is
1615 if (sched->curr_pid[this_cpu] != prev_pid)
1616 sched->nr_context_switch_bugs++;
1619 if (sched->tp_handler->switch_event)
1620 err = sched->tp_handler->switch_event(sched, evsel, sample, machine);
1622 sched->curr_pid[this_cpu] = next_pid;
1626 static int process_sched_runtime_event(struct perf_tool *tool,
1627 struct perf_evsel *evsel,
1628 struct perf_sample *sample,
1629 struct machine *machine)
1631 struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1633 if (sched->tp_handler->runtime_event)
1634 return sched->tp_handler->runtime_event(sched, evsel, sample, machine);
1639 static int perf_sched__process_fork_event(struct perf_tool *tool,
1640 union perf_event *event,
1641 struct perf_sample *sample,
1642 struct machine *machine)
1644 struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1646 /* run the fork event through the perf machineruy */
1647 perf_event__process_fork(tool, event, sample, machine);
1649 /* and then run additional processing needed for this command */
1650 if (sched->tp_handler->fork_event)
1651 return sched->tp_handler->fork_event(sched, event, machine);
1656 static int process_sched_migrate_task_event(struct perf_tool *tool,
1657 struct perf_evsel *evsel,
1658 struct perf_sample *sample,
1659 struct machine *machine)
1661 struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
1663 if (sched->tp_handler->migrate_task_event)
1664 return sched->tp_handler->migrate_task_event(sched, evsel, sample, machine);
1669 typedef int (*tracepoint_handler)(struct perf_tool *tool,
1670 struct perf_evsel *evsel,
1671 struct perf_sample *sample,
1672 struct machine *machine);
1674 static int perf_sched__process_tracepoint_sample(struct perf_tool *tool __maybe_unused,
1675 union perf_event *event __maybe_unused,
1676 struct perf_sample *sample,
1677 struct perf_evsel *evsel,
1678 struct machine *machine)
1682 if (evsel->handler != NULL) {
1683 tracepoint_handler f = evsel->handler;
1684 err = f(tool, evsel, sample, machine);
1690 static int perf_sched__read_events(struct perf_sched *sched)
1692 const struct perf_evsel_str_handler handlers[] = {
1693 { "sched:sched_switch", process_sched_switch_event, },
1694 { "sched:sched_stat_runtime", process_sched_runtime_event, },
1695 { "sched:sched_wakeup", process_sched_wakeup_event, },
1696 { "sched:sched_wakeup_new", process_sched_wakeup_event, },
1697 { "sched:sched_migrate_task", process_sched_migrate_task_event, },
1699 struct perf_session *session;
1700 struct perf_data_file file = {
1702 .mode = PERF_DATA_MODE_READ,
1703 .force = sched->force,
1707 session = perf_session__new(&file, false, &sched->tool);
1708 if (session == NULL) {
1709 pr_debug("No Memory for session\n");
1713 symbol__init(&session->header.env);
1715 if (perf_session__set_tracepoints_handlers(session, handlers))
1718 if (perf_session__has_traces(session, "record -R")) {
1719 int err = perf_session__process_events(session);
1721 pr_err("Failed to process events, error %d", err);
1725 sched->nr_events = session->evlist->stats.nr_events[0];
1726 sched->nr_lost_events = session->evlist->stats.total_lost;
1727 sched->nr_lost_chunks = session->evlist->stats.nr_events[PERF_RECORD_LOST];
1732 perf_session__delete(session);
1737 * scheduling times are printed as msec.usec
1739 static inline void print_sched_time(unsigned long long nsecs, int width)
1741 unsigned long msecs;
1742 unsigned long usecs;
1744 msecs = nsecs / NSEC_PER_MSEC;
1745 nsecs -= msecs * NSEC_PER_MSEC;
1746 usecs = nsecs / NSEC_PER_USEC;
1747 printf("%*lu.%03lu ", width, msecs, usecs);
1751 * returns runtime data for event, allocating memory for it the
1752 * first time it is used.
1754 static struct evsel_runtime *perf_evsel__get_runtime(struct perf_evsel *evsel)
1756 struct evsel_runtime *r = evsel->priv;
1759 r = zalloc(sizeof(struct evsel_runtime));
1767 * save last time event was seen per cpu
1769 static void perf_evsel__save_time(struct perf_evsel *evsel,
1770 u64 timestamp, u32 cpu)
1772 struct evsel_runtime *r = perf_evsel__get_runtime(evsel);
1777 if ((cpu >= r->ncpu) || (r->last_time == NULL)) {
1778 int i, n = __roundup_pow_of_two(cpu+1);
1779 void *p = r->last_time;
1781 p = realloc(r->last_time, n * sizeof(u64));
1786 for (i = r->ncpu; i < n; ++i)
1787 r->last_time[i] = (u64) 0;
1792 r->last_time[cpu] = timestamp;
1795 /* returns last time this event was seen on the given cpu */
1796 static u64 perf_evsel__get_time(struct perf_evsel *evsel, u32 cpu)
1798 struct evsel_runtime *r = perf_evsel__get_runtime(evsel);
1800 if ((r == NULL) || (r->last_time == NULL) || (cpu >= r->ncpu))
1803 return r->last_time[cpu];
1806 static int comm_width = 30;
1808 static char *timehist_get_commstr(struct thread *thread)
1810 static char str[32];
1811 const char *comm = thread__comm_str(thread);
1812 pid_t tid = thread->tid;
1813 pid_t pid = thread->pid_;
1817 n = scnprintf(str, sizeof(str), "%s", comm);
1819 else if (tid != pid)
1820 n = scnprintf(str, sizeof(str), "%s[%d/%d]", comm, tid, pid);
1823 n = scnprintf(str, sizeof(str), "%s[%d]", comm, tid);
1831 static void timehist_header(struct perf_sched *sched)
1833 u32 ncpus = sched->max_cpu + 1;
1836 printf("%15s %6s ", "time", "cpu");
1838 if (sched->show_cpu_visual) {
1840 for (i = 0, j = 0; i < ncpus; ++i) {
1848 printf(" %-*s %9s %9s %9s", comm_width,
1849 "task name", "wait time", "sch delay", "run time");
1851 if (sched->show_state)
1852 printf(" %s", "state");
1859 printf("%15s %-6s ", "", "");
1861 if (sched->show_cpu_visual)
1862 printf(" %*s ", ncpus, "");
1864 printf(" %-*s %9s %9s %9s", comm_width,
1865 "[tid/pid]", "(msec)", "(msec)", "(msec)");
1867 if (sched->show_state)
1875 printf("%.15s %.6s ", graph_dotted_line, graph_dotted_line);
1877 if (sched->show_cpu_visual)
1878 printf(" %.*s ", ncpus, graph_dotted_line);
1880 printf(" %.*s %.9s %.9s %.9s", comm_width,
1881 graph_dotted_line, graph_dotted_line, graph_dotted_line,
1884 if (sched->show_state)
1885 printf(" %.5s", graph_dotted_line);
1890 static char task_state_char(struct thread *thread, int state)
1892 static const char state_to_char[] = TASK_STATE_TO_CHAR_STR;
1893 unsigned bit = state ? ffs(state) : 0;
1896 if (thread->tid == 0)
1899 return bit < sizeof(state_to_char) - 1 ? state_to_char[bit] : '?';
1902 static void timehist_print_sample(struct perf_sched *sched,
1903 struct perf_evsel *evsel,
1904 struct perf_sample *sample,
1905 struct addr_location *al,
1906 struct thread *thread,
1909 struct thread_runtime *tr = thread__priv(thread);
1910 const char *next_comm = perf_evsel__strval(evsel, sample, "next_comm");
1911 const u32 next_pid = perf_evsel__intval(evsel, sample, "next_pid");
1912 u32 max_cpus = sched->max_cpu + 1;
1917 timestamp__scnprintf_usec(t, tstr, sizeof(tstr));
1918 printf("%15s [%04d] ", tstr, sample->cpu);
1920 if (sched->show_cpu_visual) {
1925 for (i = 0; i < max_cpus; ++i) {
1926 /* flag idle times with 'i'; others are sched events */
1927 if (i == sample->cpu)
1928 c = (thread->tid == 0) ? 'i' : 's';
1936 printf(" %-*s ", comm_width, timehist_get_commstr(thread));
1938 wait_time = tr->dt_sleep + tr->dt_iowait + tr->dt_preempt;
1939 print_sched_time(wait_time, 6);
1941 print_sched_time(tr->dt_delay, 6);
1942 print_sched_time(tr->dt_run, 6);
1944 if (sched->show_state)
1945 printf(" %5c ", task_state_char(thread, state));
1947 if (sched->show_next) {
1948 snprintf(nstr, sizeof(nstr), "next: %s[%d]", next_comm, next_pid);
1949 printf(" %-*s", comm_width, nstr);
1952 if (sched->show_wakeups && !sched->show_next)
1953 printf(" %-*s", comm_width, "");
1955 if (thread->tid == 0)
1958 if (sched->show_callchain)
1961 sample__fprintf_sym(sample, al, 0,
1962 EVSEL__PRINT_SYM | EVSEL__PRINT_ONELINE |
1963 EVSEL__PRINT_CALLCHAIN_ARROW |
1964 EVSEL__PRINT_SKIP_IGNORED,
1965 &callchain_cursor, stdout);
1972 * Explanation of delta-time stats:
1974 * t = time of current schedule out event
1975 * tprev = time of previous sched out event
1976 * also time of schedule-in event for current task
1977 * last_time = time of last sched change event for current task
1978 * (i.e, time process was last scheduled out)
1979 * ready_to_run = time of wakeup for current task
1981 * -----|------------|------------|------------|------
1982 * last ready tprev t
1985 * |-------- dt_wait --------|
1986 * |- dt_delay -|-- dt_run --|
1988 * dt_run = run time of current task
1989 * dt_wait = time between last schedule out event for task and tprev
1990 * represents time spent off the cpu
1991 * dt_delay = time between wakeup and schedule-in of task
1994 static void timehist_update_runtime_stats(struct thread_runtime *r,
2004 r->dt_run = t - tprev;
2005 if (r->ready_to_run) {
2006 if (r->ready_to_run > tprev)
2007 pr_debug("time travel: wakeup time for task > previous sched_switch event\n");
2009 r->dt_delay = tprev - r->ready_to_run;
2012 if (r->last_time > tprev)
2013 pr_debug("time travel: last sched out time for task > previous sched_switch event\n");
2014 else if (r->last_time) {
2015 u64 dt_wait = tprev - r->last_time;
2017 if (r->last_state == TASK_RUNNING)
2018 r->dt_preempt = dt_wait;
2019 else if (r->last_state == TASK_UNINTERRUPTIBLE)
2020 r->dt_iowait = dt_wait;
2022 r->dt_sleep = dt_wait;
2026 update_stats(&r->run_stats, r->dt_run);
2028 r->total_run_time += r->dt_run;
2029 r->total_delay_time += r->dt_delay;
2030 r->total_sleep_time += r->dt_sleep;
2031 r->total_iowait_time += r->dt_iowait;
2032 r->total_preempt_time += r->dt_preempt;
2035 static bool is_idle_sample(struct perf_sample *sample,
2036 struct perf_evsel *evsel)
2038 /* pid 0 == swapper == idle task */
2039 if (strcmp(perf_evsel__name(evsel), "sched:sched_switch") == 0)
2040 return perf_evsel__intval(evsel, sample, "prev_pid") == 0;
2042 return sample->pid == 0;
2045 static void save_task_callchain(struct perf_sched *sched,
2046 struct perf_sample *sample,
2047 struct perf_evsel *evsel,
2048 struct machine *machine)
2050 struct callchain_cursor *cursor = &callchain_cursor;
2051 struct thread *thread;
2053 /* want main thread for process - has maps */
2054 thread = machine__findnew_thread(machine, sample->pid, sample->pid);
2055 if (thread == NULL) {
2056 pr_debug("Failed to get thread for pid %d.\n", sample->pid);
2060 if (!symbol_conf.use_callchain || sample->callchain == NULL)
2063 if (thread__resolve_callchain(thread, cursor, evsel, sample,
2064 NULL, NULL, sched->max_stack + 2) != 0) {
2066 error("Failed to resolve callchain. Skipping\n");
2071 callchain_cursor_commit(cursor);
2074 struct callchain_cursor_node *node;
2077 node = callchain_cursor_current(cursor);
2083 if (!strcmp(sym->name, "schedule") ||
2084 !strcmp(sym->name, "__schedule") ||
2085 !strcmp(sym->name, "preempt_schedule"))
2089 callchain_cursor_advance(cursor);
2093 static int init_idle_thread(struct thread *thread)
2095 struct idle_thread_runtime *itr;
2097 thread__set_comm(thread, idle_comm, 0);
2099 itr = zalloc(sizeof(*itr));
2103 init_stats(&itr->tr.run_stats);
2104 callchain_init(&itr->callchain);
2105 callchain_cursor_reset(&itr->cursor);
2106 thread__set_priv(thread, itr);
2112 * Track idle stats per cpu by maintaining a local thread
2113 * struct for the idle task on each cpu.
2115 static int init_idle_threads(int ncpu)
2119 idle_threads = zalloc(ncpu * sizeof(struct thread *));
2123 idle_max_cpu = ncpu;
2125 /* allocate the actual thread struct if needed */
2126 for (i = 0; i < ncpu; ++i) {
2127 idle_threads[i] = thread__new(0, 0);
2128 if (idle_threads[i] == NULL)
2131 ret = init_idle_thread(idle_threads[i]);
2139 static void free_idle_threads(void)
2143 if (idle_threads == NULL)
2146 for (i = 0; i < idle_max_cpu; ++i) {
2147 if ((idle_threads[i]))
2148 thread__delete(idle_threads[i]);
2154 static struct thread *get_idle_thread(int cpu)
2157 * expand/allocate array of pointers to local thread
2160 if ((cpu >= idle_max_cpu) || (idle_threads == NULL)) {
2161 int i, j = __roundup_pow_of_two(cpu+1);
2164 p = realloc(idle_threads, j * sizeof(struct thread *));
2168 idle_threads = (struct thread **) p;
2169 for (i = idle_max_cpu; i < j; ++i)
2170 idle_threads[i] = NULL;
2175 /* allocate a new thread struct if needed */
2176 if (idle_threads[cpu] == NULL) {
2177 idle_threads[cpu] = thread__new(0, 0);
2179 if (idle_threads[cpu]) {
2180 if (init_idle_thread(idle_threads[cpu]) < 0)
2185 return idle_threads[cpu];
2188 static void save_idle_callchain(struct idle_thread_runtime *itr,
2189 struct perf_sample *sample)
2191 if (!symbol_conf.use_callchain || sample->callchain == NULL)
2194 callchain_cursor__copy(&itr->cursor, &callchain_cursor);
2198 * handle runtime stats saved per thread
2200 static struct thread_runtime *thread__init_runtime(struct thread *thread)
2202 struct thread_runtime *r;
2204 r = zalloc(sizeof(struct thread_runtime));
2208 init_stats(&r->run_stats);
2209 thread__set_priv(thread, r);
2214 static struct thread_runtime *thread__get_runtime(struct thread *thread)
2216 struct thread_runtime *tr;
2218 tr = thread__priv(thread);
2220 tr = thread__init_runtime(thread);
2222 pr_debug("Failed to malloc memory for runtime data.\n");
2228 static struct thread *timehist_get_thread(struct perf_sched *sched,
2229 struct perf_sample *sample,
2230 struct machine *machine,
2231 struct perf_evsel *evsel)
2233 struct thread *thread;
2235 if (is_idle_sample(sample, evsel)) {
2236 thread = get_idle_thread(sample->cpu);
2238 pr_err("Failed to get idle thread for cpu %d.\n", sample->cpu);
2241 /* there were samples with tid 0 but non-zero pid */
2242 thread = machine__findnew_thread(machine, sample->pid,
2243 sample->tid ?: sample->pid);
2244 if (thread == NULL) {
2245 pr_debug("Failed to get thread for tid %d. skipping sample.\n",
2249 save_task_callchain(sched, sample, evsel, machine);
2250 if (sched->idle_hist) {
2251 struct thread *idle;
2252 struct idle_thread_runtime *itr;
2254 idle = get_idle_thread(sample->cpu);
2256 pr_err("Failed to get idle thread for cpu %d.\n", sample->cpu);
2260 itr = thread__priv(idle);
2264 itr->last_thread = thread;
2266 /* copy task callchain when entering to idle */
2267 if (perf_evsel__intval(evsel, sample, "next_pid") == 0)
2268 save_idle_callchain(itr, sample);
2275 static bool timehist_skip_sample(struct perf_sched *sched,
2276 struct thread *thread,
2277 struct perf_evsel *evsel,
2278 struct perf_sample *sample)
2282 if (thread__is_filtered(thread)) {
2284 sched->skipped_samples++;
2287 if (sched->idle_hist) {
2288 if (strcmp(perf_evsel__name(evsel), "sched:sched_switch"))
2290 else if (perf_evsel__intval(evsel, sample, "prev_pid") != 0 &&
2291 perf_evsel__intval(evsel, sample, "next_pid") != 0)
2298 static void timehist_print_wakeup_event(struct perf_sched *sched,
2299 struct perf_evsel *evsel,
2300 struct perf_sample *sample,
2301 struct machine *machine,
2302 struct thread *awakened)
2304 struct thread *thread;
2307 thread = machine__findnew_thread(machine, sample->pid, sample->tid);
2311 /* show wakeup unless both awakee and awaker are filtered */
2312 if (timehist_skip_sample(sched, thread, evsel, sample) &&
2313 timehist_skip_sample(sched, awakened, evsel, sample)) {
2317 timestamp__scnprintf_usec(sample->time, tstr, sizeof(tstr));
2318 printf("%15s [%04d] ", tstr, sample->cpu);
2319 if (sched->show_cpu_visual)
2320 printf(" %*s ", sched->max_cpu + 1, "");
2322 printf(" %-*s ", comm_width, timehist_get_commstr(thread));
2325 printf(" %9s %9s %9s ", "", "", "");
2327 printf("awakened: %s", timehist_get_commstr(awakened));
2332 static int timehist_sched_wakeup_event(struct perf_tool *tool,
2333 union perf_event *event __maybe_unused,
2334 struct perf_evsel *evsel,
2335 struct perf_sample *sample,
2336 struct machine *machine)
2338 struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
2339 struct thread *thread;
2340 struct thread_runtime *tr = NULL;
2341 /* want pid of awakened task not pid in sample */
2342 const u32 pid = perf_evsel__intval(evsel, sample, "pid");
2344 thread = machine__findnew_thread(machine, 0, pid);
2348 tr = thread__get_runtime(thread);
2352 if (tr->ready_to_run == 0)
2353 tr->ready_to_run = sample->time;
2355 /* show wakeups if requested */
2356 if (sched->show_wakeups &&
2357 !perf_time__skip_sample(&sched->ptime, sample->time))
2358 timehist_print_wakeup_event(sched, evsel, sample, machine, thread);
2363 static void timehist_print_migration_event(struct perf_sched *sched,
2364 struct perf_evsel *evsel,
2365 struct perf_sample *sample,
2366 struct machine *machine,
2367 struct thread *migrated)
2369 struct thread *thread;
2371 u32 max_cpus = sched->max_cpu + 1;
2374 if (sched->summary_only)
2377 max_cpus = sched->max_cpu + 1;
2378 ocpu = perf_evsel__intval(evsel, sample, "orig_cpu");
2379 dcpu = perf_evsel__intval(evsel, sample, "dest_cpu");
2381 thread = machine__findnew_thread(machine, sample->pid, sample->tid);
2385 if (timehist_skip_sample(sched, thread, evsel, sample) &&
2386 timehist_skip_sample(sched, migrated, evsel, sample)) {
2390 timestamp__scnprintf_usec(sample->time, tstr, sizeof(tstr));
2391 printf("%15s [%04d] ", tstr, sample->cpu);
2393 if (sched->show_cpu_visual) {
2398 for (i = 0; i < max_cpus; ++i) {
2399 c = (i == sample->cpu) ? 'm' : ' ';
2405 printf(" %-*s ", comm_width, timehist_get_commstr(thread));
2408 printf(" %9s %9s %9s ", "", "", "");
2410 printf("migrated: %s", timehist_get_commstr(migrated));
2411 printf(" cpu %d => %d", ocpu, dcpu);
2416 static int timehist_migrate_task_event(struct perf_tool *tool,
2417 union perf_event *event __maybe_unused,
2418 struct perf_evsel *evsel,
2419 struct perf_sample *sample,
2420 struct machine *machine)
2422 struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
2423 struct thread *thread;
2424 struct thread_runtime *tr = NULL;
2425 /* want pid of migrated task not pid in sample */
2426 const u32 pid = perf_evsel__intval(evsel, sample, "pid");
2428 thread = machine__findnew_thread(machine, 0, pid);
2432 tr = thread__get_runtime(thread);
2438 /* show migrations if requested */
2439 timehist_print_migration_event(sched, evsel, sample, machine, thread);
2444 static int timehist_sched_change_event(struct perf_tool *tool,
2445 union perf_event *event,
2446 struct perf_evsel *evsel,
2447 struct perf_sample *sample,
2448 struct machine *machine)
2450 struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
2451 struct perf_time_interval *ptime = &sched->ptime;
2452 struct addr_location al;
2453 struct thread *thread;
2454 struct thread_runtime *tr = NULL;
2455 u64 tprev, t = sample->time;
2457 int state = perf_evsel__intval(evsel, sample, "prev_state");
2460 if (machine__resolve(machine, &al, sample) < 0) {
2461 pr_err("problem processing %d event. skipping it\n",
2462 event->header.type);
2467 thread = timehist_get_thread(sched, sample, machine, evsel);
2468 if (thread == NULL) {
2473 if (timehist_skip_sample(sched, thread, evsel, sample))
2476 tr = thread__get_runtime(thread);
2482 tprev = perf_evsel__get_time(evsel, sample->cpu);
2485 * If start time given:
2486 * - sample time is under window user cares about - skip sample
2487 * - tprev is under window user cares about - reset to start of window
2489 if (ptime->start && ptime->start > t)
2492 if (tprev && ptime->start > tprev)
2493 tprev = ptime->start;
2496 * If end time given:
2497 * - previous sched event is out of window - we are done
2498 * - sample time is beyond window user cares about - reset it
2499 * to close out stats for time window interest
2502 if (tprev > ptime->end)
2509 if (!sched->idle_hist || thread->tid == 0) {
2510 timehist_update_runtime_stats(tr, t, tprev);
2512 if (sched->idle_hist) {
2513 struct idle_thread_runtime *itr = (void *)tr;
2514 struct thread_runtime *last_tr;
2516 BUG_ON(thread->tid != 0);
2518 if (itr->last_thread == NULL)
2521 /* add current idle time as last thread's runtime */
2522 last_tr = thread__get_runtime(itr->last_thread);
2523 if (last_tr == NULL)
2526 timehist_update_runtime_stats(last_tr, t, tprev);
2528 * remove delta time of last thread as it's not updated
2529 * and otherwise it will show an invalid value next
2530 * time. we only care total run time and run stat.
2532 last_tr->dt_run = 0;
2533 last_tr->dt_delay = 0;
2534 last_tr->dt_sleep = 0;
2535 last_tr->dt_iowait = 0;
2536 last_tr->dt_preempt = 0;
2539 callchain_append(&itr->callchain, &itr->cursor, t - tprev);
2541 itr->last_thread = NULL;
2545 if (!sched->summary_only)
2546 timehist_print_sample(sched, evsel, sample, &al, thread, t, state);
2549 if (sched->hist_time.start == 0 && t >= ptime->start)
2550 sched->hist_time.start = t;
2551 if (ptime->end == 0 || t <= ptime->end)
2552 sched->hist_time.end = t;
2555 /* time of this sched_switch event becomes last time task seen */
2556 tr->last_time = sample->time;
2558 /* last state is used to determine where to account wait time */
2559 tr->last_state = state;
2561 /* sched out event for task so reset ready to run time */
2562 tr->ready_to_run = 0;
2565 perf_evsel__save_time(evsel, sample->time, sample->cpu);
2570 static int timehist_sched_switch_event(struct perf_tool *tool,
2571 union perf_event *event,
2572 struct perf_evsel *evsel,
2573 struct perf_sample *sample,
2574 struct machine *machine __maybe_unused)
2576 return timehist_sched_change_event(tool, event, evsel, sample, machine);
2579 static int process_lost(struct perf_tool *tool __maybe_unused,
2580 union perf_event *event,
2581 struct perf_sample *sample,
2582 struct machine *machine __maybe_unused)
2586 timestamp__scnprintf_usec(sample->time, tstr, sizeof(tstr));
2587 printf("%15s ", tstr);
2588 printf("lost %" PRIu64 " events on cpu %d\n", event->lost.lost, sample->cpu);
2594 static void print_thread_runtime(struct thread *t,
2595 struct thread_runtime *r)
2597 double mean = avg_stats(&r->run_stats);
2600 printf("%*s %5d %9" PRIu64 " ",
2601 comm_width, timehist_get_commstr(t), t->ppid,
2602 (u64) r->run_stats.n);
2604 print_sched_time(r->total_run_time, 8);
2605 stddev = rel_stddev_stats(stddev_stats(&r->run_stats), mean);
2606 print_sched_time(r->run_stats.min, 6);
2608 print_sched_time((u64) mean, 6);
2610 print_sched_time(r->run_stats.max, 6);
2612 printf("%5.2f", stddev);
2613 printf(" %5" PRIu64, r->migrations);
2617 static void print_thread_waittime(struct thread *t,
2618 struct thread_runtime *r)
2620 printf("%*s %5d %9" PRIu64 " ",
2621 comm_width, timehist_get_commstr(t), t->ppid,
2622 (u64) r->run_stats.n);
2624 print_sched_time(r->total_run_time, 8);
2625 print_sched_time(r->total_sleep_time, 6);
2627 print_sched_time(r->total_iowait_time, 6);
2629 print_sched_time(r->total_preempt_time, 6);
2631 print_sched_time(r->total_delay_time, 6);
2635 struct total_run_stats {
2636 struct perf_sched *sched;
2642 static int __show_thread_runtime(struct thread *t, void *priv)
2644 struct total_run_stats *stats = priv;
2645 struct thread_runtime *r;
2647 if (thread__is_filtered(t))
2650 r = thread__priv(t);
2651 if (r && r->run_stats.n) {
2652 stats->task_count++;
2653 stats->sched_count += r->run_stats.n;
2654 stats->total_run_time += r->total_run_time;
2656 if (stats->sched->show_state)
2657 print_thread_waittime(t, r);
2659 print_thread_runtime(t, r);
2665 static int show_thread_runtime(struct thread *t, void *priv)
2670 return __show_thread_runtime(t, priv);
2673 static int show_deadthread_runtime(struct thread *t, void *priv)
2678 return __show_thread_runtime(t, priv);
2681 static size_t callchain__fprintf_folded(FILE *fp, struct callchain_node *node)
2683 const char *sep = " <- ";
2684 struct callchain_list *chain;
2692 ret = callchain__fprintf_folded(fp, node->parent);
2695 list_for_each_entry(chain, &node->val, list) {
2696 if (chain->ip >= PERF_CONTEXT_MAX)
2698 if (chain->ms.sym && chain->ms.sym->ignore)
2700 ret += fprintf(fp, "%s%s", first ? "" : sep,
2701 callchain_list__sym_name(chain, bf, sizeof(bf),
2709 static size_t timehist_print_idlehist_callchain(struct rb_root *root)
2713 struct callchain_node *chain;
2714 struct rb_node *rb_node = rb_first(root);
2716 printf(" %16s %8s %s\n", "Idle time (msec)", "Count", "Callchains");
2717 printf(" %.16s %.8s %.50s\n", graph_dotted_line, graph_dotted_line,
2721 chain = rb_entry(rb_node, struct callchain_node, rb_node);
2722 rb_node = rb_next(rb_node);
2724 ret += fprintf(fp, " ");
2725 print_sched_time(chain->hit, 12);
2726 ret += 16; /* print_sched_time returns 2nd arg + 4 */
2727 ret += fprintf(fp, " %8d ", chain->count);
2728 ret += callchain__fprintf_folded(fp, chain);
2729 ret += fprintf(fp, "\n");
2735 static void timehist_print_summary(struct perf_sched *sched,
2736 struct perf_session *session)
2738 struct machine *m = &session->machines.host;
2739 struct total_run_stats totals;
2742 struct thread_runtime *r;
2744 u64 hist_time = sched->hist_time.end - sched->hist_time.start;
2746 memset(&totals, 0, sizeof(totals));
2747 totals.sched = sched;
2749 if (sched->idle_hist) {
2750 printf("\nIdle-time summary\n");
2751 printf("%*s parent sched-out ", comm_width, "comm");
2752 printf(" idle-time min-idle avg-idle max-idle stddev migrations\n");
2753 } else if (sched->show_state) {
2754 printf("\nWait-time summary\n");
2755 printf("%*s parent sched-in ", comm_width, "comm");
2756 printf(" run-time sleep iowait preempt delay\n");
2758 printf("\nRuntime summary\n");
2759 printf("%*s parent sched-in ", comm_width, "comm");
2760 printf(" run-time min-run avg-run max-run stddev migrations\n");
2762 printf("%*s (count) ", comm_width, "");
2763 printf(" (msec) (msec) (msec) (msec) %s\n",
2764 sched->show_state ? "(msec)" : "%");
2765 printf("%.117s\n", graph_dotted_line);
2767 machine__for_each_thread(m, show_thread_runtime, &totals);
2768 task_count = totals.task_count;
2770 printf("<no still running tasks>\n");
2772 printf("\nTerminated tasks:\n");
2773 machine__for_each_thread(m, show_deadthread_runtime, &totals);
2774 if (task_count == totals.task_count)
2775 printf("<no terminated tasks>\n");
2777 /* CPU idle stats not tracked when samples were skipped */
2778 if (sched->skipped_samples && !sched->idle_hist)
2781 printf("\nIdle stats:\n");
2782 for (i = 0; i < idle_max_cpu; ++i) {
2783 t = idle_threads[i];
2787 r = thread__priv(t);
2788 if (r && r->run_stats.n) {
2789 totals.sched_count += r->run_stats.n;
2790 printf(" CPU %2d idle for ", i);
2791 print_sched_time(r->total_run_time, 6);
2792 printf(" msec (%6.2f%%)\n", 100.0 * r->total_run_time / hist_time);
2794 printf(" CPU %2d idle entire time window\n", i);
2797 if (sched->idle_hist && symbol_conf.use_callchain) {
2798 callchain_param.mode = CHAIN_FOLDED;
2799 callchain_param.value = CCVAL_PERIOD;
2801 callchain_register_param(&callchain_param);
2803 printf("\nIdle stats by callchain:\n");
2804 for (i = 0; i < idle_max_cpu; ++i) {
2805 struct idle_thread_runtime *itr;
2807 t = idle_threads[i];
2811 itr = thread__priv(t);
2815 callchain_param.sort(&itr->sorted_root, &itr->callchain,
2816 0, &callchain_param);
2818 printf(" CPU %2d:", i);
2819 print_sched_time(itr->tr.total_run_time, 6);
2821 timehist_print_idlehist_callchain(&itr->sorted_root);
2827 " Total number of unique tasks: %" PRIu64 "\n"
2828 "Total number of context switches: %" PRIu64 "\n",
2829 totals.task_count, totals.sched_count);
2831 printf(" Total run time (msec): ");
2832 print_sched_time(totals.total_run_time, 2);
2835 printf(" Total scheduling time (msec): ");
2836 print_sched_time(hist_time, 2);
2837 printf(" (x %d)\n", sched->max_cpu);
2840 typedef int (*sched_handler)(struct perf_tool *tool,
2841 union perf_event *event,
2842 struct perf_evsel *evsel,
2843 struct perf_sample *sample,
2844 struct machine *machine);
2846 static int perf_timehist__process_sample(struct perf_tool *tool,
2847 union perf_event *event,
2848 struct perf_sample *sample,
2849 struct perf_evsel *evsel,
2850 struct machine *machine)
2852 struct perf_sched *sched = container_of(tool, struct perf_sched, tool);
2854 int this_cpu = sample->cpu;
2856 if (this_cpu > sched->max_cpu)
2857 sched->max_cpu = this_cpu;
2859 if (evsel->handler != NULL) {
2860 sched_handler f = evsel->handler;
2862 err = f(tool, event, evsel, sample, machine);
2868 static int timehist_check_attr(struct perf_sched *sched,
2869 struct perf_evlist *evlist)
2871 struct perf_evsel *evsel;
2872 struct evsel_runtime *er;
2874 list_for_each_entry(evsel, &evlist->entries, node) {
2875 er = perf_evsel__get_runtime(evsel);
2877 pr_err("Failed to allocate memory for evsel runtime data\n");
2881 if (sched->show_callchain &&
2882 !(evsel->attr.sample_type & PERF_SAMPLE_CALLCHAIN)) {
2883 pr_info("Samples do not have callchains.\n");
2884 sched->show_callchain = 0;
2885 symbol_conf.use_callchain = 0;
2892 static int perf_sched__timehist(struct perf_sched *sched)
2894 const struct perf_evsel_str_handler handlers[] = {
2895 { "sched:sched_switch", timehist_sched_switch_event, },
2896 { "sched:sched_wakeup", timehist_sched_wakeup_event, },
2897 { "sched:sched_wakeup_new", timehist_sched_wakeup_event, },
2899 const struct perf_evsel_str_handler migrate_handlers[] = {
2900 { "sched:sched_migrate_task", timehist_migrate_task_event, },
2902 struct perf_data_file file = {
2904 .mode = PERF_DATA_MODE_READ,
2905 .force = sched->force,
2908 struct perf_session *session;
2909 struct perf_evlist *evlist;
2913 * event handlers for timehist option
2915 sched->tool.sample = perf_timehist__process_sample;
2916 sched->tool.mmap = perf_event__process_mmap;
2917 sched->tool.comm = perf_event__process_comm;
2918 sched->tool.exit = perf_event__process_exit;
2919 sched->tool.fork = perf_event__process_fork;
2920 sched->tool.lost = process_lost;
2921 sched->tool.attr = perf_event__process_attr;
2922 sched->tool.tracing_data = perf_event__process_tracing_data;
2923 sched->tool.build_id = perf_event__process_build_id;
2925 sched->tool.ordered_events = true;
2926 sched->tool.ordering_requires_timestamps = true;
2928 symbol_conf.use_callchain = sched->show_callchain;
2930 session = perf_session__new(&file, false, &sched->tool);
2931 if (session == NULL)
2934 evlist = session->evlist;
2936 symbol__init(&session->header.env);
2938 if (perf_time__parse_str(&sched->ptime, sched->time_str) != 0) {
2939 pr_err("Invalid time string\n");
2943 if (timehist_check_attr(sched, evlist) != 0)
2948 /* setup per-evsel handlers */
2949 if (perf_session__set_tracepoints_handlers(session, handlers))
2952 /* sched_switch event at a minimum needs to exist */
2953 if (!perf_evlist__find_tracepoint_by_name(session->evlist,
2954 "sched:sched_switch")) {
2955 pr_err("No sched_switch events found. Have you run 'perf sched record'?\n");
2959 if (sched->show_migrations &&
2960 perf_session__set_tracepoints_handlers(session, migrate_handlers))
2963 /* pre-allocate struct for per-CPU idle stats */
2964 sched->max_cpu = session->header.env.nr_cpus_online;
2965 if (sched->max_cpu == 0)
2967 if (init_idle_threads(sched->max_cpu))
2970 /* summary_only implies summary option, but don't overwrite summary if set */
2971 if (sched->summary_only)
2972 sched->summary = sched->summary_only;
2974 if (!sched->summary_only)
2975 timehist_header(sched);
2977 err = perf_session__process_events(session);
2979 pr_err("Failed to process events, error %d", err);
2983 sched->nr_events = evlist->stats.nr_events[0];
2984 sched->nr_lost_events = evlist->stats.total_lost;
2985 sched->nr_lost_chunks = evlist->stats.nr_events[PERF_RECORD_LOST];
2988 timehist_print_summary(sched, session);
2991 free_idle_threads();
2992 perf_session__delete(session);
2998 static void print_bad_events(struct perf_sched *sched)
3000 if (sched->nr_unordered_timestamps && sched->nr_timestamps) {
3001 printf(" INFO: %.3f%% unordered timestamps (%ld out of %ld)\n",
3002 (double)sched->nr_unordered_timestamps/(double)sched->nr_timestamps*100.0,
3003 sched->nr_unordered_timestamps, sched->nr_timestamps);
3005 if (sched->nr_lost_events && sched->nr_events) {
3006 printf(" INFO: %.3f%% lost events (%ld out of %ld, in %ld chunks)\n",
3007 (double)sched->nr_lost_events/(double)sched->nr_events * 100.0,
3008 sched->nr_lost_events, sched->nr_events, sched->nr_lost_chunks);
3010 if (sched->nr_context_switch_bugs && sched->nr_timestamps) {
3011 printf(" INFO: %.3f%% context switch bugs (%ld out of %ld)",
3012 (double)sched->nr_context_switch_bugs/(double)sched->nr_timestamps*100.0,
3013 sched->nr_context_switch_bugs, sched->nr_timestamps);
3014 if (sched->nr_lost_events)
3015 printf(" (due to lost events?)");
3020 static void __merge_work_atoms(struct rb_root *root, struct work_atoms *data)
3022 struct rb_node **new = &(root->rb_node), *parent = NULL;
3023 struct work_atoms *this;
3024 const char *comm = thread__comm_str(data->thread), *this_comm;
3029 this = container_of(*new, struct work_atoms, node);
3032 this_comm = thread__comm_str(this->thread);
3033 cmp = strcmp(comm, this_comm);
3035 new = &((*new)->rb_left);
3036 } else if (cmp < 0) {
3037 new = &((*new)->rb_right);
3040 this->total_runtime += data->total_runtime;
3041 this->nb_atoms += data->nb_atoms;
3042 this->total_lat += data->total_lat;
3043 list_splice(&data->work_list, &this->work_list);
3044 if (this->max_lat < data->max_lat) {
3045 this->max_lat = data->max_lat;
3046 this->max_lat_at = data->max_lat_at;
3054 rb_link_node(&data->node, parent, new);
3055 rb_insert_color(&data->node, root);
3058 static void perf_sched__merge_lat(struct perf_sched *sched)
3060 struct work_atoms *data;
3061 struct rb_node *node;
3063 if (sched->skip_merge)
3066 while ((node = rb_first(&sched->atom_root))) {
3067 rb_erase(node, &sched->atom_root);
3068 data = rb_entry(node, struct work_atoms, node);
3069 __merge_work_atoms(&sched->merged_atom_root, data);
3073 static int perf_sched__lat(struct perf_sched *sched)
3075 struct rb_node *next;
3079 if (perf_sched__read_events(sched))
3082 perf_sched__merge_lat(sched);
3083 perf_sched__sort_lat(sched);
3085 printf("\n -----------------------------------------------------------------------------------------------------------------\n");
3086 printf(" Task | Runtime ms | Switches | Average delay ms | Maximum delay ms | Maximum delay at |\n");
3087 printf(" -----------------------------------------------------------------------------------------------------------------\n");
3089 next = rb_first(&sched->sorted_atom_root);
3092 struct work_atoms *work_list;
3094 work_list = rb_entry(next, struct work_atoms, node);
3095 output_lat_thread(sched, work_list);
3096 next = rb_next(next);
3097 thread__zput(work_list->thread);
3100 printf(" -----------------------------------------------------------------------------------------------------------------\n");
3101 printf(" TOTAL: |%11.3f ms |%9" PRIu64 " |\n",
3102 (double)sched->all_runtime / NSEC_PER_MSEC, sched->all_count);
3104 printf(" ---------------------------------------------------\n");
3106 print_bad_events(sched);
3112 static int setup_map_cpus(struct perf_sched *sched)
3114 struct cpu_map *map;
3116 sched->max_cpu = sysconf(_SC_NPROCESSORS_CONF);
3118 if (sched->map.comp) {
3119 sched->map.comp_cpus = zalloc(sched->max_cpu * sizeof(int));
3120 if (!sched->map.comp_cpus)
3124 if (!sched->map.cpus_str)
3127 map = cpu_map__new(sched->map.cpus_str);
3129 pr_err("failed to get cpus map from %s\n", sched->map.cpus_str);
3133 sched->map.cpus = map;
3137 static int setup_color_pids(struct perf_sched *sched)
3139 struct thread_map *map;
3141 if (!sched->map.color_pids_str)
3144 map = thread_map__new_by_tid_str(sched->map.color_pids_str);
3146 pr_err("failed to get thread map from %s\n", sched->map.color_pids_str);
3150 sched->map.color_pids = map;
3154 static int setup_color_cpus(struct perf_sched *sched)
3156 struct cpu_map *map;
3158 if (!sched->map.color_cpus_str)
3161 map = cpu_map__new(sched->map.color_cpus_str);
3163 pr_err("failed to get thread map from %s\n", sched->map.color_cpus_str);
3167 sched->map.color_cpus = map;
3171 static int perf_sched__map(struct perf_sched *sched)
3173 if (setup_map_cpus(sched))
3176 if (setup_color_pids(sched))
3179 if (setup_color_cpus(sched))
3183 if (perf_sched__read_events(sched))
3185 print_bad_events(sched);
3189 static int perf_sched__replay(struct perf_sched *sched)
3193 calibrate_run_measurement_overhead(sched);
3194 calibrate_sleep_measurement_overhead(sched);
3196 test_calibrations(sched);
3198 if (perf_sched__read_events(sched))
3201 printf("nr_run_events: %ld\n", sched->nr_run_events);
3202 printf("nr_sleep_events: %ld\n", sched->nr_sleep_events);
3203 printf("nr_wakeup_events: %ld\n", sched->nr_wakeup_events);
3205 if (sched->targetless_wakeups)
3206 printf("target-less wakeups: %ld\n", sched->targetless_wakeups);
3207 if (sched->multitarget_wakeups)
3208 printf("multi-target wakeups: %ld\n", sched->multitarget_wakeups);
3209 if (sched->nr_run_events_optimized)
3210 printf("run atoms optimized: %ld\n",
3211 sched->nr_run_events_optimized);
3213 print_task_traces(sched);
3214 add_cross_task_wakeups(sched);
3216 create_tasks(sched);
3217 printf("------------------------------------------------------------\n");
3218 for (i = 0; i < sched->replay_repeat; i++)
3219 run_one_test(sched);
3224 static void setup_sorting(struct perf_sched *sched, const struct option *options,
3225 const char * const usage_msg[])
3227 char *tmp, *tok, *str = strdup(sched->sort_order);
3229 for (tok = strtok_r(str, ", ", &tmp);
3230 tok; tok = strtok_r(NULL, ", ", &tmp)) {
3231 if (sort_dimension__add(tok, &sched->sort_list) < 0) {
3232 usage_with_options_msg(usage_msg, options,
3233 "Unknown --sort key: `%s'", tok);
3239 sort_dimension__add("pid", &sched->cmp_pid);
3242 static int __cmd_record(int argc, const char **argv)
3244 unsigned int rec_argc, i, j;
3245 const char **rec_argv;
3246 const char * const record_args[] = {
3252 "-e", "sched:sched_switch",
3253 "-e", "sched:sched_stat_wait",
3254 "-e", "sched:sched_stat_sleep",
3255 "-e", "sched:sched_stat_iowait",
3256 "-e", "sched:sched_stat_runtime",
3257 "-e", "sched:sched_process_fork",
3258 "-e", "sched:sched_wakeup",
3259 "-e", "sched:sched_wakeup_new",
3260 "-e", "sched:sched_migrate_task",
3263 rec_argc = ARRAY_SIZE(record_args) + argc - 1;
3264 rec_argv = calloc(rec_argc + 1, sizeof(char *));
3266 if (rec_argv == NULL)
3269 for (i = 0; i < ARRAY_SIZE(record_args); i++)
3270 rec_argv[i] = strdup(record_args[i]);
3272 for (j = 1; j < (unsigned int)argc; j++, i++)
3273 rec_argv[i] = argv[j];
3275 BUG_ON(i != rec_argc);
3277 return cmd_record(i, rec_argv);
3280 int cmd_sched(int argc, const char **argv)
3282 const char default_sort_order[] = "avg, max, switch, runtime";
3283 struct perf_sched sched = {
3285 .sample = perf_sched__process_tracepoint_sample,
3286 .comm = perf_event__process_comm,
3287 .namespaces = perf_event__process_namespaces,
3288 .lost = perf_event__process_lost,
3289 .fork = perf_sched__process_fork_event,
3290 .ordered_events = true,
3292 .cmp_pid = LIST_HEAD_INIT(sched.cmp_pid),
3293 .sort_list = LIST_HEAD_INIT(sched.sort_list),
3294 .start_work_mutex = PTHREAD_MUTEX_INITIALIZER,
3295 .work_done_wait_mutex = PTHREAD_MUTEX_INITIALIZER,
3296 .sort_order = default_sort_order,
3297 .replay_repeat = 10,
3299 .next_shortname1 = 'A',
3300 .next_shortname2 = '0',
3302 .show_callchain = 1,
3305 const struct option sched_options[] = {
3306 OPT_STRING('i', "input", &input_name, "file",
3308 OPT_INCR('v', "verbose", &verbose,
3309 "be more verbose (show symbol address, etc)"),
3310 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
3311 "dump raw trace in ASCII"),
3312 OPT_BOOLEAN('f', "force", &sched.force, "don't complain, do it"),
3315 const struct option latency_options[] = {
3316 OPT_STRING('s', "sort", &sched.sort_order, "key[,key2...]",
3317 "sort by key(s): runtime, switch, avg, max"),
3318 OPT_INTEGER('C', "CPU", &sched.profile_cpu,
3319 "CPU to profile on"),
3320 OPT_BOOLEAN('p', "pids", &sched.skip_merge,
3321 "latency stats per pid instead of per comm"),
3322 OPT_PARENT(sched_options)
3324 const struct option replay_options[] = {
3325 OPT_UINTEGER('r', "repeat", &sched.replay_repeat,
3326 "repeat the workload replay N times (-1: infinite)"),
3327 OPT_PARENT(sched_options)
3329 const struct option map_options[] = {
3330 OPT_BOOLEAN(0, "compact", &sched.map.comp,
3331 "map output in compact mode"),
3332 OPT_STRING(0, "color-pids", &sched.map.color_pids_str, "pids",
3333 "highlight given pids in map"),
3334 OPT_STRING(0, "color-cpus", &sched.map.color_cpus_str, "cpus",
3335 "highlight given CPUs in map"),
3336 OPT_STRING(0, "cpus", &sched.map.cpus_str, "cpus",
3337 "display given CPUs in map"),
3338 OPT_PARENT(sched_options)
3340 const struct option timehist_options[] = {
3341 OPT_STRING('k', "vmlinux", &symbol_conf.vmlinux_name,
3342 "file", "vmlinux pathname"),
3343 OPT_STRING(0, "kallsyms", &symbol_conf.kallsyms_name,
3344 "file", "kallsyms pathname"),
3345 OPT_BOOLEAN('g', "call-graph", &sched.show_callchain,
3346 "Display call chains if present (default on)"),
3347 OPT_UINTEGER(0, "max-stack", &sched.max_stack,
3348 "Maximum number of functions to display backtrace."),
3349 OPT_STRING(0, "symfs", &symbol_conf.symfs, "directory",
3350 "Look for files with symbols relative to this directory"),
3351 OPT_BOOLEAN('s', "summary", &sched.summary_only,
3352 "Show only syscall summary with statistics"),
3353 OPT_BOOLEAN('S', "with-summary", &sched.summary,
3354 "Show all syscalls and summary with statistics"),
3355 OPT_BOOLEAN('w', "wakeups", &sched.show_wakeups, "Show wakeup events"),
3356 OPT_BOOLEAN('n', "next", &sched.show_next, "Show next task"),
3357 OPT_BOOLEAN('M', "migrations", &sched.show_migrations, "Show migration events"),
3358 OPT_BOOLEAN('V', "cpu-visual", &sched.show_cpu_visual, "Add CPU visual"),
3359 OPT_BOOLEAN('I', "idle-hist", &sched.idle_hist, "Show idle events only"),
3360 OPT_STRING(0, "time", &sched.time_str, "str",
3361 "Time span for analysis (start,stop)"),
3362 OPT_BOOLEAN(0, "state", &sched.show_state, "Show task state when sched-out"),
3363 OPT_PARENT(sched_options)
3366 const char * const latency_usage[] = {
3367 "perf sched latency [<options>]",
3370 const char * const replay_usage[] = {
3371 "perf sched replay [<options>]",
3374 const char * const map_usage[] = {
3375 "perf sched map [<options>]",
3378 const char * const timehist_usage[] = {
3379 "perf sched timehist [<options>]",
3382 const char *const sched_subcommands[] = { "record", "latency", "map",
3385 const char *sched_usage[] = {
3389 struct trace_sched_handler lat_ops = {
3390 .wakeup_event = latency_wakeup_event,
3391 .switch_event = latency_switch_event,
3392 .runtime_event = latency_runtime_event,
3393 .migrate_task_event = latency_migrate_task_event,
3395 struct trace_sched_handler map_ops = {
3396 .switch_event = map_switch_event,
3398 struct trace_sched_handler replay_ops = {
3399 .wakeup_event = replay_wakeup_event,
3400 .switch_event = replay_switch_event,
3401 .fork_event = replay_fork_event,
3405 for (i = 0; i < ARRAY_SIZE(sched.curr_pid); i++)
3406 sched.curr_pid[i] = -1;
3408 argc = parse_options_subcommand(argc, argv, sched_options, sched_subcommands,
3409 sched_usage, PARSE_OPT_STOP_AT_NON_OPTION);
3411 usage_with_options(sched_usage, sched_options);
3414 * Aliased to 'perf script' for now:
3416 if (!strcmp(argv[0], "script"))
3417 return cmd_script(argc, argv);
3419 if (!strncmp(argv[0], "rec", 3)) {
3420 return __cmd_record(argc, argv);
3421 } else if (!strncmp(argv[0], "lat", 3)) {
3422 sched.tp_handler = &lat_ops;
3424 argc = parse_options(argc, argv, latency_options, latency_usage, 0);
3426 usage_with_options(latency_usage, latency_options);
3428 setup_sorting(&sched, latency_options, latency_usage);
3429 return perf_sched__lat(&sched);
3430 } else if (!strcmp(argv[0], "map")) {
3432 argc = parse_options(argc, argv, map_options, map_usage, 0);
3434 usage_with_options(map_usage, map_options);
3436 sched.tp_handler = &map_ops;
3437 setup_sorting(&sched, latency_options, latency_usage);
3438 return perf_sched__map(&sched);
3439 } else if (!strncmp(argv[0], "rep", 3)) {
3440 sched.tp_handler = &replay_ops;
3442 argc = parse_options(argc, argv, replay_options, replay_usage, 0);
3444 usage_with_options(replay_usage, replay_options);
3446 return perf_sched__replay(&sched);
3447 } else if (!strcmp(argv[0], "timehist")) {
3449 argc = parse_options(argc, argv, timehist_options,
3452 usage_with_options(timehist_usage, timehist_options);
3454 if ((sched.show_wakeups || sched.show_next) &&
3455 sched.summary_only) {
3456 pr_err(" Error: -s and -[n|w] are mutually exclusive.\n");
3457 parse_options_usage(timehist_usage, timehist_options, "s", true);
3458 if (sched.show_wakeups)
3459 parse_options_usage(NULL, timehist_options, "w", true);
3460 if (sched.show_next)
3461 parse_options_usage(NULL, timehist_options, "n", true);
3465 return perf_sched__timehist(&sched);
3467 usage_with_options(sched_usage, sched_options);