0ee868e6f63ba2b11de0040634c392a79dc98fbe
[linux-3.10.git] / tools / perf / builtin-sched.c
1 #include "builtin.h"
2 #include "perf.h"
3
4 #include "util/util.h"
5 #include "util/cache.h"
6 #include "util/evsel.h"
7 #include "util/symbol.h"
8 #include "util/thread.h"
9 #include "util/header.h"
10 #include "util/session.h"
11 #include "util/tool.h"
12
13 #include "util/parse-options.h"
14 #include "util/trace-event.h"
15
16 #include "util/debug.h"
17
18 #include <sys/prctl.h>
19
20 #include <semaphore.h>
21 #include <pthread.h>
22 #include <math.h>
23
24 static char                     const *input_name = "perf.data";
25
26 static char                     default_sort_order[] = "avg, max, switch, runtime";
27 static const char               *sort_order = default_sort_order;
28
29 static int                      profile_cpu = -1;
30
31 #define PR_SET_NAME             15               /* Set process name */
32 #define MAX_CPUS                4096
33
34 static u64                      run_measurement_overhead;
35 static u64                      sleep_measurement_overhead;
36
37 #define COMM_LEN                20
38 #define SYM_LEN                 129
39
40 #define MAX_PID                 65536
41
42 static unsigned long            nr_tasks;
43
44 struct sched_atom;
45
46 struct task_desc {
47         unsigned long           nr;
48         unsigned long           pid;
49         char                    comm[COMM_LEN];
50
51         unsigned long           nr_events;
52         unsigned long           curr_event;
53         struct sched_atom       **atoms;
54
55         pthread_t               thread;
56         sem_t                   sleep_sem;
57
58         sem_t                   ready_for_work;
59         sem_t                   work_done_sem;
60
61         u64                     cpu_usage;
62 };
63
64 enum sched_event_type {
65         SCHED_EVENT_RUN,
66         SCHED_EVENT_SLEEP,
67         SCHED_EVENT_WAKEUP,
68         SCHED_EVENT_MIGRATION,
69 };
70
71 struct sched_atom {
72         enum sched_event_type   type;
73         int                     specific_wait;
74         u64                     timestamp;
75         u64                     duration;
76         unsigned long           nr;
77         sem_t                   *wait_sem;
78         struct task_desc        *wakee;
79 };
80
81 static struct task_desc         *pid_to_task[MAX_PID];
82
83 static struct task_desc         **tasks;
84
85 static pthread_mutex_t          start_work_mutex = PTHREAD_MUTEX_INITIALIZER;
86 static u64                      start_time;
87
88 static pthread_mutex_t          work_done_wait_mutex = PTHREAD_MUTEX_INITIALIZER;
89
90 static unsigned long            nr_run_events;
91 static unsigned long            nr_sleep_events;
92 static unsigned long            nr_wakeup_events;
93
94 static unsigned long            nr_sleep_corrections;
95 static unsigned long            nr_run_events_optimized;
96
97 static unsigned long            targetless_wakeups;
98 static unsigned long            multitarget_wakeups;
99
100 static u64                      cpu_usage;
101 static u64                      runavg_cpu_usage;
102 static u64                      parent_cpu_usage;
103 static u64                      runavg_parent_cpu_usage;
104
105 static unsigned long            nr_runs;
106 static u64                      sum_runtime;
107 static u64                      sum_fluct;
108 static u64                      run_avg;
109
110 static unsigned int             replay_repeat = 10;
111 static unsigned long            nr_timestamps;
112 static unsigned long            nr_unordered_timestamps;
113 static unsigned long            nr_state_machine_bugs;
114 static unsigned long            nr_context_switch_bugs;
115 static unsigned long            nr_events;
116 static unsigned long            nr_lost_chunks;
117 static unsigned long            nr_lost_events;
118
119 #define TASK_STATE_TO_CHAR_STR "RSDTtZX"
120
121 enum thread_state {
122         THREAD_SLEEPING = 0,
123         THREAD_WAIT_CPU,
124         THREAD_SCHED_IN,
125         THREAD_IGNORE
126 };
127
128 struct work_atom {
129         struct list_head        list;
130         enum thread_state       state;
131         u64                     sched_out_time;
132         u64                     wake_up_time;
133         u64                     sched_in_time;
134         u64                     runtime;
135 };
136
137 struct work_atoms {
138         struct list_head        work_list;
139         struct thread           *thread;
140         struct rb_node          node;
141         u64                     max_lat;
142         u64                     max_lat_at;
143         u64                     total_lat;
144         u64                     nb_atoms;
145         u64                     total_runtime;
146 };
147
148 typedef int (*sort_fn_t)(struct work_atoms *, struct work_atoms *);
149
150 static struct rb_root           atom_root, sorted_atom_root;
151
152 static u64                      all_runtime;
153 static u64                      all_count;
154
155
156 static u64 get_nsecs(void)
157 {
158         struct timespec ts;
159
160         clock_gettime(CLOCK_MONOTONIC, &ts);
161
162         return ts.tv_sec * 1000000000ULL + ts.tv_nsec;
163 }
164
165 static void burn_nsecs(u64 nsecs)
166 {
167         u64 T0 = get_nsecs(), T1;
168
169         do {
170                 T1 = get_nsecs();
171         } while (T1 + run_measurement_overhead < T0 + nsecs);
172 }
173
174 static void sleep_nsecs(u64 nsecs)
175 {
176         struct timespec ts;
177
178         ts.tv_nsec = nsecs % 999999999;
179         ts.tv_sec = nsecs / 999999999;
180
181         nanosleep(&ts, NULL);
182 }
183
184 static void calibrate_run_measurement_overhead(void)
185 {
186         u64 T0, T1, delta, min_delta = 1000000000ULL;
187         int i;
188
189         for (i = 0; i < 10; i++) {
190                 T0 = get_nsecs();
191                 burn_nsecs(0);
192                 T1 = get_nsecs();
193                 delta = T1-T0;
194                 min_delta = min(min_delta, delta);
195         }
196         run_measurement_overhead = min_delta;
197
198         printf("run measurement overhead: %" PRIu64 " nsecs\n", min_delta);
199 }
200
201 static void calibrate_sleep_measurement_overhead(void)
202 {
203         u64 T0, T1, delta, min_delta = 1000000000ULL;
204         int i;
205
206         for (i = 0; i < 10; i++) {
207                 T0 = get_nsecs();
208                 sleep_nsecs(10000);
209                 T1 = get_nsecs();
210                 delta = T1-T0;
211                 min_delta = min(min_delta, delta);
212         }
213         min_delta -= 10000;
214         sleep_measurement_overhead = min_delta;
215
216         printf("sleep measurement overhead: %" PRIu64 " nsecs\n", min_delta);
217 }
218
219 static struct sched_atom *
220 get_new_event(struct task_desc *task, u64 timestamp)
221 {
222         struct sched_atom *event = zalloc(sizeof(*event));
223         unsigned long idx = task->nr_events;
224         size_t size;
225
226         event->timestamp = timestamp;
227         event->nr = idx;
228
229         task->nr_events++;
230         size = sizeof(struct sched_atom *) * task->nr_events;
231         task->atoms = realloc(task->atoms, size);
232         BUG_ON(!task->atoms);
233
234         task->atoms[idx] = event;
235
236         return event;
237 }
238
239 static struct sched_atom *last_event(struct task_desc *task)
240 {
241         if (!task->nr_events)
242                 return NULL;
243
244         return task->atoms[task->nr_events - 1];
245 }
246
247 static void
248 add_sched_event_run(struct task_desc *task, u64 timestamp, u64 duration)
249 {
250         struct sched_atom *event, *curr_event = last_event(task);
251
252         /*
253          * optimize an existing RUN event by merging this one
254          * to it:
255          */
256         if (curr_event && curr_event->type == SCHED_EVENT_RUN) {
257                 nr_run_events_optimized++;
258                 curr_event->duration += duration;
259                 return;
260         }
261
262         event = get_new_event(task, timestamp);
263
264         event->type = SCHED_EVENT_RUN;
265         event->duration = duration;
266
267         nr_run_events++;
268 }
269
270 static void
271 add_sched_event_wakeup(struct task_desc *task, u64 timestamp,
272                        struct task_desc *wakee)
273 {
274         struct sched_atom *event, *wakee_event;
275
276         event = get_new_event(task, timestamp);
277         event->type = SCHED_EVENT_WAKEUP;
278         event->wakee = wakee;
279
280         wakee_event = last_event(wakee);
281         if (!wakee_event || wakee_event->type != SCHED_EVENT_SLEEP) {
282                 targetless_wakeups++;
283                 return;
284         }
285         if (wakee_event->wait_sem) {
286                 multitarget_wakeups++;
287                 return;
288         }
289
290         wakee_event->wait_sem = zalloc(sizeof(*wakee_event->wait_sem));
291         sem_init(wakee_event->wait_sem, 0, 0);
292         wakee_event->specific_wait = 1;
293         event->wait_sem = wakee_event->wait_sem;
294
295         nr_wakeup_events++;
296 }
297
298 static void
299 add_sched_event_sleep(struct task_desc *task, u64 timestamp,
300                       u64 task_state __used)
301 {
302         struct sched_atom *event = get_new_event(task, timestamp);
303
304         event->type = SCHED_EVENT_SLEEP;
305
306         nr_sleep_events++;
307 }
308
309 static struct task_desc *register_pid(unsigned long pid, const char *comm)
310 {
311         struct task_desc *task;
312
313         BUG_ON(pid >= MAX_PID);
314
315         task = pid_to_task[pid];
316
317         if (task)
318                 return task;
319
320         task = zalloc(sizeof(*task));
321         task->pid = pid;
322         task->nr = nr_tasks;
323         strcpy(task->comm, comm);
324         /*
325          * every task starts in sleeping state - this gets ignored
326          * if there's no wakeup pointing to this sleep state:
327          */
328         add_sched_event_sleep(task, 0, 0);
329
330         pid_to_task[pid] = task;
331         nr_tasks++;
332         tasks = realloc(tasks, nr_tasks*sizeof(struct task_task *));
333         BUG_ON(!tasks);
334         tasks[task->nr] = task;
335
336         if (verbose)
337                 printf("registered task #%ld, PID %ld (%s)\n", nr_tasks, pid, comm);
338
339         return task;
340 }
341
342
343 static void print_task_traces(void)
344 {
345         struct task_desc *task;
346         unsigned long i;
347
348         for (i = 0; i < nr_tasks; i++) {
349                 task = tasks[i];
350                 printf("task %6ld (%20s:%10ld), nr_events: %ld\n",
351                         task->nr, task->comm, task->pid, task->nr_events);
352         }
353 }
354
355 static void add_cross_task_wakeups(void)
356 {
357         struct task_desc *task1, *task2;
358         unsigned long i, j;
359
360         for (i = 0; i < nr_tasks; i++) {
361                 task1 = tasks[i];
362                 j = i + 1;
363                 if (j == nr_tasks)
364                         j = 0;
365                 task2 = tasks[j];
366                 add_sched_event_wakeup(task1, 0, task2);
367         }
368 }
369
370 static void
371 process_sched_event(struct task_desc *this_task __used, struct sched_atom *atom)
372 {
373         int ret = 0;
374
375         switch (atom->type) {
376                 case SCHED_EVENT_RUN:
377                         burn_nsecs(atom->duration);
378                         break;
379                 case SCHED_EVENT_SLEEP:
380                         if (atom->wait_sem)
381                                 ret = sem_wait(atom->wait_sem);
382                         BUG_ON(ret);
383                         break;
384                 case SCHED_EVENT_WAKEUP:
385                         if (atom->wait_sem)
386                                 ret = sem_post(atom->wait_sem);
387                         BUG_ON(ret);
388                         break;
389                 case SCHED_EVENT_MIGRATION:
390                         break;
391                 default:
392                         BUG_ON(1);
393         }
394 }
395
396 static u64 get_cpu_usage_nsec_parent(void)
397 {
398         struct rusage ru;
399         u64 sum;
400         int err;
401
402         err = getrusage(RUSAGE_SELF, &ru);
403         BUG_ON(err);
404
405         sum =  ru.ru_utime.tv_sec*1e9 + ru.ru_utime.tv_usec*1e3;
406         sum += ru.ru_stime.tv_sec*1e9 + ru.ru_stime.tv_usec*1e3;
407
408         return sum;
409 }
410
411 static int self_open_counters(void)
412 {
413         struct perf_event_attr attr;
414         int fd;
415
416         memset(&attr, 0, sizeof(attr));
417
418         attr.type = PERF_TYPE_SOFTWARE;
419         attr.config = PERF_COUNT_SW_TASK_CLOCK;
420
421         fd = sys_perf_event_open(&attr, 0, -1, -1, 0);
422
423         if (fd < 0)
424                 die("Error: sys_perf_event_open() syscall returned"
425                     "with %d (%s)\n", fd, strerror(errno));
426         return fd;
427 }
428
429 static u64 get_cpu_usage_nsec_self(int fd)
430 {
431         u64 runtime;
432         int ret;
433
434         ret = read(fd, &runtime, sizeof(runtime));
435         BUG_ON(ret != sizeof(runtime));
436
437         return runtime;
438 }
439
440 static void *thread_func(void *ctx)
441 {
442         struct task_desc *this_task = ctx;
443         u64 cpu_usage_0, cpu_usage_1;
444         unsigned long i, ret;
445         char comm2[22];
446         int fd;
447
448         sprintf(comm2, ":%s", this_task->comm);
449         prctl(PR_SET_NAME, comm2);
450         fd = self_open_counters();
451
452 again:
453         ret = sem_post(&this_task->ready_for_work);
454         BUG_ON(ret);
455         ret = pthread_mutex_lock(&start_work_mutex);
456         BUG_ON(ret);
457         ret = pthread_mutex_unlock(&start_work_mutex);
458         BUG_ON(ret);
459
460         cpu_usage_0 = get_cpu_usage_nsec_self(fd);
461
462         for (i = 0; i < this_task->nr_events; i++) {
463                 this_task->curr_event = i;
464                 process_sched_event(this_task, this_task->atoms[i]);
465         }
466
467         cpu_usage_1 = get_cpu_usage_nsec_self(fd);
468         this_task->cpu_usage = cpu_usage_1 - cpu_usage_0;
469         ret = sem_post(&this_task->work_done_sem);
470         BUG_ON(ret);
471
472         ret = pthread_mutex_lock(&work_done_wait_mutex);
473         BUG_ON(ret);
474         ret = pthread_mutex_unlock(&work_done_wait_mutex);
475         BUG_ON(ret);
476
477         goto again;
478 }
479
480 static void create_tasks(void)
481 {
482         struct task_desc *task;
483         pthread_attr_t attr;
484         unsigned long i;
485         int err;
486
487         err = pthread_attr_init(&attr);
488         BUG_ON(err);
489         err = pthread_attr_setstacksize(&attr,
490                         (size_t) max(16 * 1024, PTHREAD_STACK_MIN));
491         BUG_ON(err);
492         err = pthread_mutex_lock(&start_work_mutex);
493         BUG_ON(err);
494         err = pthread_mutex_lock(&work_done_wait_mutex);
495         BUG_ON(err);
496         for (i = 0; i < nr_tasks; i++) {
497                 task = tasks[i];
498                 sem_init(&task->sleep_sem, 0, 0);
499                 sem_init(&task->ready_for_work, 0, 0);
500                 sem_init(&task->work_done_sem, 0, 0);
501                 task->curr_event = 0;
502                 err = pthread_create(&task->thread, &attr, thread_func, task);
503                 BUG_ON(err);
504         }
505 }
506
507 static void wait_for_tasks(void)
508 {
509         u64 cpu_usage_0, cpu_usage_1;
510         struct task_desc *task;
511         unsigned long i, ret;
512
513         start_time = get_nsecs();
514         cpu_usage = 0;
515         pthread_mutex_unlock(&work_done_wait_mutex);
516
517         for (i = 0; i < nr_tasks; i++) {
518                 task = tasks[i];
519                 ret = sem_wait(&task->ready_for_work);
520                 BUG_ON(ret);
521                 sem_init(&task->ready_for_work, 0, 0);
522         }
523         ret = pthread_mutex_lock(&work_done_wait_mutex);
524         BUG_ON(ret);
525
526         cpu_usage_0 = get_cpu_usage_nsec_parent();
527
528         pthread_mutex_unlock(&start_work_mutex);
529
530         for (i = 0; i < nr_tasks; i++) {
531                 task = tasks[i];
532                 ret = sem_wait(&task->work_done_sem);
533                 BUG_ON(ret);
534                 sem_init(&task->work_done_sem, 0, 0);
535                 cpu_usage += task->cpu_usage;
536                 task->cpu_usage = 0;
537         }
538
539         cpu_usage_1 = get_cpu_usage_nsec_parent();
540         if (!runavg_cpu_usage)
541                 runavg_cpu_usage = cpu_usage;
542         runavg_cpu_usage = (runavg_cpu_usage*9 + cpu_usage)/10;
543
544         parent_cpu_usage = cpu_usage_1 - cpu_usage_0;
545         if (!runavg_parent_cpu_usage)
546                 runavg_parent_cpu_usage = parent_cpu_usage;
547         runavg_parent_cpu_usage = (runavg_parent_cpu_usage*9 +
548                                    parent_cpu_usage)/10;
549
550         ret = pthread_mutex_lock(&start_work_mutex);
551         BUG_ON(ret);
552
553         for (i = 0; i < nr_tasks; i++) {
554                 task = tasks[i];
555                 sem_init(&task->sleep_sem, 0, 0);
556                 task->curr_event = 0;
557         }
558 }
559
560 static void run_one_test(void)
561 {
562         u64 T0, T1, delta, avg_delta, fluct;
563
564         T0 = get_nsecs();
565         wait_for_tasks();
566         T1 = get_nsecs();
567
568         delta = T1 - T0;
569         sum_runtime += delta;
570         nr_runs++;
571
572         avg_delta = sum_runtime / nr_runs;
573         if (delta < avg_delta)
574                 fluct = avg_delta - delta;
575         else
576                 fluct = delta - avg_delta;
577         sum_fluct += fluct;
578         if (!run_avg)
579                 run_avg = delta;
580         run_avg = (run_avg*9 + delta)/10;
581
582         printf("#%-3ld: %0.3f, ",
583                 nr_runs, (double)delta/1000000.0);
584
585         printf("ravg: %0.2f, ",
586                 (double)run_avg/1e6);
587
588         printf("cpu: %0.2f / %0.2f",
589                 (double)cpu_usage/1e6, (double)runavg_cpu_usage/1e6);
590
591 #if 0
592         /*
593          * rusage statistics done by the parent, these are less
594          * accurate than the sum_exec_runtime based statistics:
595          */
596         printf(" [%0.2f / %0.2f]",
597                 (double)parent_cpu_usage/1e6,
598                 (double)runavg_parent_cpu_usage/1e6);
599 #endif
600
601         printf("\n");
602
603         if (nr_sleep_corrections)
604                 printf(" (%ld sleep corrections)\n", nr_sleep_corrections);
605         nr_sleep_corrections = 0;
606 }
607
608 static void test_calibrations(void)
609 {
610         u64 T0, T1;
611
612         T0 = get_nsecs();
613         burn_nsecs(1e6);
614         T1 = get_nsecs();
615
616         printf("the run test took %" PRIu64 " nsecs\n", T1 - T0);
617
618         T0 = get_nsecs();
619         sleep_nsecs(1e6);
620         T1 = get_nsecs();
621
622         printf("the sleep test took %" PRIu64 " nsecs\n", T1 - T0);
623 }
624
625 #define FILL_FIELD(ptr, field, event, data)     \
626         ptr.field = (typeof(ptr.field)) raw_field_value(event, #field, data)
627
628 #define FILL_ARRAY(ptr, array, event, data)                     \
629 do {                                                            \
630         void *__array = raw_field_ptr(event, #array, data);     \
631         memcpy(ptr.array, __array, sizeof(ptr.array));  \
632 } while(0)
633
634 #define FILL_COMMON_FIELDS(ptr, event, data)                    \
635 do {                                                            \
636         FILL_FIELD(ptr, common_type, event, data);              \
637         FILL_FIELD(ptr, common_flags, event, data);             \
638         FILL_FIELD(ptr, common_preempt_count, event, data);     \
639         FILL_FIELD(ptr, common_pid, event, data);               \
640         FILL_FIELD(ptr, common_tgid, event, data);              \
641 } while (0)
642
643
644
645 struct trace_switch_event {
646         u32 size;
647
648         u16 common_type;
649         u8 common_flags;
650         u8 common_preempt_count;
651         u32 common_pid;
652         u32 common_tgid;
653
654         char prev_comm[16];
655         u32 prev_pid;
656         u32 prev_prio;
657         u64 prev_state;
658         char next_comm[16];
659         u32 next_pid;
660         u32 next_prio;
661 };
662
663 struct trace_runtime_event {
664         u32 size;
665
666         u16 common_type;
667         u8 common_flags;
668         u8 common_preempt_count;
669         u32 common_pid;
670         u32 common_tgid;
671
672         char comm[16];
673         u32 pid;
674         u64 runtime;
675         u64 vruntime;
676 };
677
678 struct trace_wakeup_event {
679         u32 size;
680
681         u16 common_type;
682         u8 common_flags;
683         u8 common_preempt_count;
684         u32 common_pid;
685         u32 common_tgid;
686
687         char comm[16];
688         u32 pid;
689
690         u32 prio;
691         u32 success;
692         u32 cpu;
693 };
694
695 struct trace_fork_event {
696         u32 size;
697
698         u16 common_type;
699         u8 common_flags;
700         u8 common_preempt_count;
701         u32 common_pid;
702         u32 common_tgid;
703
704         char parent_comm[16];
705         u32 parent_pid;
706         char child_comm[16];
707         u32 child_pid;
708 };
709
710 struct trace_migrate_task_event {
711         u32 size;
712
713         u16 common_type;
714         u8 common_flags;
715         u8 common_preempt_count;
716         u32 common_pid;
717         u32 common_tgid;
718
719         char comm[16];
720         u32 pid;
721
722         u32 prio;
723         u32 cpu;
724 };
725
726 struct trace_sched_handler {
727         void (*switch_event)(struct trace_switch_event *,
728                              struct machine *,
729                              struct event *,
730                              int cpu,
731                              u64 timestamp,
732                              struct thread *thread);
733
734         void (*runtime_event)(struct trace_runtime_event *,
735                               struct machine *,
736                               struct event *,
737                               int cpu,
738                               u64 timestamp,
739                               struct thread *thread);
740
741         void (*wakeup_event)(struct trace_wakeup_event *,
742                              struct machine *,
743                              struct event *,
744                              int cpu,
745                              u64 timestamp,
746                              struct thread *thread);
747
748         void (*fork_event)(struct trace_fork_event *,
749                            struct event *,
750                            int cpu,
751                            u64 timestamp,
752                            struct thread *thread);
753
754         void (*migrate_task_event)(struct trace_migrate_task_event *,
755                            struct machine *machine,
756                            struct event *,
757                            int cpu,
758                            u64 timestamp,
759                            struct thread *thread);
760 };
761
762
763 static void
764 replay_wakeup_event(struct trace_wakeup_event *wakeup_event,
765                     struct machine *machine __used,
766                     struct event *event,
767                     int cpu __used,
768                     u64 timestamp __used,
769                     struct thread *thread __used)
770 {
771         struct task_desc *waker, *wakee;
772
773         if (verbose) {
774                 printf("sched_wakeup event %p\n", event);
775
776                 printf(" ... pid %d woke up %s/%d\n",
777                         wakeup_event->common_pid,
778                         wakeup_event->comm,
779                         wakeup_event->pid);
780         }
781
782         waker = register_pid(wakeup_event->common_pid, "<unknown>");
783         wakee = register_pid(wakeup_event->pid, wakeup_event->comm);
784
785         add_sched_event_wakeup(waker, timestamp, wakee);
786 }
787
788 static u64 cpu_last_switched[MAX_CPUS];
789
790 static void
791 replay_switch_event(struct trace_switch_event *switch_event,
792                     struct machine *machine __used,
793                     struct event *event,
794                     int cpu,
795                     u64 timestamp,
796                     struct thread *thread __used)
797 {
798         struct task_desc *prev, __used *next;
799         u64 timestamp0;
800         s64 delta;
801
802         if (verbose)
803                 printf("sched_switch event %p\n", event);
804
805         if (cpu >= MAX_CPUS || cpu < 0)
806                 return;
807
808         timestamp0 = cpu_last_switched[cpu];
809         if (timestamp0)
810                 delta = timestamp - timestamp0;
811         else
812                 delta = 0;
813
814         if (delta < 0)
815                 die("hm, delta: %" PRIu64 " < 0 ?\n", delta);
816
817         if (verbose) {
818                 printf(" ... switch from %s/%d to %s/%d [ran %" PRIu64 " nsecs]\n",
819                         switch_event->prev_comm, switch_event->prev_pid,
820                         switch_event->next_comm, switch_event->next_pid,
821                         delta);
822         }
823
824         prev = register_pid(switch_event->prev_pid, switch_event->prev_comm);
825         next = register_pid(switch_event->next_pid, switch_event->next_comm);
826
827         cpu_last_switched[cpu] = timestamp;
828
829         add_sched_event_run(prev, timestamp, delta);
830         add_sched_event_sleep(prev, timestamp, switch_event->prev_state);
831 }
832
833
834 static void
835 replay_fork_event(struct trace_fork_event *fork_event,
836                   struct event *event,
837                   int cpu __used,
838                   u64 timestamp __used,
839                   struct thread *thread __used)
840 {
841         if (verbose) {
842                 printf("sched_fork event %p\n", event);
843                 printf("... parent: %s/%d\n", fork_event->parent_comm, fork_event->parent_pid);
844                 printf("...  child: %s/%d\n", fork_event->child_comm, fork_event->child_pid);
845         }
846         register_pid(fork_event->parent_pid, fork_event->parent_comm);
847         register_pid(fork_event->child_pid, fork_event->child_comm);
848 }
849
850 static struct trace_sched_handler replay_ops  = {
851         .wakeup_event           = replay_wakeup_event,
852         .switch_event           = replay_switch_event,
853         .fork_event             = replay_fork_event,
854 };
855
856 struct sort_dimension {
857         const char              *name;
858         sort_fn_t               cmp;
859         struct list_head        list;
860 };
861
862 static LIST_HEAD(cmp_pid);
863
864 static int
865 thread_lat_cmp(struct list_head *list, struct work_atoms *l, struct work_atoms *r)
866 {
867         struct sort_dimension *sort;
868         int ret = 0;
869
870         BUG_ON(list_empty(list));
871
872         list_for_each_entry(sort, list, list) {
873                 ret = sort->cmp(l, r);
874                 if (ret)
875                         return ret;
876         }
877
878         return ret;
879 }
880
881 static struct work_atoms *
882 thread_atoms_search(struct rb_root *root, struct thread *thread,
883                          struct list_head *sort_list)
884 {
885         struct rb_node *node = root->rb_node;
886         struct work_atoms key = { .thread = thread };
887
888         while (node) {
889                 struct work_atoms *atoms;
890                 int cmp;
891
892                 atoms = container_of(node, struct work_atoms, node);
893
894                 cmp = thread_lat_cmp(sort_list, &key, atoms);
895                 if (cmp > 0)
896                         node = node->rb_left;
897                 else if (cmp < 0)
898                         node = node->rb_right;
899                 else {
900                         BUG_ON(thread != atoms->thread);
901                         return atoms;
902                 }
903         }
904         return NULL;
905 }
906
907 static void
908 __thread_latency_insert(struct rb_root *root, struct work_atoms *data,
909                          struct list_head *sort_list)
910 {
911         struct rb_node **new = &(root->rb_node), *parent = NULL;
912
913         while (*new) {
914                 struct work_atoms *this;
915                 int cmp;
916
917                 this = container_of(*new, struct work_atoms, node);
918                 parent = *new;
919
920                 cmp = thread_lat_cmp(sort_list, data, this);
921
922                 if (cmp > 0)
923                         new = &((*new)->rb_left);
924                 else
925                         new = &((*new)->rb_right);
926         }
927
928         rb_link_node(&data->node, parent, new);
929         rb_insert_color(&data->node, root);
930 }
931
932 static void thread_atoms_insert(struct thread *thread)
933 {
934         struct work_atoms *atoms = zalloc(sizeof(*atoms));
935         if (!atoms)
936                 die("No memory");
937
938         atoms->thread = thread;
939         INIT_LIST_HEAD(&atoms->work_list);
940         __thread_latency_insert(&atom_root, atoms, &cmp_pid);
941 }
942
943 static void
944 latency_fork_event(struct trace_fork_event *fork_event __used,
945                    struct event *event __used,
946                    int cpu __used,
947                    u64 timestamp __used,
948                    struct thread *thread __used)
949 {
950         /* should insert the newcomer */
951 }
952
953 __used
954 static char sched_out_state(struct trace_switch_event *switch_event)
955 {
956         const char *str = TASK_STATE_TO_CHAR_STR;
957
958         return str[switch_event->prev_state];
959 }
960
961 static void
962 add_sched_out_event(struct work_atoms *atoms,
963                     char run_state,
964                     u64 timestamp)
965 {
966         struct work_atom *atom = zalloc(sizeof(*atom));
967         if (!atom)
968                 die("Non memory");
969
970         atom->sched_out_time = timestamp;
971
972         if (run_state == 'R') {
973                 atom->state = THREAD_WAIT_CPU;
974                 atom->wake_up_time = atom->sched_out_time;
975         }
976
977         list_add_tail(&atom->list, &atoms->work_list);
978 }
979
980 static void
981 add_runtime_event(struct work_atoms *atoms, u64 delta, u64 timestamp __used)
982 {
983         struct work_atom *atom;
984
985         BUG_ON(list_empty(&atoms->work_list));
986
987         atom = list_entry(atoms->work_list.prev, struct work_atom, list);
988
989         atom->runtime += delta;
990         atoms->total_runtime += delta;
991 }
992
993 static void
994 add_sched_in_event(struct work_atoms *atoms, u64 timestamp)
995 {
996         struct work_atom *atom;
997         u64 delta;
998
999         if (list_empty(&atoms->work_list))
1000                 return;
1001
1002         atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1003
1004         if (atom->state != THREAD_WAIT_CPU)
1005                 return;
1006
1007         if (timestamp < atom->wake_up_time) {
1008                 atom->state = THREAD_IGNORE;
1009                 return;
1010         }
1011
1012         atom->state = THREAD_SCHED_IN;
1013         atom->sched_in_time = timestamp;
1014
1015         delta = atom->sched_in_time - atom->wake_up_time;
1016         atoms->total_lat += delta;
1017         if (delta > atoms->max_lat) {
1018                 atoms->max_lat = delta;
1019                 atoms->max_lat_at = timestamp;
1020         }
1021         atoms->nb_atoms++;
1022 }
1023
1024 static void
1025 latency_switch_event(struct trace_switch_event *switch_event,
1026                      struct machine *machine,
1027                      struct event *event __used,
1028                      int cpu,
1029                      u64 timestamp,
1030                      struct thread *thread __used)
1031 {
1032         struct work_atoms *out_events, *in_events;
1033         struct thread *sched_out, *sched_in;
1034         u64 timestamp0;
1035         s64 delta;
1036
1037         BUG_ON(cpu >= MAX_CPUS || cpu < 0);
1038
1039         timestamp0 = cpu_last_switched[cpu];
1040         cpu_last_switched[cpu] = timestamp;
1041         if (timestamp0)
1042                 delta = timestamp - timestamp0;
1043         else
1044                 delta = 0;
1045
1046         if (delta < 0)
1047                 die("hm, delta: %" PRIu64 " < 0 ?\n", delta);
1048
1049
1050         sched_out = machine__findnew_thread(machine, switch_event->prev_pid);
1051         sched_in = machine__findnew_thread(machine, switch_event->next_pid);
1052
1053         out_events = thread_atoms_search(&atom_root, sched_out, &cmp_pid);
1054         if (!out_events) {
1055                 thread_atoms_insert(sched_out);
1056                 out_events = thread_atoms_search(&atom_root, sched_out, &cmp_pid);
1057                 if (!out_events)
1058                         die("out-event: Internal tree error");
1059         }
1060         add_sched_out_event(out_events, sched_out_state(switch_event), timestamp);
1061
1062         in_events = thread_atoms_search(&atom_root, sched_in, &cmp_pid);
1063         if (!in_events) {
1064                 thread_atoms_insert(sched_in);
1065                 in_events = thread_atoms_search(&atom_root, sched_in, &cmp_pid);
1066                 if (!in_events)
1067                         die("in-event: Internal tree error");
1068                 /*
1069                  * Take came in we have not heard about yet,
1070                  * add in an initial atom in runnable state:
1071                  */
1072                 add_sched_out_event(in_events, 'R', timestamp);
1073         }
1074         add_sched_in_event(in_events, timestamp);
1075 }
1076
1077 static void
1078 latency_runtime_event(struct trace_runtime_event *runtime_event,
1079                      struct machine *machine,
1080                      struct event *event __used,
1081                      int cpu,
1082                      u64 timestamp,
1083                      struct thread *this_thread __used)
1084 {
1085         struct thread *thread = machine__findnew_thread(machine, runtime_event->pid);
1086         struct work_atoms *atoms = thread_atoms_search(&atom_root, thread, &cmp_pid);
1087
1088         BUG_ON(cpu >= MAX_CPUS || cpu < 0);
1089         if (!atoms) {
1090                 thread_atoms_insert(thread);
1091                 atoms = thread_atoms_search(&atom_root, thread, &cmp_pid);
1092                 if (!atoms)
1093                         die("in-event: Internal tree error");
1094                 add_sched_out_event(atoms, 'R', timestamp);
1095         }
1096
1097         add_runtime_event(atoms, runtime_event->runtime, timestamp);
1098 }
1099
1100 static void
1101 latency_wakeup_event(struct trace_wakeup_event *wakeup_event,
1102                      struct machine *machine,
1103                      struct event *__event __used,
1104                      int cpu __used,
1105                      u64 timestamp,
1106                      struct thread *thread __used)
1107 {
1108         struct work_atoms *atoms;
1109         struct work_atom *atom;
1110         struct thread *wakee;
1111
1112         /* Note for later, it may be interesting to observe the failing cases */
1113         if (!wakeup_event->success)
1114                 return;
1115
1116         wakee = machine__findnew_thread(machine, wakeup_event->pid);
1117         atoms = thread_atoms_search(&atom_root, wakee, &cmp_pid);
1118         if (!atoms) {
1119                 thread_atoms_insert(wakee);
1120                 atoms = thread_atoms_search(&atom_root, wakee, &cmp_pid);
1121                 if (!atoms)
1122                         die("wakeup-event: Internal tree error");
1123                 add_sched_out_event(atoms, 'S', timestamp);
1124         }
1125
1126         BUG_ON(list_empty(&atoms->work_list));
1127
1128         atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1129
1130         /*
1131          * You WILL be missing events if you've recorded only
1132          * one CPU, or are only looking at only one, so don't
1133          * make useless noise.
1134          */
1135         if (profile_cpu == -1 && atom->state != THREAD_SLEEPING)
1136                 nr_state_machine_bugs++;
1137
1138         nr_timestamps++;
1139         if (atom->sched_out_time > timestamp) {
1140                 nr_unordered_timestamps++;
1141                 return;
1142         }
1143
1144         atom->state = THREAD_WAIT_CPU;
1145         atom->wake_up_time = timestamp;
1146 }
1147
1148 static void
1149 latency_migrate_task_event(struct trace_migrate_task_event *migrate_task_event,
1150                      struct machine *machine,
1151                      struct event *__event __used,
1152                      int cpu __used,
1153                      u64 timestamp,
1154                      struct thread *thread __used)
1155 {
1156         struct work_atoms *atoms;
1157         struct work_atom *atom;
1158         struct thread *migrant;
1159
1160         /*
1161          * Only need to worry about migration when profiling one CPU.
1162          */
1163         if (profile_cpu == -1)
1164                 return;
1165
1166         migrant = machine__findnew_thread(machine, migrate_task_event->pid);
1167         atoms = thread_atoms_search(&atom_root, migrant, &cmp_pid);
1168         if (!atoms) {
1169                 thread_atoms_insert(migrant);
1170                 register_pid(migrant->pid, migrant->comm);
1171                 atoms = thread_atoms_search(&atom_root, migrant, &cmp_pid);
1172                 if (!atoms)
1173                         die("migration-event: Internal tree error");
1174                 add_sched_out_event(atoms, 'R', timestamp);
1175         }
1176
1177         BUG_ON(list_empty(&atoms->work_list));
1178
1179         atom = list_entry(atoms->work_list.prev, struct work_atom, list);
1180         atom->sched_in_time = atom->sched_out_time = atom->wake_up_time = timestamp;
1181
1182         nr_timestamps++;
1183
1184         if (atom->sched_out_time > timestamp)
1185                 nr_unordered_timestamps++;
1186 }
1187
1188 static struct trace_sched_handler lat_ops  = {
1189         .wakeup_event           = latency_wakeup_event,
1190         .switch_event           = latency_switch_event,
1191         .runtime_event          = latency_runtime_event,
1192         .fork_event             = latency_fork_event,
1193         .migrate_task_event     = latency_migrate_task_event,
1194 };
1195
1196 static void output_lat_thread(struct work_atoms *work_list)
1197 {
1198         int i;
1199         int ret;
1200         u64 avg;
1201
1202         if (!work_list->nb_atoms)
1203                 return;
1204         /*
1205          * Ignore idle threads:
1206          */
1207         if (!strcmp(work_list->thread->comm, "swapper"))
1208                 return;
1209
1210         all_runtime += work_list->total_runtime;
1211         all_count += work_list->nb_atoms;
1212
1213         ret = printf("  %s:%d ", work_list->thread->comm, work_list->thread->pid);
1214
1215         for (i = 0; i < 24 - ret; i++)
1216                 printf(" ");
1217
1218         avg = work_list->total_lat / work_list->nb_atoms;
1219
1220         printf("|%11.3f ms |%9" PRIu64 " | avg:%9.3f ms | max:%9.3f ms | max at: %9.6f s\n",
1221               (double)work_list->total_runtime / 1e6,
1222                  work_list->nb_atoms, (double)avg / 1e6,
1223                  (double)work_list->max_lat / 1e6,
1224                  (double)work_list->max_lat_at / 1e9);
1225 }
1226
1227 static int pid_cmp(struct work_atoms *l, struct work_atoms *r)
1228 {
1229         if (l->thread->pid < r->thread->pid)
1230                 return -1;
1231         if (l->thread->pid > r->thread->pid)
1232                 return 1;
1233
1234         return 0;
1235 }
1236
1237 static struct sort_dimension pid_sort_dimension = {
1238         .name                   = "pid",
1239         .cmp                    = pid_cmp,
1240 };
1241
1242 static int avg_cmp(struct work_atoms *l, struct work_atoms *r)
1243 {
1244         u64 avgl, avgr;
1245
1246         if (!l->nb_atoms)
1247                 return -1;
1248
1249         if (!r->nb_atoms)
1250                 return 1;
1251
1252         avgl = l->total_lat / l->nb_atoms;
1253         avgr = r->total_lat / r->nb_atoms;
1254
1255         if (avgl < avgr)
1256                 return -1;
1257         if (avgl > avgr)
1258                 return 1;
1259
1260         return 0;
1261 }
1262
1263 static struct sort_dimension avg_sort_dimension = {
1264         .name                   = "avg",
1265         .cmp                    = avg_cmp,
1266 };
1267
1268 static int max_cmp(struct work_atoms *l, struct work_atoms *r)
1269 {
1270         if (l->max_lat < r->max_lat)
1271                 return -1;
1272         if (l->max_lat > r->max_lat)
1273                 return 1;
1274
1275         return 0;
1276 }
1277
1278 static struct sort_dimension max_sort_dimension = {
1279         .name                   = "max",
1280         .cmp                    = max_cmp,
1281 };
1282
1283 static int switch_cmp(struct work_atoms *l, struct work_atoms *r)
1284 {
1285         if (l->nb_atoms < r->nb_atoms)
1286                 return -1;
1287         if (l->nb_atoms > r->nb_atoms)
1288                 return 1;
1289
1290         return 0;
1291 }
1292
1293 static struct sort_dimension switch_sort_dimension = {
1294         .name                   = "switch",
1295         .cmp                    = switch_cmp,
1296 };
1297
1298 static int runtime_cmp(struct work_atoms *l, struct work_atoms *r)
1299 {
1300         if (l->total_runtime < r->total_runtime)
1301                 return -1;
1302         if (l->total_runtime > r->total_runtime)
1303                 return 1;
1304
1305         return 0;
1306 }
1307
1308 static struct sort_dimension runtime_sort_dimension = {
1309         .name                   = "runtime",
1310         .cmp                    = runtime_cmp,
1311 };
1312
1313 static struct sort_dimension *available_sorts[] = {
1314         &pid_sort_dimension,
1315         &avg_sort_dimension,
1316         &max_sort_dimension,
1317         &switch_sort_dimension,
1318         &runtime_sort_dimension,
1319 };
1320
1321 #define NB_AVAILABLE_SORTS      (int)(sizeof(available_sorts) / sizeof(struct sort_dimension *))
1322
1323 static LIST_HEAD(sort_list);
1324
1325 static int sort_dimension__add(const char *tok, struct list_head *list)
1326 {
1327         int i;
1328
1329         for (i = 0; i < NB_AVAILABLE_SORTS; i++) {
1330                 if (!strcmp(available_sorts[i]->name, tok)) {
1331                         list_add_tail(&available_sorts[i]->list, list);
1332
1333                         return 0;
1334                 }
1335         }
1336
1337         return -1;
1338 }
1339
1340 static void setup_sorting(void);
1341
1342 static void sort_lat(void)
1343 {
1344         struct rb_node *node;
1345
1346         for (;;) {
1347                 struct work_atoms *data;
1348                 node = rb_first(&atom_root);
1349                 if (!node)
1350                         break;
1351
1352                 rb_erase(node, &atom_root);
1353                 data = rb_entry(node, struct work_atoms, node);
1354                 __thread_latency_insert(&sorted_atom_root, data, &sort_list);
1355         }
1356 }
1357
1358 static struct trace_sched_handler *trace_handler;
1359
1360 static void
1361 process_sched_wakeup_event(void *data, struct machine *machine,
1362                            struct event *event,
1363                            int cpu __used,
1364                            u64 timestamp __used,
1365                            struct thread *thread __used)
1366 {
1367         struct trace_wakeup_event wakeup_event;
1368
1369         FILL_COMMON_FIELDS(wakeup_event, event, data);
1370
1371         FILL_ARRAY(wakeup_event, comm, event, data);
1372         FILL_FIELD(wakeup_event, pid, event, data);
1373         FILL_FIELD(wakeup_event, prio, event, data);
1374         FILL_FIELD(wakeup_event, success, event, data);
1375         FILL_FIELD(wakeup_event, cpu, event, data);
1376
1377         if (trace_handler->wakeup_event)
1378                 trace_handler->wakeup_event(&wakeup_event, machine, event,
1379                                             cpu, timestamp, thread);
1380 }
1381
1382 /*
1383  * Track the current task - that way we can know whether there's any
1384  * weird events, such as a task being switched away that is not current.
1385  */
1386 static int max_cpu;
1387
1388 static u32 curr_pid[MAX_CPUS] = { [0 ... MAX_CPUS-1] = -1 };
1389
1390 static struct thread *curr_thread[MAX_CPUS];
1391
1392 static char next_shortname1 = 'A';
1393 static char next_shortname2 = '0';
1394
1395 static void
1396 map_switch_event(struct trace_switch_event *switch_event,
1397                  struct machine *machine,
1398                  struct event *event __used,
1399                  int this_cpu,
1400                  u64 timestamp,
1401                  struct thread *thread __used)
1402 {
1403         struct thread *sched_out __used, *sched_in;
1404         int new_shortname;
1405         u64 timestamp0;
1406         s64 delta;
1407         int cpu;
1408
1409         BUG_ON(this_cpu >= MAX_CPUS || this_cpu < 0);
1410
1411         if (this_cpu > max_cpu)
1412                 max_cpu = this_cpu;
1413
1414         timestamp0 = cpu_last_switched[this_cpu];
1415         cpu_last_switched[this_cpu] = timestamp;
1416         if (timestamp0)
1417                 delta = timestamp - timestamp0;
1418         else
1419                 delta = 0;
1420
1421         if (delta < 0)
1422                 die("hm, delta: %" PRIu64 " < 0 ?\n", delta);
1423
1424
1425         sched_out = machine__findnew_thread(machine, switch_event->prev_pid);
1426         sched_in = machine__findnew_thread(machine, switch_event->next_pid);
1427
1428         curr_thread[this_cpu] = sched_in;
1429
1430         printf("  ");
1431
1432         new_shortname = 0;
1433         if (!sched_in->shortname[0]) {
1434                 sched_in->shortname[0] = next_shortname1;
1435                 sched_in->shortname[1] = next_shortname2;
1436
1437                 if (next_shortname1 < 'Z') {
1438                         next_shortname1++;
1439                 } else {
1440                         next_shortname1='A';
1441                         if (next_shortname2 < '9') {
1442                                 next_shortname2++;
1443                         } else {
1444                                 next_shortname2='0';
1445                         }
1446                 }
1447                 new_shortname = 1;
1448         }
1449
1450         for (cpu = 0; cpu <= max_cpu; cpu++) {
1451                 if (cpu != this_cpu)
1452                         printf(" ");
1453                 else
1454                         printf("*");
1455
1456                 if (curr_thread[cpu]) {
1457                         if (curr_thread[cpu]->pid)
1458                                 printf("%2s ", curr_thread[cpu]->shortname);
1459                         else
1460                                 printf(".  ");
1461                 } else
1462                         printf("   ");
1463         }
1464
1465         printf("  %12.6f secs ", (double)timestamp/1e9);
1466         if (new_shortname) {
1467                 printf("%s => %s:%d\n",
1468                         sched_in->shortname, sched_in->comm, sched_in->pid);
1469         } else {
1470                 printf("\n");
1471         }
1472 }
1473
1474
1475 static void
1476 process_sched_switch_event(void *data, struct machine *machine,
1477                            struct event *event,
1478                            int this_cpu,
1479                            u64 timestamp __used,
1480                            struct thread *thread __used)
1481 {
1482         struct trace_switch_event switch_event;
1483
1484         FILL_COMMON_FIELDS(switch_event, event, data);
1485
1486         FILL_ARRAY(switch_event, prev_comm, event, data);
1487         FILL_FIELD(switch_event, prev_pid, event, data);
1488         FILL_FIELD(switch_event, prev_prio, event, data);
1489         FILL_FIELD(switch_event, prev_state, event, data);
1490         FILL_ARRAY(switch_event, next_comm, event, data);
1491         FILL_FIELD(switch_event, next_pid, event, data);
1492         FILL_FIELD(switch_event, next_prio, event, data);
1493
1494         if (curr_pid[this_cpu] != (u32)-1) {
1495                 /*
1496                  * Are we trying to switch away a PID that is
1497                  * not current?
1498                  */
1499                 if (curr_pid[this_cpu] != switch_event.prev_pid)
1500                         nr_context_switch_bugs++;
1501         }
1502         if (trace_handler->switch_event)
1503                 trace_handler->switch_event(&switch_event, machine, event,
1504                                             this_cpu, timestamp, thread);
1505
1506         curr_pid[this_cpu] = switch_event.next_pid;
1507 }
1508
1509 static void
1510 process_sched_runtime_event(void *data, struct machine *machine,
1511                            struct event *event,
1512                            int cpu __used,
1513                            u64 timestamp __used,
1514                            struct thread *thread __used)
1515 {
1516         struct trace_runtime_event runtime_event;
1517
1518         FILL_ARRAY(runtime_event, comm, event, data);
1519         FILL_FIELD(runtime_event, pid, event, data);
1520         FILL_FIELD(runtime_event, runtime, event, data);
1521         FILL_FIELD(runtime_event, vruntime, event, data);
1522
1523         if (trace_handler->runtime_event)
1524                 trace_handler->runtime_event(&runtime_event, machine, event, cpu, timestamp, thread);
1525 }
1526
1527 static void
1528 process_sched_fork_event(void *data,
1529                          struct event *event,
1530                          int cpu __used,
1531                          u64 timestamp __used,
1532                          struct thread *thread __used)
1533 {
1534         struct trace_fork_event fork_event;
1535
1536         FILL_COMMON_FIELDS(fork_event, event, data);
1537
1538         FILL_ARRAY(fork_event, parent_comm, event, data);
1539         FILL_FIELD(fork_event, parent_pid, event, data);
1540         FILL_ARRAY(fork_event, child_comm, event, data);
1541         FILL_FIELD(fork_event, child_pid, event, data);
1542
1543         if (trace_handler->fork_event)
1544                 trace_handler->fork_event(&fork_event, event,
1545                                           cpu, timestamp, thread);
1546 }
1547
1548 static void
1549 process_sched_exit_event(struct event *event,
1550                          int cpu __used,
1551                          u64 timestamp __used,
1552                          struct thread *thread __used)
1553 {
1554         if (verbose)
1555                 printf("sched_exit event %p\n", event);
1556 }
1557
1558 static void
1559 process_sched_migrate_task_event(void *data, struct machine *machine,
1560                            struct event *event,
1561                            int cpu __used,
1562                            u64 timestamp __used,
1563                            struct thread *thread __used)
1564 {
1565         struct trace_migrate_task_event migrate_task_event;
1566
1567         FILL_COMMON_FIELDS(migrate_task_event, event, data);
1568
1569         FILL_ARRAY(migrate_task_event, comm, event, data);
1570         FILL_FIELD(migrate_task_event, pid, event, data);
1571         FILL_FIELD(migrate_task_event, prio, event, data);
1572         FILL_FIELD(migrate_task_event, cpu, event, data);
1573
1574         if (trace_handler->migrate_task_event)
1575                 trace_handler->migrate_task_event(&migrate_task_event, machine,
1576                                                  event, cpu, timestamp, thread);
1577 }
1578
1579 static void process_raw_event(union perf_event *raw_event __used,
1580                               struct machine *machine, void *data, int cpu,
1581                               u64 timestamp, struct thread *thread)
1582 {
1583         struct event *event;
1584         int type;
1585
1586
1587         type = trace_parse_common_type(data);
1588         event = trace_find_event(type);
1589
1590         if (!strcmp(event->name, "sched_switch"))
1591                 process_sched_switch_event(data, machine, event, cpu, timestamp, thread);
1592         if (!strcmp(event->name, "sched_stat_runtime"))
1593                 process_sched_runtime_event(data, machine, event, cpu, timestamp, thread);
1594         if (!strcmp(event->name, "sched_wakeup"))
1595                 process_sched_wakeup_event(data, machine, event, cpu, timestamp, thread);
1596         if (!strcmp(event->name, "sched_wakeup_new"))
1597                 process_sched_wakeup_event(data, machine, event, cpu, timestamp, thread);
1598         if (!strcmp(event->name, "sched_process_fork"))
1599                 process_sched_fork_event(data, event, cpu, timestamp, thread);
1600         if (!strcmp(event->name, "sched_process_exit"))
1601                 process_sched_exit_event(event, cpu, timestamp, thread);
1602         if (!strcmp(event->name, "sched_migrate_task"))
1603                 process_sched_migrate_task_event(data, machine, event, cpu, timestamp, thread);
1604 }
1605
1606 static int process_sample_event(struct perf_tool *tool __used,
1607                                 union perf_event *event,
1608                                 struct perf_sample *sample,
1609                                 struct perf_evsel *evsel,
1610                                 struct machine *machine)
1611 {
1612         struct thread *thread;
1613
1614         if (!(evsel->attr.sample_type & PERF_SAMPLE_RAW))
1615                 return 0;
1616
1617         thread = machine__findnew_thread(machine, sample->pid);
1618         if (thread == NULL) {
1619                 pr_debug("problem processing %d event, skipping it.\n",
1620                          event->header.type);
1621                 return -1;
1622         }
1623
1624         dump_printf(" ... thread: %s:%d\n", thread->comm, thread->pid);
1625
1626         if (profile_cpu != -1 && profile_cpu != (int)sample->cpu)
1627                 return 0;
1628
1629         process_raw_event(event, machine, sample->raw_data, sample->cpu,
1630                           sample->time, thread);
1631
1632         return 0;
1633 }
1634
1635 static struct perf_tool perf_sched = {
1636         .sample                 = process_sample_event,
1637         .comm                   = perf_event__process_comm,
1638         .lost                   = perf_event__process_lost,
1639         .fork                   = perf_event__process_task,
1640         .ordered_samples        = true,
1641 };
1642
1643 static void read_events(bool destroy, struct perf_session **psession)
1644 {
1645         int err = -EINVAL;
1646         struct perf_session *session = perf_session__new(input_name, O_RDONLY,
1647                                                          0, false, &perf_sched);
1648         if (session == NULL)
1649                 die("No Memory");
1650
1651         if (perf_session__has_traces(session, "record -R")) {
1652                 err = perf_session__process_events(session, &perf_sched);
1653                 if (err)
1654                         die("Failed to process events, error %d", err);
1655
1656                 nr_events      = session->hists.stats.nr_events[0];
1657                 nr_lost_events = session->hists.stats.total_lost;
1658                 nr_lost_chunks = session->hists.stats.nr_events[PERF_RECORD_LOST];
1659         }
1660
1661         if (destroy)
1662                 perf_session__delete(session);
1663
1664         if (psession)
1665                 *psession = session;
1666 }
1667
1668 static void print_bad_events(void)
1669 {
1670         if (nr_unordered_timestamps && nr_timestamps) {
1671                 printf("  INFO: %.3f%% unordered timestamps (%ld out of %ld)\n",
1672                         (double)nr_unordered_timestamps/(double)nr_timestamps*100.0,
1673                         nr_unordered_timestamps, nr_timestamps);
1674         }
1675         if (nr_lost_events && nr_events) {
1676                 printf("  INFO: %.3f%% lost events (%ld out of %ld, in %ld chunks)\n",
1677                         (double)nr_lost_events/(double)nr_events*100.0,
1678                         nr_lost_events, nr_events, nr_lost_chunks);
1679         }
1680         if (nr_state_machine_bugs && nr_timestamps) {
1681                 printf("  INFO: %.3f%% state machine bugs (%ld out of %ld)",
1682                         (double)nr_state_machine_bugs/(double)nr_timestamps*100.0,
1683                         nr_state_machine_bugs, nr_timestamps);
1684                 if (nr_lost_events)
1685                         printf(" (due to lost events?)");
1686                 printf("\n");
1687         }
1688         if (nr_context_switch_bugs && nr_timestamps) {
1689                 printf("  INFO: %.3f%% context switch bugs (%ld out of %ld)",
1690                         (double)nr_context_switch_bugs/(double)nr_timestamps*100.0,
1691                         nr_context_switch_bugs, nr_timestamps);
1692                 if (nr_lost_events)
1693                         printf(" (due to lost events?)");
1694                 printf("\n");
1695         }
1696 }
1697
1698 static void __cmd_lat(void)
1699 {
1700         struct rb_node *next;
1701         struct perf_session *session;
1702
1703         setup_pager();
1704         read_events(false, &session);
1705         sort_lat();
1706
1707         printf("\n ---------------------------------------------------------------------------------------------------------------\n");
1708         printf("  Task                  |   Runtime ms  | Switches | Average delay ms | Maximum delay ms | Maximum delay at     |\n");
1709         printf(" ---------------------------------------------------------------------------------------------------------------\n");
1710
1711         next = rb_first(&sorted_atom_root);
1712
1713         while (next) {
1714                 struct work_atoms *work_list;
1715
1716                 work_list = rb_entry(next, struct work_atoms, node);
1717                 output_lat_thread(work_list);
1718                 next = rb_next(next);
1719         }
1720
1721         printf(" -----------------------------------------------------------------------------------------\n");
1722         printf("  TOTAL:                |%11.3f ms |%9" PRIu64 " |\n",
1723                 (double)all_runtime/1e6, all_count);
1724
1725         printf(" ---------------------------------------------------\n");
1726
1727         print_bad_events();
1728         printf("\n");
1729
1730         perf_session__delete(session);
1731 }
1732
1733 static struct trace_sched_handler map_ops  = {
1734         .wakeup_event           = NULL,
1735         .switch_event           = map_switch_event,
1736         .runtime_event          = NULL,
1737         .fork_event             = NULL,
1738 };
1739
1740 static void __cmd_map(void)
1741 {
1742         max_cpu = sysconf(_SC_NPROCESSORS_CONF);
1743
1744         setup_pager();
1745         read_events(true, NULL);
1746         print_bad_events();
1747 }
1748
1749 static void __cmd_replay(void)
1750 {
1751         unsigned long i;
1752
1753         calibrate_run_measurement_overhead();
1754         calibrate_sleep_measurement_overhead();
1755
1756         test_calibrations();
1757
1758         read_events(true, NULL);
1759
1760         printf("nr_run_events:        %ld\n", nr_run_events);
1761         printf("nr_sleep_events:      %ld\n", nr_sleep_events);
1762         printf("nr_wakeup_events:     %ld\n", nr_wakeup_events);
1763
1764         if (targetless_wakeups)
1765                 printf("target-less wakeups:  %ld\n", targetless_wakeups);
1766         if (multitarget_wakeups)
1767                 printf("multi-target wakeups: %ld\n", multitarget_wakeups);
1768         if (nr_run_events_optimized)
1769                 printf("run atoms optimized: %ld\n",
1770                         nr_run_events_optimized);
1771
1772         print_task_traces();
1773         add_cross_task_wakeups();
1774
1775         create_tasks();
1776         printf("------------------------------------------------------------\n");
1777         for (i = 0; i < replay_repeat; i++)
1778                 run_one_test();
1779 }
1780
1781
1782 static const char * const sched_usage[] = {
1783         "perf sched [<options>] {record|latency|map|replay|script}",
1784         NULL
1785 };
1786
1787 static const struct option sched_options[] = {
1788         OPT_STRING('i', "input", &input_name, "file",
1789                     "input file name"),
1790         OPT_INCR('v', "verbose", &verbose,
1791                     "be more verbose (show symbol address, etc)"),
1792         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1793                     "dump raw trace in ASCII"),
1794         OPT_END()
1795 };
1796
1797 static const char * const latency_usage[] = {
1798         "perf sched latency [<options>]",
1799         NULL
1800 };
1801
1802 static const struct option latency_options[] = {
1803         OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1804                    "sort by key(s): runtime, switch, avg, max"),
1805         OPT_INCR('v', "verbose", &verbose,
1806                     "be more verbose (show symbol address, etc)"),
1807         OPT_INTEGER('C', "CPU", &profile_cpu,
1808                     "CPU to profile on"),
1809         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1810                     "dump raw trace in ASCII"),
1811         OPT_END()
1812 };
1813
1814 static const char * const replay_usage[] = {
1815         "perf sched replay [<options>]",
1816         NULL
1817 };
1818
1819 static const struct option replay_options[] = {
1820         OPT_UINTEGER('r', "repeat", &replay_repeat,
1821                      "repeat the workload replay N times (-1: infinite)"),
1822         OPT_INCR('v', "verbose", &verbose,
1823                     "be more verbose (show symbol address, etc)"),
1824         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1825                     "dump raw trace in ASCII"),
1826         OPT_END()
1827 };
1828
1829 static void setup_sorting(void)
1830 {
1831         char *tmp, *tok, *str = strdup(sort_order);
1832
1833         for (tok = strtok_r(str, ", ", &tmp);
1834                         tok; tok = strtok_r(NULL, ", ", &tmp)) {
1835                 if (sort_dimension__add(tok, &sort_list) < 0) {
1836                         error("Unknown --sort key: `%s'", tok);
1837                         usage_with_options(latency_usage, latency_options);
1838                 }
1839         }
1840
1841         free(str);
1842
1843         sort_dimension__add("pid", &cmp_pid);
1844 }
1845
1846 static const char *record_args[] = {
1847         "record",
1848         "-a",
1849         "-R",
1850         "-f",
1851         "-m", "1024",
1852         "-c", "1",
1853         "-e", "sched:sched_switch",
1854         "-e", "sched:sched_stat_wait",
1855         "-e", "sched:sched_stat_sleep",
1856         "-e", "sched:sched_stat_iowait",
1857         "-e", "sched:sched_stat_runtime",
1858         "-e", "sched:sched_process_exit",
1859         "-e", "sched:sched_process_fork",
1860         "-e", "sched:sched_wakeup",
1861         "-e", "sched:sched_migrate_task",
1862 };
1863
1864 static int __cmd_record(int argc, const char **argv)
1865 {
1866         unsigned int rec_argc, i, j;
1867         const char **rec_argv;
1868
1869         rec_argc = ARRAY_SIZE(record_args) + argc - 1;
1870         rec_argv = calloc(rec_argc + 1, sizeof(char *));
1871
1872         if (rec_argv == NULL)
1873                 return -ENOMEM;
1874
1875         for (i = 0; i < ARRAY_SIZE(record_args); i++)
1876                 rec_argv[i] = strdup(record_args[i]);
1877
1878         for (j = 1; j < (unsigned int)argc; j++, i++)
1879                 rec_argv[i] = argv[j];
1880
1881         BUG_ON(i != rec_argc);
1882
1883         return cmd_record(i, rec_argv, NULL);
1884 }
1885
1886 int cmd_sched(int argc, const char **argv, const char *prefix __used)
1887 {
1888         argc = parse_options(argc, argv, sched_options, sched_usage,
1889                              PARSE_OPT_STOP_AT_NON_OPTION);
1890         if (!argc)
1891                 usage_with_options(sched_usage, sched_options);
1892
1893         /*
1894          * Aliased to 'perf script' for now:
1895          */
1896         if (!strcmp(argv[0], "script"))
1897                 return cmd_script(argc, argv, prefix);
1898
1899         symbol__init();
1900         if (!strncmp(argv[0], "rec", 3)) {
1901                 return __cmd_record(argc, argv);
1902         } else if (!strncmp(argv[0], "lat", 3)) {
1903                 trace_handler = &lat_ops;
1904                 if (argc > 1) {
1905                         argc = parse_options(argc, argv, latency_options, latency_usage, 0);
1906                         if (argc)
1907                                 usage_with_options(latency_usage, latency_options);
1908                 }
1909                 setup_sorting();
1910                 __cmd_lat();
1911         } else if (!strcmp(argv[0], "map")) {
1912                 trace_handler = &map_ops;
1913                 setup_sorting();
1914                 __cmd_map();
1915         } else if (!strncmp(argv[0], "rep", 3)) {
1916                 trace_handler = &replay_ops;
1917                 if (argc) {
1918                         argc = parse_options(argc, argv, replay_options, replay_usage, 0);
1919                         if (argc)
1920                                 usage_with_options(replay_usage, replay_options);
1921                 }
1922                 __cmd_replay();
1923         } else {
1924                 usage_with_options(sched_usage, sched_options);
1925         }
1926
1927         return 0;
1928 }