5 #include "util/cache.h"
6 #include "util/symbol.h"
7 #include "util/thread.h"
8 #include "util/header.h"
10 #include "util/parse-options.h"
11 #include "util/trace-event.h"
13 #include "util/debug.h"
15 #include <sys/types.h>
16 #include <sys/prctl.h>
18 #include <semaphore.h>
22 static char const *input_name = "perf.data";
24 static unsigned long page_size;
25 static unsigned long mmap_window = 32;
27 static unsigned long total_comm = 0;
29 static struct rb_root threads;
30 static struct thread *last_match;
32 static struct perf_header *header;
33 static u64 sample_type;
35 static char default_sort_order[] = "avg, max, switch, runtime";
36 static char *sort_order = default_sort_order;
38 #define PR_SET_NAME 15 /* Set process name */
41 #define BUG_ON(x) assert(!(x))
43 static u64 run_measurement_overhead;
44 static u64 sleep_measurement_overhead;
51 static unsigned long nr_tasks;
60 unsigned long nr_events;
61 unsigned long curr_event;
62 struct sched_atom **atoms;
73 enum sched_event_type {
80 enum sched_event_type type;
86 struct task_desc *wakee;
89 static struct task_desc *pid_to_task[MAX_PID];
91 static struct task_desc **tasks;
93 static pthread_mutex_t start_work_mutex = PTHREAD_MUTEX_INITIALIZER;
94 static u64 start_time;
96 static pthread_mutex_t work_done_wait_mutex = PTHREAD_MUTEX_INITIALIZER;
98 static unsigned long nr_run_events;
99 static unsigned long nr_sleep_events;
100 static unsigned long nr_wakeup_events;
102 static unsigned long nr_sleep_corrections;
103 static unsigned long nr_run_events_optimized;
105 static unsigned long targetless_wakeups;
106 static unsigned long multitarget_wakeups;
108 static u64 cpu_usage;
109 static u64 runavg_cpu_usage;
110 static u64 parent_cpu_usage;
111 static u64 runavg_parent_cpu_usage;
113 static unsigned long nr_runs;
114 static u64 sum_runtime;
115 static u64 sum_fluct;
118 static unsigned long replay_repeat = 10;
119 static unsigned long nr_timestamps;
120 static unsigned long nr_unordered_timestamps;
121 static unsigned long nr_state_machine_bugs;
122 static unsigned long nr_context_switch_bugs;
123 static unsigned long nr_events;
124 static unsigned long nr_lost_chunks;
125 static unsigned long nr_lost_events;
127 #define TASK_STATE_TO_CHAR_STR "RSDTtZX"
137 struct list_head list;
138 enum thread_state state;
146 struct list_head work_list;
147 struct thread *thread;
155 typedef int (*sort_fn_t)(struct work_atoms *, struct work_atoms *);
157 static struct rb_root atom_root, sorted_atom_root;
159 static u64 all_runtime;
160 static u64 all_count;
162 static int read_events(void);
165 static u64 get_nsecs(void)
169 clock_gettime(CLOCK_MONOTONIC, &ts);
171 return ts.tv_sec * 1000000000ULL + ts.tv_nsec;
174 static void burn_nsecs(u64 nsecs)
176 u64 T0 = get_nsecs(), T1;
180 } while (T1 + run_measurement_overhead < T0 + nsecs);
183 static void sleep_nsecs(u64 nsecs)
187 ts.tv_nsec = nsecs % 999999999;
188 ts.tv_sec = nsecs / 999999999;
190 nanosleep(&ts, NULL);
193 static void calibrate_run_measurement_overhead(void)
195 u64 T0, T1, delta, min_delta = 1000000000ULL;
198 for (i = 0; i < 10; i++) {
203 min_delta = min(min_delta, delta);
205 run_measurement_overhead = min_delta;
207 printf("run measurement overhead: %Ld nsecs\n", min_delta);
210 static void calibrate_sleep_measurement_overhead(void)
212 u64 T0, T1, delta, min_delta = 1000000000ULL;
215 for (i = 0; i < 10; i++) {
220 min_delta = min(min_delta, delta);
223 sleep_measurement_overhead = min_delta;
225 printf("sleep measurement overhead: %Ld nsecs\n", min_delta);
228 static struct sched_atom *
229 get_new_event(struct task_desc *task, u64 timestamp)
231 struct sched_atom *event = calloc(1, sizeof(*event));
232 unsigned long idx = task->nr_events;
235 event->timestamp = timestamp;
239 size = sizeof(struct sched_atom *) * task->nr_events;
240 task->atoms = realloc(task->atoms, size);
241 BUG_ON(!task->atoms);
243 task->atoms[idx] = event;
248 static struct sched_atom *last_event(struct task_desc *task)
250 if (!task->nr_events)
253 return task->atoms[task->nr_events - 1];
257 add_sched_event_run(struct task_desc *task, u64 timestamp, u64 duration)
259 struct sched_atom *event, *curr_event = last_event(task);
262 * optimize an existing RUN event by merging this one
265 if (curr_event && curr_event->type == SCHED_EVENT_RUN) {
266 nr_run_events_optimized++;
267 curr_event->duration += duration;
271 event = get_new_event(task, timestamp);
273 event->type = SCHED_EVENT_RUN;
274 event->duration = duration;
280 add_sched_event_wakeup(struct task_desc *task, u64 timestamp,
281 struct task_desc *wakee)
283 struct sched_atom *event, *wakee_event;
285 event = get_new_event(task, timestamp);
286 event->type = SCHED_EVENT_WAKEUP;
287 event->wakee = wakee;
289 wakee_event = last_event(wakee);
290 if (!wakee_event || wakee_event->type != SCHED_EVENT_SLEEP) {
291 targetless_wakeups++;
294 if (wakee_event->wait_sem) {
295 multitarget_wakeups++;
299 wakee_event->wait_sem = calloc(1, sizeof(*wakee_event->wait_sem));
300 sem_init(wakee_event->wait_sem, 0, 0);
301 wakee_event->specific_wait = 1;
302 event->wait_sem = wakee_event->wait_sem;
308 add_sched_event_sleep(struct task_desc *task, u64 timestamp,
309 u64 task_state __used)
311 struct sched_atom *event = get_new_event(task, timestamp);
313 event->type = SCHED_EVENT_SLEEP;
318 static struct task_desc *register_pid(unsigned long pid, const char *comm)
320 struct task_desc *task;
322 BUG_ON(pid >= MAX_PID);
324 task = pid_to_task[pid];
329 task = calloc(1, sizeof(*task));
332 strcpy(task->comm, comm);
334 * every task starts in sleeping state - this gets ignored
335 * if there's no wakeup pointing to this sleep state:
337 add_sched_event_sleep(task, 0, 0);
339 pid_to_task[pid] = task;
341 tasks = realloc(tasks, nr_tasks*sizeof(struct task_task *));
343 tasks[task->nr] = task;
346 printf("registered task #%ld, PID %ld (%s)\n", nr_tasks, pid, comm);
352 static void print_task_traces(void)
354 struct task_desc *task;
357 for (i = 0; i < nr_tasks; i++) {
359 printf("task %6ld (%20s:%10ld), nr_events: %ld\n",
360 task->nr, task->comm, task->pid, task->nr_events);
364 static void add_cross_task_wakeups(void)
366 struct task_desc *task1, *task2;
369 for (i = 0; i < nr_tasks; i++) {
375 add_sched_event_wakeup(task1, 0, task2);
380 process_sched_event(struct task_desc *this_task __used, struct sched_atom *atom)
387 delta = start_time + atom->timestamp - now;
389 switch (atom->type) {
390 case SCHED_EVENT_RUN:
391 burn_nsecs(atom->duration);
393 case SCHED_EVENT_SLEEP:
395 ret = sem_wait(atom->wait_sem);
398 case SCHED_EVENT_WAKEUP:
400 ret = sem_post(atom->wait_sem);
408 static u64 get_cpu_usage_nsec_parent(void)
414 err = getrusage(RUSAGE_SELF, &ru);
417 sum = ru.ru_utime.tv_sec*1e9 + ru.ru_utime.tv_usec*1e3;
418 sum += ru.ru_stime.tv_sec*1e9 + ru.ru_stime.tv_usec*1e3;
423 static u64 get_cpu_usage_nsec_self(void)
425 char filename [] = "/proc/1234567890/sched";
426 unsigned long msecs, nsecs;
434 sprintf(filename, "/proc/%d/sched", getpid());
435 file = fopen(filename, "r");
438 while ((chars = getline(&line, &len, file)) != -1) {
439 ret = sscanf(line, "se.sum_exec_runtime : %ld.%06ld\n",
442 total = msecs*1e6 + nsecs;
453 static void *thread_func(void *ctx)
455 struct task_desc *this_task = ctx;
456 u64 cpu_usage_0, cpu_usage_1;
457 unsigned long i, ret;
460 sprintf(comm2, ":%s", this_task->comm);
461 prctl(PR_SET_NAME, comm2);
464 ret = sem_post(&this_task->ready_for_work);
466 ret = pthread_mutex_lock(&start_work_mutex);
468 ret = pthread_mutex_unlock(&start_work_mutex);
471 cpu_usage_0 = get_cpu_usage_nsec_self();
473 for (i = 0; i < this_task->nr_events; i++) {
474 this_task->curr_event = i;
475 process_sched_event(this_task, this_task->atoms[i]);
478 cpu_usage_1 = get_cpu_usage_nsec_self();
479 this_task->cpu_usage = cpu_usage_1 - cpu_usage_0;
481 ret = sem_post(&this_task->work_done_sem);
484 ret = pthread_mutex_lock(&work_done_wait_mutex);
486 ret = pthread_mutex_unlock(&work_done_wait_mutex);
492 static void create_tasks(void)
494 struct task_desc *task;
499 err = pthread_attr_init(&attr);
501 err = pthread_attr_setstacksize(&attr, (size_t)(16*1024));
503 err = pthread_mutex_lock(&start_work_mutex);
505 err = pthread_mutex_lock(&work_done_wait_mutex);
507 for (i = 0; i < nr_tasks; i++) {
509 sem_init(&task->sleep_sem, 0, 0);
510 sem_init(&task->ready_for_work, 0, 0);
511 sem_init(&task->work_done_sem, 0, 0);
512 task->curr_event = 0;
513 err = pthread_create(&task->thread, &attr, thread_func, task);
518 static void wait_for_tasks(void)
520 u64 cpu_usage_0, cpu_usage_1;
521 struct task_desc *task;
522 unsigned long i, ret;
524 start_time = get_nsecs();
526 pthread_mutex_unlock(&work_done_wait_mutex);
528 for (i = 0; i < nr_tasks; i++) {
530 ret = sem_wait(&task->ready_for_work);
532 sem_init(&task->ready_for_work, 0, 0);
534 ret = pthread_mutex_lock(&work_done_wait_mutex);
537 cpu_usage_0 = get_cpu_usage_nsec_parent();
539 pthread_mutex_unlock(&start_work_mutex);
541 for (i = 0; i < nr_tasks; i++) {
543 ret = sem_wait(&task->work_done_sem);
545 sem_init(&task->work_done_sem, 0, 0);
546 cpu_usage += task->cpu_usage;
550 cpu_usage_1 = get_cpu_usage_nsec_parent();
551 if (!runavg_cpu_usage)
552 runavg_cpu_usage = cpu_usage;
553 runavg_cpu_usage = (runavg_cpu_usage*9 + cpu_usage)/10;
555 parent_cpu_usage = cpu_usage_1 - cpu_usage_0;
556 if (!runavg_parent_cpu_usage)
557 runavg_parent_cpu_usage = parent_cpu_usage;
558 runavg_parent_cpu_usage = (runavg_parent_cpu_usage*9 +
559 parent_cpu_usage)/10;
561 ret = pthread_mutex_lock(&start_work_mutex);
564 for (i = 0; i < nr_tasks; i++) {
566 sem_init(&task->sleep_sem, 0, 0);
567 task->curr_event = 0;
571 static void run_one_test(void)
573 u64 T0, T1, delta, avg_delta, fluct, std_dev;
580 sum_runtime += delta;
583 avg_delta = sum_runtime / nr_runs;
584 if (delta < avg_delta)
585 fluct = avg_delta - delta;
587 fluct = delta - avg_delta;
589 std_dev = sum_fluct / nr_runs / sqrt(nr_runs);
592 run_avg = (run_avg*9 + delta)/10;
594 printf("#%-3ld: %0.3f, ",
595 nr_runs, (double)delta/1000000.0);
597 printf("ravg: %0.2f, ",
598 (double)run_avg/1e6);
600 printf("cpu: %0.2f / %0.2f",
601 (double)cpu_usage/1e6, (double)runavg_cpu_usage/1e6);
605 * rusage statistics done by the parent, these are less
606 * accurate than the sum_exec_runtime based statistics:
608 printf(" [%0.2f / %0.2f]",
609 (double)parent_cpu_usage/1e6,
610 (double)runavg_parent_cpu_usage/1e6);
615 if (nr_sleep_corrections)
616 printf(" (%ld sleep corrections)\n", nr_sleep_corrections);
617 nr_sleep_corrections = 0;
620 static void test_calibrations(void)
628 printf("the run test took %Ld nsecs\n", T1-T0);
634 printf("the sleep test took %Ld nsecs\n", T1-T0);
637 static void __cmd_replay(void)
641 calibrate_run_measurement_overhead();
642 calibrate_sleep_measurement_overhead();
648 printf("nr_run_events: %ld\n", nr_run_events);
649 printf("nr_sleep_events: %ld\n", nr_sleep_events);
650 printf("nr_wakeup_events: %ld\n", nr_wakeup_events);
652 if (targetless_wakeups)
653 printf("target-less wakeups: %ld\n", targetless_wakeups);
654 if (multitarget_wakeups)
655 printf("multi-target wakeups: %ld\n", multitarget_wakeups);
656 if (nr_run_events_optimized)
657 printf("run atoms optimized: %ld\n",
658 nr_run_events_optimized);
661 add_cross_task_wakeups();
664 printf("------------------------------------------------------------\n");
665 for (i = 0; i < replay_repeat; i++)
670 process_comm_event(event_t *event, unsigned long offset, unsigned long head)
672 struct thread *thread;
674 thread = threads__findnew(event->comm.pid, &threads, &last_match);
676 dump_printf("%p [%p]: perf_event_comm: %s:%d\n",
677 (void *)(offset + head),
678 (void *)(long)(event->header.size),
679 event->comm.comm, event->comm.pid);
681 if (thread == NULL ||
682 thread__set_comm(thread, event->comm.comm)) {
683 dump_printf("problem processing perf_event_comm, skipping event.\n");
692 struct raw_event_sample {
697 #define FILL_FIELD(ptr, field, event, data) \
698 ptr.field = (typeof(ptr.field)) raw_field_value(event, #field, data)
700 #define FILL_ARRAY(ptr, array, event, data) \
702 void *__array = raw_field_ptr(event, #array, data); \
703 memcpy(ptr.array, __array, sizeof(ptr.array)); \
706 #define FILL_COMMON_FIELDS(ptr, event, data) \
708 FILL_FIELD(ptr, common_type, event, data); \
709 FILL_FIELD(ptr, common_flags, event, data); \
710 FILL_FIELD(ptr, common_preempt_count, event, data); \
711 FILL_FIELD(ptr, common_pid, event, data); \
712 FILL_FIELD(ptr, common_tgid, event, data); \
717 struct trace_switch_event {
722 u8 common_preempt_count;
735 struct trace_runtime_event {
740 u8 common_preempt_count;
750 struct trace_wakeup_event {
755 u8 common_preempt_count;
767 struct trace_fork_event {
772 u8 common_preempt_count;
776 char parent_comm[16];
782 struct trace_sched_handler {
783 void (*switch_event)(struct trace_switch_event *,
787 struct thread *thread);
789 void (*runtime_event)(struct trace_runtime_event *,
793 struct thread *thread);
795 void (*wakeup_event)(struct trace_wakeup_event *,
799 struct thread *thread);
801 void (*fork_event)(struct trace_fork_event *,
805 struct thread *thread);
810 replay_wakeup_event(struct trace_wakeup_event *wakeup_event,
813 u64 timestamp __used,
814 struct thread *thread __used)
816 struct task_desc *waker, *wakee;
819 printf("sched_wakeup event %p\n", event);
821 printf(" ... pid %d woke up %s/%d\n",
822 wakeup_event->common_pid,
827 waker = register_pid(wakeup_event->common_pid, "<unknown>");
828 wakee = register_pid(wakeup_event->pid, wakeup_event->comm);
830 add_sched_event_wakeup(waker, timestamp, wakee);
833 static u64 cpu_last_switched[MAX_CPUS];
836 replay_switch_event(struct trace_switch_event *switch_event,
840 struct thread *thread __used)
842 struct task_desc *prev, *next;
847 printf("sched_switch event %p\n", event);
849 if (cpu >= MAX_CPUS || cpu < 0)
852 timestamp0 = cpu_last_switched[cpu];
854 delta = timestamp - timestamp0;
859 die("hm, delta: %Ld < 0 ?\n", delta);
862 printf(" ... switch from %s/%d to %s/%d [ran %Ld nsecs]\n",
863 switch_event->prev_comm, switch_event->prev_pid,
864 switch_event->next_comm, switch_event->next_pid,
868 prev = register_pid(switch_event->prev_pid, switch_event->prev_comm);
869 next = register_pid(switch_event->next_pid, switch_event->next_comm);
871 cpu_last_switched[cpu] = timestamp;
873 add_sched_event_run(prev, timestamp, delta);
874 add_sched_event_sleep(prev, timestamp, switch_event->prev_state);
879 replay_fork_event(struct trace_fork_event *fork_event,
882 u64 timestamp __used,
883 struct thread *thread __used)
886 printf("sched_fork event %p\n", event);
887 printf("... parent: %s/%d\n", fork_event->parent_comm, fork_event->parent_pid);
888 printf("... child: %s/%d\n", fork_event->child_comm, fork_event->child_pid);
890 register_pid(fork_event->parent_pid, fork_event->parent_comm);
891 register_pid(fork_event->child_pid, fork_event->child_comm);
894 static struct trace_sched_handler replay_ops = {
895 .wakeup_event = replay_wakeup_event,
896 .switch_event = replay_switch_event,
897 .fork_event = replay_fork_event,
900 struct sort_dimension {
903 struct list_head list;
906 static LIST_HEAD(cmp_pid);
909 thread_lat_cmp(struct list_head *list, struct work_atoms *l, struct work_atoms *r)
911 struct sort_dimension *sort;
914 BUG_ON(list_empty(list));
916 list_for_each_entry(sort, list, list) {
917 ret = sort->cmp(l, r);
925 static struct work_atoms *
926 thread_atoms_search(struct rb_root *root, struct thread *thread,
927 struct list_head *sort_list)
929 struct rb_node *node = root->rb_node;
930 struct work_atoms key = { .thread = thread };
933 struct work_atoms *atoms;
936 atoms = container_of(node, struct work_atoms, node);
938 cmp = thread_lat_cmp(sort_list, &key, atoms);
940 node = node->rb_left;
942 node = node->rb_right;
944 BUG_ON(thread != atoms->thread);
952 __thread_latency_insert(struct rb_root *root, struct work_atoms *data,
953 struct list_head *sort_list)
955 struct rb_node **new = &(root->rb_node), *parent = NULL;
958 struct work_atoms *this;
961 this = container_of(*new, struct work_atoms, node);
964 cmp = thread_lat_cmp(sort_list, data, this);
967 new = &((*new)->rb_left);
969 new = &((*new)->rb_right);
972 rb_link_node(&data->node, parent, new);
973 rb_insert_color(&data->node, root);
976 static void thread_atoms_insert(struct thread *thread)
978 struct work_atoms *atoms;
980 atoms = calloc(sizeof(*atoms), 1);
984 atoms->thread = thread;
985 INIT_LIST_HEAD(&atoms->work_list);
986 __thread_latency_insert(&atom_root, atoms, &cmp_pid);
990 latency_fork_event(struct trace_fork_event *fork_event __used,
991 struct event *event __used,
993 u64 timestamp __used,
994 struct thread *thread __used)
996 /* should insert the newcomer */
1000 static char sched_out_state(struct trace_switch_event *switch_event)
1002 const char *str = TASK_STATE_TO_CHAR_STR;
1004 return str[switch_event->prev_state];
1008 add_sched_out_event(struct work_atoms *atoms,
1012 struct work_atom *atom;
1014 atom = calloc(sizeof(*atom), 1);
1018 atom->sched_out_time = timestamp;
1020 if (run_state == 'R') {
1021 atom->state = THREAD_WAIT_CPU;
1022 atom->wake_up_time = atom->sched_out_time;
1025 list_add_tail(&atom->list, &atoms->work_list);
1029 add_runtime_event(struct work_atoms *atoms, u64 delta, u64 timestamp __used)
1031 struct work_atom *atom;
1033 BUG_ON(list_empty(&atoms->work_list));
1035 atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1037 atom->runtime += delta;
1038 atoms->total_runtime += delta;
1042 add_sched_in_event(struct work_atoms *atoms, u64 timestamp)
1044 struct work_atom *atom;
1047 if (list_empty(&atoms->work_list))
1050 atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1052 if (atom->state != THREAD_WAIT_CPU)
1055 if (timestamp < atom->wake_up_time) {
1056 atom->state = THREAD_IGNORE;
1060 atom->state = THREAD_SCHED_IN;
1061 atom->sched_in_time = timestamp;
1063 delta = atom->sched_in_time - atom->wake_up_time;
1064 atoms->total_lat += delta;
1065 if (delta > atoms->max_lat)
1066 atoms->max_lat = delta;
1071 latency_switch_event(struct trace_switch_event *switch_event,
1072 struct event *event __used,
1075 struct thread *thread __used)
1077 struct work_atoms *out_events, *in_events;
1078 struct thread *sched_out, *sched_in;
1082 BUG_ON(cpu >= MAX_CPUS || cpu < 0);
1084 timestamp0 = cpu_last_switched[cpu];
1085 cpu_last_switched[cpu] = timestamp;
1087 delta = timestamp - timestamp0;
1092 die("hm, delta: %Ld < 0 ?\n", delta);
1095 sched_out = threads__findnew(switch_event->prev_pid, &threads, &last_match);
1096 sched_in = threads__findnew(switch_event->next_pid, &threads, &last_match);
1098 out_events = thread_atoms_search(&atom_root, sched_out, &cmp_pid);
1100 thread_atoms_insert(sched_out);
1101 out_events = thread_atoms_search(&atom_root, sched_out, &cmp_pid);
1103 die("out-event: Internal tree error");
1105 add_sched_out_event(out_events, sched_out_state(switch_event), timestamp);
1107 in_events = thread_atoms_search(&atom_root, sched_in, &cmp_pid);
1109 thread_atoms_insert(sched_in);
1110 in_events = thread_atoms_search(&atom_root, sched_in, &cmp_pid);
1112 die("in-event: Internal tree error");
1114 * Take came in we have not heard about yet,
1115 * add in an initial atom in runnable state:
1117 add_sched_out_event(in_events, 'R', timestamp);
1119 add_sched_in_event(in_events, timestamp);
1123 latency_runtime_event(struct trace_runtime_event *runtime_event,
1124 struct event *event __used,
1127 struct thread *this_thread __used)
1129 struct work_atoms *atoms;
1130 struct thread *thread;
1132 BUG_ON(cpu >= MAX_CPUS || cpu < 0);
1134 thread = threads__findnew(runtime_event->pid, &threads, &last_match);
1135 atoms = thread_atoms_search(&atom_root, thread, &cmp_pid);
1137 thread_atoms_insert(thread);
1138 atoms = thread_atoms_search(&atom_root, thread, &cmp_pid);
1140 die("in-event: Internal tree error");
1141 add_sched_out_event(atoms, 'R', timestamp);
1144 add_runtime_event(atoms, runtime_event->runtime, timestamp);
1148 latency_wakeup_event(struct trace_wakeup_event *wakeup_event,
1149 struct event *__event __used,
1152 struct thread *thread __used)
1154 struct work_atoms *atoms;
1155 struct work_atom *atom;
1156 struct thread *wakee;
1158 /* Note for later, it may be interesting to observe the failing cases */
1159 if (!wakeup_event->success)
1162 wakee = threads__findnew(wakeup_event->pid, &threads, &last_match);
1163 atoms = thread_atoms_search(&atom_root, wakee, &cmp_pid);
1165 thread_atoms_insert(wakee);
1166 atoms = thread_atoms_search(&atom_root, wakee, &cmp_pid);
1168 die("wakeup-event: Internal tree error");
1169 add_sched_out_event(atoms, 'S', timestamp);
1172 BUG_ON(list_empty(&atoms->work_list));
1174 atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1176 if (atom->state != THREAD_SLEEPING)
1177 nr_state_machine_bugs++;
1180 if (atom->sched_out_time > timestamp) {
1181 nr_unordered_timestamps++;
1185 atom->state = THREAD_WAIT_CPU;
1186 atom->wake_up_time = timestamp;
1189 static struct trace_sched_handler lat_ops = {
1190 .wakeup_event = latency_wakeup_event,
1191 .switch_event = latency_switch_event,
1192 .runtime_event = latency_runtime_event,
1193 .fork_event = latency_fork_event,
1196 static void output_lat_thread(struct work_atoms *work_list)
1202 if (!work_list->nb_atoms)
1205 * Ignore idle threads:
1207 if (!work_list->thread->pid)
1210 all_runtime += work_list->total_runtime;
1211 all_count += work_list->nb_atoms;
1213 ret = printf(" %s-%d ", work_list->thread->comm, work_list->thread->pid);
1215 for (i = 0; i < 24 - ret; i++)
1218 avg = work_list->total_lat / work_list->nb_atoms;
1220 printf("|%11.3f ms |%9llu | avg:%9.3f ms | max:%9.3f ms |\n",
1221 (double)work_list->total_runtime / 1e6,
1222 work_list->nb_atoms, (double)avg / 1e6,
1223 (double)work_list->max_lat / 1e6);
1226 static int pid_cmp(struct work_atoms *l, struct work_atoms *r)
1228 if (l->thread->pid < r->thread->pid)
1230 if (l->thread->pid > r->thread->pid)
1236 static struct sort_dimension pid_sort_dimension = {
1241 static int avg_cmp(struct work_atoms *l, struct work_atoms *r)
1251 avgl = l->total_lat / l->nb_atoms;
1252 avgr = r->total_lat / r->nb_atoms;
1262 static struct sort_dimension avg_sort_dimension = {
1267 static int max_cmp(struct work_atoms *l, struct work_atoms *r)
1269 if (l->max_lat < r->max_lat)
1271 if (l->max_lat > r->max_lat)
1277 static struct sort_dimension max_sort_dimension = {
1282 static int switch_cmp(struct work_atoms *l, struct work_atoms *r)
1284 if (l->nb_atoms < r->nb_atoms)
1286 if (l->nb_atoms > r->nb_atoms)
1292 static struct sort_dimension switch_sort_dimension = {
1297 static int runtime_cmp(struct work_atoms *l, struct work_atoms *r)
1299 if (l->total_runtime < r->total_runtime)
1301 if (l->total_runtime > r->total_runtime)
1307 static struct sort_dimension runtime_sort_dimension = {
1312 static struct sort_dimension *available_sorts[] = {
1313 &pid_sort_dimension,
1314 &avg_sort_dimension,
1315 &max_sort_dimension,
1316 &switch_sort_dimension,
1317 &runtime_sort_dimension,
1320 #define NB_AVAILABLE_SORTS (int)(sizeof(available_sorts) / sizeof(struct sort_dimension *))
1322 static LIST_HEAD(sort_list);
1324 static int sort_dimension__add(char *tok, struct list_head *list)
1328 for (i = 0; i < NB_AVAILABLE_SORTS; i++) {
1329 if (!strcmp(available_sorts[i]->name, tok)) {
1330 list_add_tail(&available_sorts[i]->list, list);
1339 static void setup_sorting(void);
1341 static void sort_lat(void)
1343 struct rb_node *node;
1346 struct work_atoms *data;
1347 node = rb_first(&atom_root);
1351 rb_erase(node, &atom_root);
1352 data = rb_entry(node, struct work_atoms, node);
1353 __thread_latency_insert(&sorted_atom_root, data, &sort_list);
1357 static void __cmd_lat(void)
1359 struct rb_node *next;
1365 printf("\n -----------------------------------------------------------------------------------------\n");
1366 printf(" Task | Runtime ms | Switches | Average delay ms | Maximum delay ms |\n");
1367 printf(" -----------------------------------------------------------------------------------------\n");
1369 next = rb_first(&sorted_atom_root);
1372 struct work_atoms *work_list;
1374 work_list = rb_entry(next, struct work_atoms, node);
1375 output_lat_thread(work_list);
1376 next = rb_next(next);
1379 printf(" -----------------------------------------------------------------------------------------\n");
1380 printf(" TOTAL: |%11.3f ms |%9Ld |\n",
1381 (double)all_runtime/1e6, all_count);
1383 printf(" ---------------------------------------------------\n");
1384 if (nr_unordered_timestamps && nr_timestamps) {
1385 printf(" INFO: %.3f%% unordered timestamps (%ld out of %ld)\n",
1386 (double)nr_unordered_timestamps/(double)nr_timestamps*100.0,
1387 nr_unordered_timestamps, nr_timestamps);
1390 if (nr_lost_events && nr_events) {
1391 printf(" INFO: %.3f%% lost events (%ld out of %ld, in %ld chunks)\n",
1392 (double)nr_lost_events/(double)nr_events*100.0,
1393 nr_lost_events, nr_events, nr_lost_chunks);
1395 if (nr_state_machine_bugs && nr_timestamps) {
1396 printf(" INFO: %.3f%% state machine bugs (%ld out of %ld)",
1397 (double)nr_state_machine_bugs/(double)nr_timestamps*100.0,
1398 nr_state_machine_bugs, nr_timestamps);
1400 printf(" (due to lost events?)");
1403 if (nr_context_switch_bugs && nr_timestamps) {
1404 printf(" INFO: %.3f%% context switch bugs (%ld out of %ld)",
1405 (double)nr_context_switch_bugs/(double)nr_timestamps*100.0,
1406 nr_context_switch_bugs, nr_timestamps);
1408 printf(" (due to lost events?)");
1415 static struct trace_sched_handler *trace_handler;
1418 process_sched_wakeup_event(struct raw_event_sample *raw,
1419 struct event *event,
1421 u64 timestamp __used,
1422 struct thread *thread __used)
1424 struct trace_wakeup_event wakeup_event;
1426 FILL_COMMON_FIELDS(wakeup_event, event, raw->data);
1428 FILL_ARRAY(wakeup_event, comm, event, raw->data);
1429 FILL_FIELD(wakeup_event, pid, event, raw->data);
1430 FILL_FIELD(wakeup_event, prio, event, raw->data);
1431 FILL_FIELD(wakeup_event, success, event, raw->data);
1432 FILL_FIELD(wakeup_event, cpu, event, raw->data);
1434 trace_handler->wakeup_event(&wakeup_event, event, cpu, timestamp, thread);
1438 * Track the current task - that way we can know whether there's any
1439 * weird events, such as a task being switched away that is not current.
1441 static u32 curr_pid[MAX_CPUS] = { [0 ... MAX_CPUS-1] = -1 };
1444 process_sched_switch_event(struct raw_event_sample *raw,
1445 struct event *event,
1447 u64 timestamp __used,
1448 struct thread *thread __used)
1450 struct trace_switch_event switch_event;
1452 FILL_COMMON_FIELDS(switch_event, event, raw->data);
1454 FILL_ARRAY(switch_event, prev_comm, event, raw->data);
1455 FILL_FIELD(switch_event, prev_pid, event, raw->data);
1456 FILL_FIELD(switch_event, prev_prio, event, raw->data);
1457 FILL_FIELD(switch_event, prev_state, event, raw->data);
1458 FILL_ARRAY(switch_event, next_comm, event, raw->data);
1459 FILL_FIELD(switch_event, next_pid, event, raw->data);
1460 FILL_FIELD(switch_event, next_prio, event, raw->data);
1462 if (curr_pid[cpu] != (u32)-1) {
1464 * Are we trying to switch away a PID that is
1467 if (curr_pid[cpu] != switch_event.prev_pid)
1468 nr_context_switch_bugs++;
1470 curr_pid[cpu] = switch_event.next_pid;
1472 trace_handler->switch_event(&switch_event, event, cpu, timestamp, thread);
1476 process_sched_runtime_event(struct raw_event_sample *raw,
1477 struct event *event,
1479 u64 timestamp __used,
1480 struct thread *thread __used)
1482 struct trace_runtime_event runtime_event;
1484 FILL_ARRAY(runtime_event, comm, event, raw->data);
1485 FILL_FIELD(runtime_event, pid, event, raw->data);
1486 FILL_FIELD(runtime_event, runtime, event, raw->data);
1487 FILL_FIELD(runtime_event, vruntime, event, raw->data);
1489 trace_handler->runtime_event(&runtime_event, event, cpu, timestamp, thread);
1493 process_sched_fork_event(struct raw_event_sample *raw,
1494 struct event *event,
1496 u64 timestamp __used,
1497 struct thread *thread __used)
1499 struct trace_fork_event fork_event;
1501 FILL_COMMON_FIELDS(fork_event, event, raw->data);
1503 FILL_ARRAY(fork_event, parent_comm, event, raw->data);
1504 FILL_FIELD(fork_event, parent_pid, event, raw->data);
1505 FILL_ARRAY(fork_event, child_comm, event, raw->data);
1506 FILL_FIELD(fork_event, child_pid, event, raw->data);
1508 trace_handler->fork_event(&fork_event, event, cpu, timestamp, thread);
1512 process_sched_exit_event(struct event *event,
1514 u64 timestamp __used,
1515 struct thread *thread __used)
1518 printf("sched_exit event %p\n", event);
1522 process_raw_event(event_t *raw_event __used, void *more_data,
1523 int cpu, u64 timestamp, struct thread *thread)
1525 struct raw_event_sample *raw = more_data;
1526 struct event *event;
1529 type = trace_parse_common_type(raw->data);
1530 event = trace_find_event(type);
1532 if (!strcmp(event->name, "sched_switch"))
1533 process_sched_switch_event(raw, event, cpu, timestamp, thread);
1534 if (!strcmp(event->name, "sched_stat_runtime"))
1535 process_sched_runtime_event(raw, event, cpu, timestamp, thread);
1536 if (!strcmp(event->name, "sched_wakeup"))
1537 process_sched_wakeup_event(raw, event, cpu, timestamp, thread);
1538 if (!strcmp(event->name, "sched_wakeup_new"))
1539 process_sched_wakeup_event(raw, event, cpu, timestamp, thread);
1540 if (!strcmp(event->name, "sched_process_fork"))
1541 process_sched_fork_event(raw, event, cpu, timestamp, thread);
1542 if (!strcmp(event->name, "sched_process_exit"))
1543 process_sched_exit_event(event, cpu, timestamp, thread);
1547 process_sample_event(event_t *event, unsigned long offset, unsigned long head)
1551 struct dso *dso = NULL;
1552 struct thread *thread;
1553 u64 ip = event->ip.ip;
1557 void *more_data = event->ip.__more_data;
1560 thread = threads__findnew(event->ip.pid, &threads, &last_match);
1562 if (sample_type & PERF_SAMPLE_TIME) {
1563 timestamp = *(u64 *)more_data;
1564 more_data += sizeof(u64);
1567 if (sample_type & PERF_SAMPLE_CPU) {
1568 cpu = *(u32 *)more_data;
1569 more_data += sizeof(u32);
1570 more_data += sizeof(u32); /* reserved */
1573 if (sample_type & PERF_SAMPLE_PERIOD) {
1574 period = *(u64 *)more_data;
1575 more_data += sizeof(u64);
1578 dump_printf("%p [%p]: PERF_EVENT_SAMPLE (IP, %d): %d/%d: %p period: %Ld\n",
1579 (void *)(offset + head),
1580 (void *)(long)(event->header.size),
1582 event->ip.pid, event->ip.tid,
1586 dump_printf(" ... thread: %s:%d\n", thread->comm, thread->pid);
1588 if (thread == NULL) {
1589 eprintf("problem processing %d event, skipping it.\n",
1590 event->header.type);
1594 cpumode = event->header.misc & PERF_EVENT_MISC_CPUMODE_MASK;
1596 if (cpumode == PERF_EVENT_MISC_KERNEL) {
1602 dump_printf(" ...... dso: %s\n", dso->name);
1604 } else if (cpumode == PERF_EVENT_MISC_USER) {
1613 dso = hypervisor_dso;
1615 dump_printf(" ...... dso: [hypervisor]\n");
1618 if (sample_type & PERF_SAMPLE_RAW)
1619 process_raw_event(event, more_data, cpu, timestamp, thread);
1625 process_event(event_t *event, unsigned long offset, unsigned long head)
1630 switch (event->header.type) {
1631 case PERF_EVENT_MMAP:
1633 case PERF_EVENT_LOST:
1635 nr_lost_events += event->lost.lost;
1638 case PERF_EVENT_COMM:
1639 return process_comm_event(event, offset, head);
1641 case PERF_EVENT_EXIT ... PERF_EVENT_READ:
1644 case PERF_EVENT_SAMPLE:
1645 return process_sample_event(event, offset, head);
1647 case PERF_EVENT_MAX:
1655 static int read_events(void)
1657 int ret, rc = EXIT_FAILURE;
1658 unsigned long offset = 0;
1659 unsigned long head = 0;
1660 struct stat perf_stat;
1666 register_idle_thread(&threads, &last_match);
1668 input = open(input_name, O_RDONLY);
1670 perror("failed to open file");
1674 ret = fstat(input, &perf_stat);
1676 perror("failed to stat file");
1680 if (!perf_stat.st_size) {
1681 fprintf(stderr, "zero-sized file, nothing to do!\n");
1684 header = perf_header__read(input);
1685 head = header->data_offset;
1686 sample_type = perf_header__sample_type(header);
1688 if (!(sample_type & PERF_SAMPLE_RAW))
1689 die("No trace sample to read. Did you call perf record "
1692 if (load_kernel() < 0) {
1693 perror("failed to load kernel symbols");
1694 return EXIT_FAILURE;
1698 buf = (char *)mmap(NULL, page_size * mmap_window, PROT_READ,
1699 MAP_SHARED, input, offset);
1700 if (buf == MAP_FAILED) {
1701 perror("failed to mmap file");
1706 event = (event_t *)(buf + head);
1708 size = event->header.size;
1712 if (head + event->header.size >= page_size * mmap_window) {
1713 unsigned long shift = page_size * (head / page_size);
1716 res = munmap(buf, page_size * mmap_window);
1724 size = event->header.size;
1727 if (!size || process_event(event, offset, head) < 0) {
1730 * assume we lost track of the stream, check alignment, and
1731 * increment a single u64 in the hope to catch on again 'soon'.
1734 if (unlikely(head & 7))
1742 if (offset + head < (unsigned long)perf_stat.st_size)
1751 static const char * const sched_usage[] = {
1752 "perf sched [<options>] {record|latency|replay|trace}",
1756 static const struct option sched_options[] = {
1757 OPT_BOOLEAN('v', "verbose", &verbose,
1758 "be more verbose (show symbol address, etc)"),
1759 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1760 "dump raw trace in ASCII"),
1764 static const char * const latency_usage[] = {
1765 "perf sched latency [<options>]",
1769 static const struct option latency_options[] = {
1770 OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1771 "sort by key(s): runtime, switch, avg, max"),
1772 OPT_BOOLEAN('v', "verbose", &verbose,
1773 "be more verbose (show symbol address, etc)"),
1774 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1775 "dump raw trace in ASCII"),
1779 static const char * const replay_usage[] = {
1780 "perf sched replay [<options>]",
1784 static const struct option replay_options[] = {
1785 OPT_INTEGER('r', "repeat", &replay_repeat,
1786 "repeat the workload replay N times (-1: infinite)"),
1787 OPT_BOOLEAN('v', "verbose", &verbose,
1788 "be more verbose (show symbol address, etc)"),
1789 OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1790 "dump raw trace in ASCII"),
1794 static void setup_sorting(void)
1796 char *tmp, *tok, *str = strdup(sort_order);
1798 for (tok = strtok_r(str, ", ", &tmp);
1799 tok; tok = strtok_r(NULL, ", ", &tmp)) {
1800 if (sort_dimension__add(tok, &sort_list) < 0) {
1801 error("Unknown --sort key: `%s'", tok);
1802 usage_with_options(latency_usage, latency_options);
1808 sort_dimension__add((char *)"pid", &cmp_pid);
1811 static const char *record_args[] = {
1819 "-e", "sched:sched_switch:r",
1820 "-e", "sched:sched_stat_wait:r",
1821 "-e", "sched:sched_stat_sleep:r",
1822 "-e", "sched:sched_stat_iowait:r",
1823 "-e", "sched:sched_stat_runtime:r",
1824 "-e", "sched:sched_process_exit:r",
1825 "-e", "sched:sched_process_fork:r",
1826 "-e", "sched:sched_wakeup:r",
1827 "-e", "sched:sched_migrate_task:r",
1830 static int __cmd_record(int argc, const char **argv)
1832 unsigned int rec_argc, i, j;
1833 const char **rec_argv;
1835 rec_argc = ARRAY_SIZE(record_args) + argc - 1;
1836 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1838 for (i = 0; i < ARRAY_SIZE(record_args); i++)
1839 rec_argv[i] = strdup(record_args[i]);
1841 for (j = 1; j < (unsigned int)argc; j++, i++)
1842 rec_argv[i] = argv[j];
1844 BUG_ON(i != rec_argc);
1846 return cmd_record(i, rec_argv, NULL);
1849 int cmd_sched(int argc, const char **argv, const char *prefix __used)
1852 page_size = getpagesize();
1854 argc = parse_options(argc, argv, sched_options, sched_usage,
1855 PARSE_OPT_STOP_AT_NON_OPTION);
1857 usage_with_options(sched_usage, sched_options);
1859 if (!strncmp(argv[0], "rec", 3)) {
1860 return __cmd_record(argc, argv);
1861 } else if (!strncmp(argv[0], "lat", 3)) {
1862 trace_handler = &lat_ops;
1864 argc = parse_options(argc, argv, latency_options, latency_usage, 0);
1866 usage_with_options(latency_usage, latency_options);
1870 } else if (!strncmp(argv[0], "rep", 3)) {
1871 trace_handler = &replay_ops;
1873 argc = parse_options(argc, argv, replay_options, replay_usage, 0);
1875 usage_with_options(replay_usage, replay_options);
1878 } else if (!strcmp(argv[0], "trace")) {
1880 * Aliased to 'perf trace' for now:
1882 return cmd_trace(argc, argv, prefix);
1884 usage_with_options(sched_usage, sched_options);