perf sched: Implement multidimensional sorting
[linux-3.10.git] / tools / perf / builtin-sched.c
1 #include "builtin.h"
2
3 #include "util/util.h"
4 #include "util/cache.h"
5 #include "util/symbol.h"
6 #include "util/thread.h"
7 #include "util/header.h"
8
9 #include "util/parse-options.h"
10
11 #include "perf.h"
12 #include "util/debug.h"
13
14 #include "util/trace-event.h"
15 #include <sys/types.h>
16
17
18 #define MAX_CPUS 4096
19
20 static char                     const *input_name = "perf.data";
21 static int                      input;
22 static unsigned long            page_size;
23 static unsigned long            mmap_window = 32;
24
25 static unsigned long            total_comm = 0;
26
27 static struct rb_root           threads;
28 static struct thread            *last_match;
29
30 static struct perf_header       *header;
31 static u64                      sample_type;
32
33 static int                      replay_mode;
34 static int                      lat_mode;
35
36 static char                     default_sort_order[] = "avg, max, switch, runtime";
37 static char                     *sort_order = default_sort_order;
38
39
40 /*
41  * Scheduler benchmarks
42  */
43 #include <sys/resource.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/time.h>
47 #include <sys/prctl.h>
48
49 #include <linux/unistd.h>
50
51 #include <semaphore.h>
52 #include <pthread.h>
53 #include <signal.h>
54 #include <values.h>
55 #include <string.h>
56 #include <unistd.h>
57 #include <stdlib.h>
58 #include <assert.h>
59 #include <fcntl.h>
60 #include <time.h>
61 #include <math.h>
62
63 #include <stdio.h>
64
65 #define PR_SET_NAME     15               /* Set process name */
66
67 #define BUG_ON(x)       assert(!(x))
68
69 #define DEBUG           0
70
71 typedef unsigned long long nsec_t;
72
73 static nsec_t run_measurement_overhead;
74 static nsec_t sleep_measurement_overhead;
75
76 static nsec_t get_nsecs(void)
77 {
78         struct timespec ts;
79
80         clock_gettime(CLOCK_MONOTONIC, &ts);
81
82         return ts.tv_sec * 1000000000ULL + ts.tv_nsec;
83 }
84
85 static void burn_nsecs(nsec_t nsecs)
86 {
87         nsec_t T0 = get_nsecs(), T1;
88
89         do {
90                 T1 = get_nsecs();
91         } while (T1 + run_measurement_overhead < T0 + nsecs);
92 }
93
94 static void sleep_nsecs(nsec_t nsecs)
95 {
96         struct timespec ts;
97
98         ts.tv_nsec = nsecs % 999999999;
99         ts.tv_sec = nsecs / 999999999;
100
101         nanosleep(&ts, NULL);
102 }
103
104 static void calibrate_run_measurement_overhead(void)
105 {
106         nsec_t T0, T1, delta, min_delta = 1000000000ULL;
107         int i;
108
109         for (i = 0; i < 10; i++) {
110                 T0 = get_nsecs();
111                 burn_nsecs(0);
112                 T1 = get_nsecs();
113                 delta = T1-T0;
114                 min_delta = min(min_delta, delta);
115         }
116         run_measurement_overhead = min_delta;
117
118         printf("run measurement overhead: %Ld nsecs\n", min_delta);
119 }
120
121 static void calibrate_sleep_measurement_overhead(void)
122 {
123         nsec_t T0, T1, delta, min_delta = 1000000000ULL;
124         int i;
125
126         for (i = 0; i < 10; i++) {
127                 T0 = get_nsecs();
128                 sleep_nsecs(10000);
129                 T1 = get_nsecs();
130                 delta = T1-T0;
131                 min_delta = min(min_delta, delta);
132         }
133         min_delta -= 10000;
134         sleep_measurement_overhead = min_delta;
135
136         printf("sleep measurement overhead: %Ld nsecs\n", min_delta);
137 }
138
139 #define COMM_LEN        20
140 #define SYM_LEN         129
141
142 #define MAX_PID         65536
143
144 static unsigned long nr_tasks;
145
146 struct sched_event;
147
148 struct task_desc {
149         unsigned long           nr;
150         unsigned long           pid;
151         char                    comm[COMM_LEN];
152
153         unsigned long           nr_events;
154         unsigned long           curr_event;
155         struct sched_event      **events;
156
157         pthread_t               thread;
158         sem_t                   sleep_sem;
159
160         sem_t                   ready_for_work;
161         sem_t                   work_done_sem;
162
163         nsec_t                  cpu_usage;
164 };
165
166 enum sched_event_type {
167         SCHED_EVENT_RUN,
168         SCHED_EVENT_SLEEP,
169         SCHED_EVENT_WAKEUP,
170 };
171
172 struct sched_event {
173         enum sched_event_type   type;
174         nsec_t                  timestamp;
175         nsec_t                  duration;
176         unsigned long           nr;
177         int                     specific_wait;
178         sem_t                   *wait_sem;
179         struct task_desc        *wakee;
180 };
181
182 static struct task_desc         *pid_to_task[MAX_PID];
183
184 static struct task_desc         **tasks;
185
186 static pthread_mutex_t          start_work_mutex = PTHREAD_MUTEX_INITIALIZER;
187 static nsec_t                   start_time;
188
189 static pthread_mutex_t          work_done_wait_mutex = PTHREAD_MUTEX_INITIALIZER;
190
191 static unsigned long            nr_run_events;
192 static unsigned long            nr_sleep_events;
193 static unsigned long            nr_wakeup_events;
194
195 static unsigned long            nr_sleep_corrections;
196 static unsigned long            nr_run_events_optimized;
197
198 static struct sched_event *
199 get_new_event(struct task_desc *task, nsec_t timestamp)
200 {
201         struct sched_event *event = calloc(1, sizeof(*event));
202         unsigned long idx = task->nr_events;
203         size_t size;
204
205         event->timestamp = timestamp;
206         event->nr = idx;
207
208         task->nr_events++;
209         size = sizeof(struct sched_event *) * task->nr_events;
210         task->events = realloc(task->events, size);
211         BUG_ON(!task->events);
212
213         task->events[idx] = event;
214
215         return event;
216 }
217
218 static struct sched_event *last_event(struct task_desc *task)
219 {
220         if (!task->nr_events)
221                 return NULL;
222
223         return task->events[task->nr_events - 1];
224 }
225
226 static void
227 add_sched_event_run(struct task_desc *task, nsec_t timestamp, u64 duration)
228 {
229         struct sched_event *event, *curr_event = last_event(task);
230
231         /*
232          * optimize an existing RUN event by merging this one
233          * to it:
234          */
235         if (curr_event && curr_event->type == SCHED_EVENT_RUN) {
236                 nr_run_events_optimized++;
237                 curr_event->duration += duration;
238                 return;
239         }
240
241         event = get_new_event(task, timestamp);
242
243         event->type = SCHED_EVENT_RUN;
244         event->duration = duration;
245
246         nr_run_events++;
247 }
248
249 static unsigned long            targetless_wakeups;
250 static unsigned long            multitarget_wakeups;
251
252 static void
253 add_sched_event_wakeup(struct task_desc *task, nsec_t timestamp,
254                        struct task_desc *wakee)
255 {
256         struct sched_event *event, *wakee_event;
257
258         event = get_new_event(task, timestamp);
259         event->type = SCHED_EVENT_WAKEUP;
260         event->wakee = wakee;
261
262         wakee_event = last_event(wakee);
263         if (!wakee_event || wakee_event->type != SCHED_EVENT_SLEEP) {
264                 targetless_wakeups++;
265                 return;
266         }
267         if (wakee_event->wait_sem) {
268                 multitarget_wakeups++;
269                 return;
270         }
271
272         wakee_event->wait_sem = calloc(1, sizeof(*wakee_event->wait_sem));
273         sem_init(wakee_event->wait_sem, 0, 0);
274         wakee_event->specific_wait = 1;
275         event->wait_sem = wakee_event->wait_sem;
276
277         nr_wakeup_events++;
278 }
279
280 static void
281 add_sched_event_sleep(struct task_desc *task, nsec_t timestamp,
282                       u64 task_state __used)
283 {
284         struct sched_event *event = get_new_event(task, timestamp);
285
286         event->type = SCHED_EVENT_SLEEP;
287
288         nr_sleep_events++;
289 }
290
291 static struct task_desc *register_pid(unsigned long pid, const char *comm)
292 {
293         struct task_desc *task;
294
295         BUG_ON(pid >= MAX_PID);
296
297         task = pid_to_task[pid];
298
299         if (task)
300                 return task;
301
302         task = calloc(1, sizeof(*task));
303         task->pid = pid;
304         task->nr = nr_tasks;
305         strcpy(task->comm, comm);
306         /*
307          * every task starts in sleeping state - this gets ignored
308          * if there's no wakeup pointing to this sleep state:
309          */
310         add_sched_event_sleep(task, 0, 0);
311
312         pid_to_task[pid] = task;
313         nr_tasks++;
314         tasks = realloc(tasks, nr_tasks*sizeof(struct task_task *));
315         BUG_ON(!tasks);
316         tasks[task->nr] = task;
317
318         if (verbose)
319                 printf("registered task #%ld, PID %ld (%s)\n", nr_tasks, pid, comm);
320
321         return task;
322 }
323
324
325 static void print_task_traces(void)
326 {
327         struct task_desc *task;
328         unsigned long i;
329
330         for (i = 0; i < nr_tasks; i++) {
331                 task = tasks[i];
332                 printf("task %6ld (%20s:%10ld), nr_events: %ld\n",
333                         task->nr, task->comm, task->pid, task->nr_events);
334         }
335 }
336
337 static void add_cross_task_wakeups(void)
338 {
339         struct task_desc *task1, *task2;
340         unsigned long i, j;
341
342         for (i = 0; i < nr_tasks; i++) {
343                 task1 = tasks[i];
344                 j = i + 1;
345                 if (j == nr_tasks)
346                         j = 0;
347                 task2 = tasks[j];
348                 add_sched_event_wakeup(task1, 0, task2);
349         }
350 }
351
352 static void
353 process_sched_event(struct task_desc *this_task __used, struct sched_event *event)
354 {
355         int ret = 0;
356         nsec_t now;
357         long long delta;
358
359         now = get_nsecs();
360         delta = start_time + event->timestamp - now;
361
362         switch (event->type) {
363                 case SCHED_EVENT_RUN:
364                         burn_nsecs(event->duration);
365                         break;
366                 case SCHED_EVENT_SLEEP:
367                         if (event->wait_sem)
368                                 ret = sem_wait(event->wait_sem);
369                         BUG_ON(ret);
370                         break;
371                 case SCHED_EVENT_WAKEUP:
372                         if (event->wait_sem)
373                                 ret = sem_post(event->wait_sem);
374                         BUG_ON(ret);
375                         break;
376                 default:
377                         BUG_ON(1);
378         }
379 }
380
381 static nsec_t get_cpu_usage_nsec_parent(void)
382 {
383         struct rusage ru;
384         nsec_t sum;
385         int err;
386
387         err = getrusage(RUSAGE_SELF, &ru);
388         BUG_ON(err);
389
390         sum =  ru.ru_utime.tv_sec*1e9 + ru.ru_utime.tv_usec*1e3;
391         sum += ru.ru_stime.tv_sec*1e9 + ru.ru_stime.tv_usec*1e3;
392
393         return sum;
394 }
395
396 static nsec_t get_cpu_usage_nsec_self(void)
397 {
398         char filename [] = "/proc/1234567890/sched";
399         unsigned long msecs, nsecs;
400         char *line = NULL;
401         nsec_t total = 0;
402         size_t len = 0;
403         ssize_t chars;
404         FILE *file;
405         int ret;
406
407         sprintf(filename, "/proc/%d/sched", getpid());
408         file = fopen(filename, "r");
409         BUG_ON(!file);
410
411         while ((chars = getline(&line, &len, file)) != -1) {
412                 ret = sscanf(line, "se.sum_exec_runtime : %ld.%06ld\n",
413                         &msecs, &nsecs);
414                 if (ret == 2) {
415                         total = msecs*1e6 + nsecs;
416                         break;
417                 }
418         }
419         if (line)
420                 free(line);
421         fclose(file);
422
423         return total;
424 }
425
426 static void *thread_func(void *ctx)
427 {
428         struct task_desc *this_task = ctx;
429         nsec_t cpu_usage_0, cpu_usage_1;
430         unsigned long i, ret;
431         char comm2[22];
432
433         sprintf(comm2, ":%s", this_task->comm);
434         prctl(PR_SET_NAME, comm2);
435
436 again:
437         ret = sem_post(&this_task->ready_for_work);
438         BUG_ON(ret);
439         ret = pthread_mutex_lock(&start_work_mutex);
440         BUG_ON(ret);
441         ret = pthread_mutex_unlock(&start_work_mutex);
442         BUG_ON(ret);
443
444         cpu_usage_0 = get_cpu_usage_nsec_self();
445
446         for (i = 0; i < this_task->nr_events; i++) {
447                 this_task->curr_event = i;
448                 process_sched_event(this_task, this_task->events[i]);
449         }
450
451         cpu_usage_1 = get_cpu_usage_nsec_self();
452         this_task->cpu_usage = cpu_usage_1 - cpu_usage_0;
453
454         ret = sem_post(&this_task->work_done_sem);
455         BUG_ON(ret);
456
457         ret = pthread_mutex_lock(&work_done_wait_mutex);
458         BUG_ON(ret);
459         ret = pthread_mutex_unlock(&work_done_wait_mutex);
460         BUG_ON(ret);
461
462         goto again;
463 }
464
465 static void create_tasks(void)
466 {
467         struct task_desc *task;
468         pthread_attr_t attr;
469         unsigned long i;
470         int err;
471
472         err = pthread_attr_init(&attr);
473         BUG_ON(err);
474         err = pthread_attr_setstacksize(&attr, (size_t)(16*1024));
475         BUG_ON(err);
476         err = pthread_mutex_lock(&start_work_mutex);
477         BUG_ON(err);
478         err = pthread_mutex_lock(&work_done_wait_mutex);
479         BUG_ON(err);
480         for (i = 0; i < nr_tasks; i++) {
481                 task = tasks[i];
482                 sem_init(&task->sleep_sem, 0, 0);
483                 sem_init(&task->ready_for_work, 0, 0);
484                 sem_init(&task->work_done_sem, 0, 0);
485                 task->curr_event = 0;
486                 err = pthread_create(&task->thread, &attr, thread_func, task);
487                 BUG_ON(err);
488         }
489 }
490
491 static nsec_t                   cpu_usage;
492 static nsec_t                   runavg_cpu_usage;
493 static nsec_t                   parent_cpu_usage;
494 static nsec_t                   runavg_parent_cpu_usage;
495
496 static void wait_for_tasks(void)
497 {
498         nsec_t cpu_usage_0, cpu_usage_1;
499         struct task_desc *task;
500         unsigned long i, ret;
501
502         start_time = get_nsecs();
503         cpu_usage = 0;
504         pthread_mutex_unlock(&work_done_wait_mutex);
505
506         for (i = 0; i < nr_tasks; i++) {
507                 task = tasks[i];
508                 ret = sem_wait(&task->ready_for_work);
509                 BUG_ON(ret);
510                 sem_init(&task->ready_for_work, 0, 0);
511         }
512         ret = pthread_mutex_lock(&work_done_wait_mutex);
513         BUG_ON(ret);
514
515         cpu_usage_0 = get_cpu_usage_nsec_parent();
516
517         pthread_mutex_unlock(&start_work_mutex);
518
519         for (i = 0; i < nr_tasks; i++) {
520                 task = tasks[i];
521                 ret = sem_wait(&task->work_done_sem);
522                 BUG_ON(ret);
523                 sem_init(&task->work_done_sem, 0, 0);
524                 cpu_usage += task->cpu_usage;
525                 task->cpu_usage = 0;
526         }
527
528         cpu_usage_1 = get_cpu_usage_nsec_parent();
529         if (!runavg_cpu_usage)
530                 runavg_cpu_usage = cpu_usage;
531         runavg_cpu_usage = (runavg_cpu_usage*9 + cpu_usage)/10;
532
533         parent_cpu_usage = cpu_usage_1 - cpu_usage_0;
534         if (!runavg_parent_cpu_usage)
535                 runavg_parent_cpu_usage = parent_cpu_usage;
536         runavg_parent_cpu_usage = (runavg_parent_cpu_usage*9 +
537                                    parent_cpu_usage)/10;
538
539         ret = pthread_mutex_lock(&start_work_mutex);
540         BUG_ON(ret);
541
542         for (i = 0; i < nr_tasks; i++) {
543                 task = tasks[i];
544                 sem_init(&task->sleep_sem, 0, 0);
545                 task->curr_event = 0;
546         }
547 }
548
549 static int read_events(void);
550
551 static unsigned long nr_runs;
552 static nsec_t sum_runtime;
553 static nsec_t sum_fluct;
554 static nsec_t run_avg;
555
556 static void run_one_test(void)
557 {
558         nsec_t T0, T1, delta, avg_delta, fluct, std_dev;
559
560         T0 = get_nsecs();
561         wait_for_tasks();
562         T1 = get_nsecs();
563
564         delta = T1 - T0;
565         sum_runtime += delta;
566         nr_runs++;
567
568         avg_delta = sum_runtime / nr_runs;
569         if (delta < avg_delta)
570                 fluct = avg_delta - delta;
571         else
572                 fluct = delta - avg_delta;
573         sum_fluct += fluct;
574         std_dev = sum_fluct / nr_runs / sqrt(nr_runs);
575         if (!run_avg)
576                 run_avg = delta;
577         run_avg = (run_avg*9 + delta)/10;
578
579         printf("#%-3ld: %0.3f, ",
580                 nr_runs, (double)delta/1000000.0);
581
582 #if 0
583         printf("%0.2f +- %0.2f, ",
584                 (double)avg_delta/1e6, (double)std_dev/1e6);
585 #endif
586         printf("ravg: %0.2f, ",
587                 (double)run_avg/1e6);
588
589         printf("cpu: %0.2f / %0.2f",
590                 (double)cpu_usage/1e6, (double)runavg_cpu_usage/1e6);
591
592 #if 0
593         /*
594          * rusage statistics done by the parent, these are less
595          * accurate than the sum_exec_runtime based statistics:
596          */
597         printf(" [%0.2f / %0.2f]",
598                 (double)parent_cpu_usage/1e6,
599                 (double)runavg_parent_cpu_usage/1e6);
600 #endif
601
602         printf("\n");
603
604         if (nr_sleep_corrections)
605                 printf(" (%ld sleep corrections)\n", nr_sleep_corrections);
606         nr_sleep_corrections = 0;
607 }
608
609 static void test_calibrations(void)
610 {
611         nsec_t T0, T1;
612
613         T0 = get_nsecs();
614         burn_nsecs(1e6);
615         T1 = get_nsecs();
616
617         printf("the run test took %Ld nsecs\n", T1-T0);
618
619         T0 = get_nsecs();
620         sleep_nsecs(1e6);
621         T1 = get_nsecs();
622
623         printf("the sleep test took %Ld nsecs\n", T1-T0);
624 }
625
626 static void __cmd_replay(void)
627 {
628         long nr_iterations = 10, i;
629
630         calibrate_run_measurement_overhead();
631         calibrate_sleep_measurement_overhead();
632
633         test_calibrations();
634
635         read_events();
636
637         printf("nr_run_events:        %ld\n", nr_run_events);
638         printf("nr_sleep_events:      %ld\n", nr_sleep_events);
639         printf("nr_wakeup_events:     %ld\n", nr_wakeup_events);
640
641         if (targetless_wakeups)
642                 printf("target-less wakeups:  %ld\n", targetless_wakeups);
643         if (multitarget_wakeups)
644                 printf("multi-target wakeups: %ld\n", multitarget_wakeups);
645         if (nr_run_events_optimized)
646                 printf("run events optimized: %ld\n",
647                         nr_run_events_optimized);
648
649         print_task_traces();
650         add_cross_task_wakeups();
651
652         create_tasks();
653         printf("------------------------------------------------------------\n");
654         for (i = 0; i < nr_iterations; i++)
655                 run_one_test();
656 }
657
658 static int
659 process_comm_event(event_t *event, unsigned long offset, unsigned long head)
660 {
661         struct thread *thread;
662
663         thread = threads__findnew(event->comm.pid, &threads, &last_match);
664
665         dump_printf("%p [%p]: PERF_EVENT_COMM: %s:%d\n",
666                 (void *)(offset + head),
667                 (void *)(long)(event->header.size),
668                 event->comm.comm, event->comm.pid);
669
670         if (thread == NULL ||
671             thread__set_comm(thread, event->comm.comm)) {
672                 dump_printf("problem processing PERF_EVENT_COMM, skipping event.\n");
673                 return -1;
674         }
675         total_comm++;
676
677         return 0;
678 }
679
680
681 struct raw_event_sample {
682         u32 size;
683         char data[0];
684 };
685
686 #define FILL_FIELD(ptr, field, event, data)     \
687         ptr.field = (typeof(ptr.field)) raw_field_value(event, #field, data)
688
689 #define FILL_ARRAY(ptr, array, event, data)                     \
690 do {                                                            \
691         void *__array = raw_field_ptr(event, #array, data);     \
692         memcpy(ptr.array, __array, sizeof(ptr.array));  \
693 } while(0)
694
695 #define FILL_COMMON_FIELDS(ptr, event, data)                    \
696 do {                                                            \
697         FILL_FIELD(ptr, common_type, event, data);              \
698         FILL_FIELD(ptr, common_flags, event, data);             \
699         FILL_FIELD(ptr, common_preempt_count, event, data);     \
700         FILL_FIELD(ptr, common_pid, event, data);               \
701         FILL_FIELD(ptr, common_tgid, event, data);              \
702 } while (0)
703
704
705
706 struct trace_switch_event {
707         u32 size;
708
709         u16 common_type;
710         u8 common_flags;
711         u8 common_preempt_count;
712         u32 common_pid;
713         u32 common_tgid;
714
715         char prev_comm[16];
716         u32 prev_pid;
717         u32 prev_prio;
718         u64 prev_state;
719         char next_comm[16];
720         u32 next_pid;
721         u32 next_prio;
722 };
723
724
725 struct trace_wakeup_event {
726         u32 size;
727
728         u16 common_type;
729         u8 common_flags;
730         u8 common_preempt_count;
731         u32 common_pid;
732         u32 common_tgid;
733
734         char comm[16];
735         u32 pid;
736
737         u32 prio;
738         u32 success;
739         u32 cpu;
740 };
741
742 struct trace_fork_event {
743         u32 size;
744
745         u16 common_type;
746         u8 common_flags;
747         u8 common_preempt_count;
748         u32 common_pid;
749         u32 common_tgid;
750
751         char parent_comm[16];
752         u32 parent_pid;
753         char child_comm[16];
754         u32 child_pid;
755 };
756
757 struct trace_sched_handler {
758         void (*switch_event)(struct trace_switch_event *,
759                              struct event *,
760                              int cpu,
761                              u64 timestamp,
762                              struct thread *thread);
763
764         void (*wakeup_event)(struct trace_wakeup_event *,
765                              struct event *,
766                              int cpu,
767                              u64 timestamp,
768                              struct thread *thread);
769
770         void (*fork_event)(struct trace_fork_event *,
771                            struct event *,
772                            int cpu,
773                            u64 timestamp,
774                            struct thread *thread);
775 };
776
777
778 static void
779 replay_wakeup_event(struct trace_wakeup_event *wakeup_event,
780                     struct event *event,
781                     int cpu __used,
782                     u64 timestamp __used,
783                     struct thread *thread __used)
784 {
785         struct task_desc *waker, *wakee;
786
787         if (verbose) {
788                 printf("sched_wakeup event %p\n", event);
789
790                 printf(" ... pid %d woke up %s/%d\n",
791                         wakeup_event->common_pid,
792                         wakeup_event->comm,
793                         wakeup_event->pid);
794         }
795
796         waker = register_pid(wakeup_event->common_pid, "<unknown>");
797         wakee = register_pid(wakeup_event->pid, wakeup_event->comm);
798
799         add_sched_event_wakeup(waker, timestamp, wakee);
800 }
801
802 static unsigned long cpu_last_switched[MAX_CPUS];
803
804 static void
805 replay_switch_event(struct trace_switch_event *switch_event,
806                     struct event *event,
807                     int cpu,
808                     u64 timestamp,
809                     struct thread *thread __used)
810 {
811         struct task_desc *prev, *next;
812         u64 timestamp0;
813         s64 delta;
814
815         if (verbose)
816                 printf("sched_switch event %p\n", event);
817
818         if (cpu >= MAX_CPUS || cpu < 0)
819                 return;
820
821         timestamp0 = cpu_last_switched[cpu];
822         if (timestamp0)
823                 delta = timestamp - timestamp0;
824         else
825                 delta = 0;
826
827         if (delta < 0)
828                 die("hm, delta: %Ld < 0 ?\n", delta);
829
830         if (verbose) {
831                 printf(" ... switch from %s/%d to %s/%d [ran %Ld nsecs]\n",
832                         switch_event->prev_comm, switch_event->prev_pid,
833                         switch_event->next_comm, switch_event->next_pid,
834                         delta);
835         }
836
837         prev = register_pid(switch_event->prev_pid, switch_event->prev_comm);
838         next = register_pid(switch_event->next_pid, switch_event->next_comm);
839
840         cpu_last_switched[cpu] = timestamp;
841
842         add_sched_event_run(prev, timestamp, delta);
843         add_sched_event_sleep(prev, timestamp, switch_event->prev_state);
844 }
845
846
847 static void
848 replay_fork_event(struct trace_fork_event *fork_event,
849                   struct event *event,
850                   int cpu __used,
851                   u64 timestamp __used,
852                   struct thread *thread __used)
853 {
854         if (verbose) {
855                 printf("sched_fork event %p\n", event);
856                 printf("... parent: %s/%d\n", fork_event->parent_comm, fork_event->parent_pid);
857                 printf("...  child: %s/%d\n", fork_event->child_comm, fork_event->child_pid);
858         }
859         register_pid(fork_event->parent_pid, fork_event->parent_comm);
860         register_pid(fork_event->child_pid, fork_event->child_comm);
861 }
862
863 static struct trace_sched_handler replay_ops  = {
864         .wakeup_event           = replay_wakeup_event,
865         .switch_event           = replay_switch_event,
866         .fork_event             = replay_fork_event,
867 };
868
869 #define TASK_STATE_TO_CHAR_STR "RSDTtZX"
870
871 enum thread_state {
872         THREAD_SLEEPING = 0,
873         THREAD_WAIT_CPU,
874         THREAD_SCHED_IN,
875         THREAD_IGNORE
876 };
877
878 struct work_atom {
879         struct list_head        list;
880         enum thread_state       state;
881         u64                     wake_up_time;
882         u64                     sched_in_time;
883         u64                     runtime;
884 };
885
886 struct task_atoms {
887         struct list_head        snapshot_list;
888         struct thread           *thread;
889         struct rb_node          node;
890         u64                     max_lat;
891         u64                     total_lat;
892         u64                     nb_atoms;
893         u64                     total_runtime;
894 };
895
896 typedef int (*sort_thread_lat)(struct task_atoms *, struct task_atoms *);
897
898 struct sort_dimension {
899         const char              *name;
900         sort_thread_lat         cmp;
901         struct list_head        list;
902 };
903
904 static LIST_HEAD(cmp_pid);
905
906 static struct rb_root lat_snapshot_root, sorted_lat_snapshot_root;
907
908 static struct task_atoms *
909 thread_atom_list_search(struct rb_root *root, struct thread *thread)
910 {
911         struct rb_node *node = root->rb_node;
912
913         while (node) {
914                 struct task_atoms *atoms;
915
916                 atoms = container_of(node, struct task_atoms, node);
917                 if (thread->pid > atoms->thread->pid)
918                         node = node->rb_left;
919                 else if (thread->pid < atoms->thread->pid)
920                         node = node->rb_right;
921                 else {
922                         return atoms;
923                 }
924         }
925         return NULL;
926 }
927
928 static int
929 thread_lat_cmp(struct list_head *list, struct task_atoms *l,
930                struct task_atoms *r)
931 {
932         struct sort_dimension *sort;
933         int ret = 0;
934
935         list_for_each_entry(sort, list, list) {
936                 ret = sort->cmp(l, r);
937                 if (ret)
938                         return ret;
939         }
940
941         return ret;
942 }
943
944 static void
945 __thread_latency_insert(struct rb_root *root, struct task_atoms *data,
946                          struct list_head *sort_list)
947 {
948         struct rb_node **new = &(root->rb_node), *parent = NULL;
949
950         while (*new) {
951                 struct task_atoms *this;
952                 int cmp;
953
954                 this = container_of(*new, struct task_atoms, node);
955                 parent = *new;
956
957                 cmp = thread_lat_cmp(sort_list, data, this);
958
959                 if (cmp > 0)
960                         new = &((*new)->rb_left);
961                 else
962                         new = &((*new)->rb_right);
963         }
964
965         rb_link_node(&data->node, parent, new);
966         rb_insert_color(&data->node, root);
967 }
968
969 static void thread_atom_list_insert(struct thread *thread)
970 {
971         struct task_atoms *atoms;
972         atoms = calloc(sizeof(*atoms), 1);
973         if (!atoms)
974                 die("No memory");
975
976         atoms->thread = thread;
977         INIT_LIST_HEAD(&atoms->snapshot_list);
978         __thread_latency_insert(&lat_snapshot_root, atoms, &cmp_pid);
979 }
980
981 static void
982 latency_fork_event(struct trace_fork_event *fork_event __used,
983                    struct event *event __used,
984                    int cpu __used,
985                    u64 timestamp __used,
986                    struct thread *thread __used)
987 {
988         /* should insert the newcomer */
989 }
990
991 __used
992 static char sched_out_state(struct trace_switch_event *switch_event)
993 {
994         const char *str = TASK_STATE_TO_CHAR_STR;
995
996         return str[switch_event->prev_state];
997 }
998
999 static void
1000 lat_sched_out(struct task_atoms *atoms,
1001               struct trace_switch_event *switch_event __used,
1002               u64 delta,
1003               u64 timestamp)
1004 {
1005         struct work_atom *snapshot;
1006
1007         snapshot = calloc(sizeof(*snapshot), 1);
1008         if (!snapshot)
1009                 die("Non memory");
1010
1011         if (sched_out_state(switch_event) == 'R') {
1012                 snapshot->state = THREAD_WAIT_CPU;
1013                 snapshot->wake_up_time = timestamp;
1014         }
1015
1016         snapshot->runtime = delta;
1017         list_add_tail(&snapshot->list, &atoms->snapshot_list);
1018 }
1019
1020 static void
1021 lat_sched_in(struct task_atoms *atoms, u64 timestamp)
1022 {
1023         struct work_atom *snapshot;
1024         u64 delta;
1025
1026         if (list_empty(&atoms->snapshot_list))
1027                 return;
1028
1029         snapshot = list_entry(atoms->snapshot_list.prev, struct work_atom,
1030                               list);
1031
1032         if (snapshot->state != THREAD_WAIT_CPU)
1033                 return;
1034
1035         if (timestamp < snapshot->wake_up_time) {
1036                 snapshot->state = THREAD_IGNORE;
1037                 return;
1038         }
1039
1040         snapshot->state = THREAD_SCHED_IN;
1041         snapshot->sched_in_time = timestamp;
1042
1043         delta = snapshot->sched_in_time - snapshot->wake_up_time;
1044         atoms->total_lat += delta;
1045         if (delta > atoms->max_lat)
1046                 atoms->max_lat = delta;
1047         atoms->nb_atoms++;
1048         atoms->total_runtime += snapshot->runtime;
1049 }
1050
1051 static void
1052 latency_switch_event(struct trace_switch_event *switch_event,
1053                      struct event *event __used,
1054                      int cpu,
1055                      u64 timestamp,
1056                      struct thread *thread __used)
1057 {
1058         struct task_atoms *out_atoms, *in_atoms;
1059         struct thread *sched_out, *sched_in;
1060         u64 timestamp0;
1061         s64 delta;
1062
1063         if (cpu >= MAX_CPUS || cpu < 0)
1064                 return;
1065
1066         timestamp0 = cpu_last_switched[cpu];
1067         cpu_last_switched[cpu] = timestamp;
1068         if (timestamp0)
1069                 delta = timestamp - timestamp0;
1070         else
1071                 delta = 0;
1072
1073         if (delta < 0)
1074                 die("hm, delta: %Ld < 0 ?\n", delta);
1075
1076
1077         sched_out = threads__findnew(switch_event->prev_pid, &threads, &last_match);
1078         sched_in = threads__findnew(switch_event->next_pid, &threads, &last_match);
1079
1080         in_atoms = thread_atom_list_search(&lat_snapshot_root, sched_in);
1081         if (!in_atoms) {
1082                 thread_atom_list_insert(sched_in);
1083                 in_atoms = thread_atom_list_search(&lat_snapshot_root, sched_in);
1084                 if (!in_atoms)
1085                         die("Internal latency tree error");
1086         }
1087
1088         out_atoms = thread_atom_list_search(&lat_snapshot_root, sched_out);
1089         if (!out_atoms) {
1090                 thread_atom_list_insert(sched_out);
1091                 out_atoms = thread_atom_list_search(&lat_snapshot_root, sched_out);
1092                 if (!out_atoms)
1093                         die("Internal latency tree error");
1094         }
1095
1096         lat_sched_in(in_atoms, timestamp);
1097         lat_sched_out(out_atoms, switch_event, delta, timestamp);
1098 }
1099
1100 static void
1101 latency_wakeup_event(struct trace_wakeup_event *wakeup_event,
1102                      struct event *event __used,
1103                      int cpu __used,
1104                      u64 timestamp,
1105                      struct thread *thread __used)
1106 {
1107         struct task_atoms *atoms;
1108         struct work_atom *snapshot;
1109         struct thread *wakee;
1110
1111         /* Note for later, it may be interesting to observe the failing cases */
1112         if (!wakeup_event->success)
1113                 return;
1114
1115         wakee = threads__findnew(wakeup_event->pid, &threads, &last_match);
1116         atoms = thread_atom_list_search(&lat_snapshot_root, wakee);
1117         if (!atoms) {
1118                 thread_atom_list_insert(wakee);
1119                 return;
1120         }
1121
1122         if (list_empty(&atoms->snapshot_list))
1123                 return;
1124
1125         snapshot = list_entry(atoms->snapshot_list.prev, struct work_atom,
1126                               list);
1127
1128         if (snapshot->state != THREAD_SLEEPING)
1129                 return;
1130
1131         snapshot->state = THREAD_WAIT_CPU;
1132         snapshot->wake_up_time = timestamp;
1133 }
1134
1135 static struct trace_sched_handler lat_ops  = {
1136         .wakeup_event           = latency_wakeup_event,
1137         .switch_event           = latency_switch_event,
1138         .fork_event             = latency_fork_event,
1139 };
1140
1141 static u64 all_runtime;
1142 static u64 all_count;
1143
1144 static void output_lat_thread(struct task_atoms *atom_list)
1145 {
1146         int i;
1147         int ret;
1148         u64 avg;
1149
1150         if (!atom_list->nb_atoms)
1151                 return;
1152
1153         all_runtime += atom_list->total_runtime;
1154         all_count += atom_list->nb_atoms;
1155
1156         ret = printf(" %s ", atom_list->thread->comm);
1157
1158         for (i = 0; i < 19 - ret; i++)
1159                 printf(" ");
1160
1161         avg = atom_list->total_lat / atom_list->nb_atoms;
1162
1163         printf("|%9.3f ms |%9llu | avg:%9.3f ms | max:%9.3f ms |\n",
1164               (double)atom_list->total_runtime / 1e6,
1165                  atom_list->nb_atoms, (double)avg / 1e6,
1166                  (double)atom_list->max_lat / 1e6);
1167 }
1168
1169 static int pid_cmp(struct task_atoms *l, struct task_atoms *r)
1170 {
1171
1172         if (l->thread->pid < r->thread->pid)
1173                 return -1;
1174         if (l->thread->pid > r->thread->pid)
1175                 return 1;
1176
1177         return 0;
1178 }
1179
1180 static struct sort_dimension pid_sort_dimension = {
1181         .name = "pid",
1182         .cmp = pid_cmp,
1183 };
1184
1185 static int avg_cmp(struct task_atoms *l, struct task_atoms *r)
1186 {
1187         u64 avgl, avgr;
1188
1189         if (!l->nb_atoms)
1190                 return -1;
1191
1192         if (!r->nb_atoms)
1193                 return 1;
1194
1195         avgl = l->total_lat / l->nb_atoms;
1196         avgr = r->total_lat / r->nb_atoms;
1197
1198         if (avgl < avgr)
1199                 return -1;
1200         if (avgl > avgr)
1201                 return 1;
1202
1203         return 0;
1204 }
1205
1206 static struct sort_dimension avg_sort_dimension = {
1207         .name   = "avg",
1208         .cmp    = avg_cmp,
1209 };
1210
1211 static int max_cmp(struct task_atoms *l, struct task_atoms *r)
1212 {
1213         if (l->max_lat < r->max_lat)
1214                 return -1;
1215         if (l->max_lat > r->max_lat)
1216                 return 1;
1217
1218         return 0;
1219 }
1220
1221 static struct sort_dimension max_sort_dimension = {
1222         .name   = "max",
1223         .cmp    = max_cmp,
1224 };
1225
1226 static int switch_cmp(struct task_atoms *l, struct task_atoms *r)
1227 {
1228         if (l->nb_atoms < r->nb_atoms)
1229                 return -1;
1230         if (l->nb_atoms > r->nb_atoms)
1231                 return 1;
1232
1233         return 0;
1234 }
1235
1236 static struct sort_dimension switch_sort_dimension = {
1237         .name   = "switch",
1238         .cmp    = switch_cmp,
1239 };
1240
1241 static int runtime_cmp(struct task_atoms *l, struct task_atoms *r)
1242 {
1243         if (l->total_runtime < r->total_runtime)
1244                 return -1;
1245         if (l->total_runtime > r->total_runtime)
1246                 return 1;
1247
1248         return 0;
1249 }
1250
1251 static struct sort_dimension runtime_sort_dimension = {
1252         .name   = "runtime",
1253         .cmp    = runtime_cmp,
1254 };
1255
1256 static struct sort_dimension *available_sorts[] = {
1257         &pid_sort_dimension,
1258         &avg_sort_dimension,
1259         &max_sort_dimension,
1260         &switch_sort_dimension,
1261         &runtime_sort_dimension,
1262 };
1263
1264 #define NB_AVAILABLE_SORTS      (int)(sizeof(available_sorts) / sizeof(struct sort_dimension *))
1265
1266 static LIST_HEAD(sort_list);
1267
1268 static int sort_dimension__add(char *tok, struct list_head *list)
1269 {
1270         int i;
1271
1272         for (i = 0; i < NB_AVAILABLE_SORTS; i++) {
1273                 if (!strcmp(available_sorts[i]->name, tok)) {
1274                         list_add_tail(&available_sorts[i]->list, list);
1275
1276                         return 0;
1277                 }
1278         }
1279
1280         return -1;
1281 }
1282
1283 static void setup_sorting(void);
1284
1285 static void sort_lat(void)
1286 {
1287         struct rb_node *node;
1288
1289         for (;;) {
1290                 struct task_atoms *data;
1291                 node = rb_first(&lat_snapshot_root);
1292                 if (!node)
1293                         break;
1294
1295                 rb_erase(node, &lat_snapshot_root);
1296                 data = rb_entry(node, struct task_atoms, node);
1297                 __thread_latency_insert(&sorted_lat_snapshot_root, data, &sort_list);
1298         }
1299 }
1300
1301 static void __cmd_lat(void)
1302 {
1303         struct rb_node *next;
1304
1305         setup_pager();
1306         read_events();
1307         sort_lat();
1308
1309         printf("-----------------------------------------------------------------------------------\n");
1310         printf(" Task              |  Runtime ms | Switches | Average delay ms | Maximum delay ms |\n");
1311         printf("-----------------------------------------------------------------------------------\n");
1312
1313         next = rb_first(&sorted_lat_snapshot_root);
1314
1315         while (next) {
1316                 struct task_atoms *atom_list;
1317
1318                 atom_list = rb_entry(next, struct task_atoms, node);
1319                 output_lat_thread(atom_list);
1320                 next = rb_next(next);
1321         }
1322
1323         printf("-----------------------------------------------------------------------------------\n");
1324         printf(" TOTAL:            |%9.3f ms |%9Ld |\n",
1325                 (double)all_runtime/1e6, all_count);
1326         printf("---------------------------------------------\n");
1327 }
1328
1329 static struct trace_sched_handler *trace_handler;
1330
1331 static void
1332 process_sched_wakeup_event(struct raw_event_sample *raw,
1333                            struct event *event,
1334                            int cpu __used,
1335                            u64 timestamp __used,
1336                            struct thread *thread __used)
1337 {
1338         struct trace_wakeup_event wakeup_event;
1339
1340         FILL_COMMON_FIELDS(wakeup_event, event, raw->data);
1341
1342         FILL_ARRAY(wakeup_event, comm, event, raw->data);
1343         FILL_FIELD(wakeup_event, pid, event, raw->data);
1344         FILL_FIELD(wakeup_event, prio, event, raw->data);
1345         FILL_FIELD(wakeup_event, success, event, raw->data);
1346         FILL_FIELD(wakeup_event, cpu, event, raw->data);
1347
1348         trace_handler->wakeup_event(&wakeup_event, event, cpu, timestamp, thread);
1349 }
1350
1351 static void
1352 process_sched_switch_event(struct raw_event_sample *raw,
1353                            struct event *event,
1354                            int cpu __used,
1355                            u64 timestamp __used,
1356                            struct thread *thread __used)
1357 {
1358         struct trace_switch_event switch_event;
1359
1360         FILL_COMMON_FIELDS(switch_event, event, raw->data);
1361
1362         FILL_ARRAY(switch_event, prev_comm, event, raw->data);
1363         FILL_FIELD(switch_event, prev_pid, event, raw->data);
1364         FILL_FIELD(switch_event, prev_prio, event, raw->data);
1365         FILL_FIELD(switch_event, prev_state, event, raw->data);
1366         FILL_ARRAY(switch_event, next_comm, event, raw->data);
1367         FILL_FIELD(switch_event, next_pid, event, raw->data);
1368         FILL_FIELD(switch_event, next_prio, event, raw->data);
1369
1370         trace_handler->switch_event(&switch_event, event, cpu, timestamp, thread);
1371 }
1372
1373 static void
1374 process_sched_fork_event(struct raw_event_sample *raw,
1375                          struct event *event,
1376                          int cpu __used,
1377                          u64 timestamp __used,
1378                          struct thread *thread __used)
1379 {
1380         struct trace_fork_event fork_event;
1381
1382         FILL_COMMON_FIELDS(fork_event, event, raw->data);
1383
1384         FILL_ARRAY(fork_event, parent_comm, event, raw->data);
1385         FILL_FIELD(fork_event, parent_pid, event, raw->data);
1386         FILL_ARRAY(fork_event, child_comm, event, raw->data);
1387         FILL_FIELD(fork_event, child_pid, event, raw->data);
1388
1389         trace_handler->fork_event(&fork_event, event, cpu, timestamp, thread);
1390 }
1391
1392 static void
1393 process_sched_exit_event(struct event *event,
1394                          int cpu __used,
1395                          u64 timestamp __used,
1396                          struct thread *thread __used)
1397 {
1398         if (verbose)
1399                 printf("sched_exit event %p\n", event);
1400 }
1401
1402 static void
1403 process_raw_event(event_t *raw_event __used, void *more_data,
1404                   int cpu, u64 timestamp, struct thread *thread)
1405 {
1406         struct raw_event_sample *raw = more_data;
1407         struct event *event;
1408         int type;
1409
1410         type = trace_parse_common_type(raw->data);
1411         event = trace_find_event(type);
1412
1413         if (!strcmp(event->name, "sched_switch"))
1414                 process_sched_switch_event(raw, event, cpu, timestamp, thread);
1415         if (!strcmp(event->name, "sched_wakeup"))
1416                 process_sched_wakeup_event(raw, event, cpu, timestamp, thread);
1417         if (!strcmp(event->name, "sched_wakeup_new"))
1418                 process_sched_wakeup_event(raw, event, cpu, timestamp, thread);
1419         if (!strcmp(event->name, "sched_process_fork"))
1420                 process_sched_fork_event(raw, event, cpu, timestamp, thread);
1421         if (!strcmp(event->name, "sched_process_exit"))
1422                 process_sched_exit_event(event, cpu, timestamp, thread);
1423 }
1424
1425 static int
1426 process_sample_event(event_t *event, unsigned long offset, unsigned long head)
1427 {
1428         char level;
1429         int show = 0;
1430         struct dso *dso = NULL;
1431         struct thread *thread;
1432         u64 ip = event->ip.ip;
1433         u64 timestamp = -1;
1434         u32 cpu = -1;
1435         u64 period = 1;
1436         void *more_data = event->ip.__more_data;
1437         int cpumode;
1438
1439         thread = threads__findnew(event->ip.pid, &threads, &last_match);
1440
1441         if (sample_type & PERF_SAMPLE_TIME) {
1442                 timestamp = *(u64 *)more_data;
1443                 more_data += sizeof(u64);
1444         }
1445
1446         if (sample_type & PERF_SAMPLE_CPU) {
1447                 cpu = *(u32 *)more_data;
1448                 more_data += sizeof(u32);
1449                 more_data += sizeof(u32); /* reserved */
1450         }
1451
1452         if (sample_type & PERF_SAMPLE_PERIOD) {
1453                 period = *(u64 *)more_data;
1454                 more_data += sizeof(u64);
1455         }
1456
1457         dump_printf("%p [%p]: PERF_EVENT_SAMPLE (IP, %d): %d/%d: %p period: %Ld\n",
1458                 (void *)(offset + head),
1459                 (void *)(long)(event->header.size),
1460                 event->header.misc,
1461                 event->ip.pid, event->ip.tid,
1462                 (void *)(long)ip,
1463                 (long long)period);
1464
1465         dump_printf(" ... thread: %s:%d\n", thread->comm, thread->pid);
1466
1467         if (thread == NULL) {
1468                 eprintf("problem processing %d event, skipping it.\n",
1469                         event->header.type);
1470                 return -1;
1471         }
1472
1473         cpumode = event->header.misc & PERF_EVENT_MISC_CPUMODE_MASK;
1474
1475         if (cpumode == PERF_EVENT_MISC_KERNEL) {
1476                 show = SHOW_KERNEL;
1477                 level = 'k';
1478
1479                 dso = kernel_dso;
1480
1481                 dump_printf(" ...... dso: %s\n", dso->name);
1482
1483         } else if (cpumode == PERF_EVENT_MISC_USER) {
1484
1485                 show = SHOW_USER;
1486                 level = '.';
1487
1488         } else {
1489                 show = SHOW_HV;
1490                 level = 'H';
1491
1492                 dso = hypervisor_dso;
1493
1494                 dump_printf(" ...... dso: [hypervisor]\n");
1495         }
1496
1497         if (sample_type & PERF_SAMPLE_RAW)
1498                 process_raw_event(event, more_data, cpu, timestamp, thread);
1499
1500         return 0;
1501 }
1502
1503 static int
1504 process_event(event_t *event, unsigned long offset, unsigned long head)
1505 {
1506         trace_event(event);
1507
1508         switch (event->header.type) {
1509         case PERF_EVENT_MMAP ... PERF_EVENT_LOST:
1510                 return 0;
1511
1512         case PERF_EVENT_COMM:
1513                 return process_comm_event(event, offset, head);
1514
1515         case PERF_EVENT_EXIT ... PERF_EVENT_READ:
1516                 return 0;
1517
1518         case PERF_EVENT_SAMPLE:
1519                 return process_sample_event(event, offset, head);
1520
1521         case PERF_EVENT_MAX:
1522         default:
1523                 return -1;
1524         }
1525
1526         return 0;
1527 }
1528
1529 static int read_events(void)
1530 {
1531         int ret, rc = EXIT_FAILURE;
1532         unsigned long offset = 0;
1533         unsigned long head = 0;
1534         struct stat perf_stat;
1535         event_t *event;
1536         uint32_t size;
1537         char *buf;
1538
1539         trace_report();
1540         register_idle_thread(&threads, &last_match);
1541
1542         input = open(input_name, O_RDONLY);
1543         if (input < 0) {
1544                 perror("failed to open file");
1545                 exit(-1);
1546         }
1547
1548         ret = fstat(input, &perf_stat);
1549         if (ret < 0) {
1550                 perror("failed to stat file");
1551                 exit(-1);
1552         }
1553
1554         if (!perf_stat.st_size) {
1555                 fprintf(stderr, "zero-sized file, nothing to do!\n");
1556                 exit(0);
1557         }
1558         header = perf_header__read(input);
1559         head = header->data_offset;
1560         sample_type = perf_header__sample_type(header);
1561
1562         if (!(sample_type & PERF_SAMPLE_RAW))
1563                 die("No trace sample to read. Did you call perf record "
1564                     "without -R?");
1565
1566         if (load_kernel() < 0) {
1567                 perror("failed to load kernel symbols");
1568                 return EXIT_FAILURE;
1569         }
1570
1571 remap:
1572         buf = (char *)mmap(NULL, page_size * mmap_window, PROT_READ,
1573                            MAP_SHARED, input, offset);
1574         if (buf == MAP_FAILED) {
1575                 perror("failed to mmap file");
1576                 exit(-1);
1577         }
1578
1579 more:
1580         event = (event_t *)(buf + head);
1581
1582         size = event->header.size;
1583         if (!size)
1584                 size = 8;
1585
1586         if (head + event->header.size >= page_size * mmap_window) {
1587                 unsigned long shift = page_size * (head / page_size);
1588                 int res;
1589
1590                 res = munmap(buf, page_size * mmap_window);
1591                 assert(res == 0);
1592
1593                 offset += shift;
1594                 head -= shift;
1595                 goto remap;
1596         }
1597
1598         size = event->header.size;
1599
1600
1601         if (!size || process_event(event, offset, head) < 0) {
1602
1603                 /*
1604                  * assume we lost track of the stream, check alignment, and
1605                  * increment a single u64 in the hope to catch on again 'soon'.
1606                  */
1607
1608                 if (unlikely(head & 7))
1609                         head &= ~7ULL;
1610
1611                 size = 8;
1612         }
1613
1614         head += size;
1615
1616         if (offset + head < (unsigned long)perf_stat.st_size)
1617                 goto more;
1618
1619         rc = EXIT_SUCCESS;
1620         close(input);
1621
1622         return rc;
1623 }
1624
1625 static const char * const sched_usage[] = {
1626         "perf sched [<options>] <command>",
1627         NULL
1628 };
1629
1630 static const struct option options[] = {
1631         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1632                     "dump raw trace in ASCII"),
1633         OPT_BOOLEAN('r', "replay", &replay_mode,
1634                     "replay sched behaviour from traces"),
1635         OPT_BOOLEAN('l', "latency", &lat_mode,
1636                     "measure various latencies"),
1637         OPT_STRING('s', "sort", &sort_order, "key[,key2...]",
1638                    "sort by key(s): runtime, switch, avg, max"),
1639         OPT_BOOLEAN('v', "verbose", &verbose,
1640                     "be more verbose (show symbol address, etc)"),
1641         OPT_END()
1642 };
1643
1644 static void setup_sorting(void)
1645 {
1646         char *tmp, *tok, *str = strdup(sort_order);
1647
1648         for (tok = strtok_r(str, ", ", &tmp);
1649                         tok; tok = strtok_r(NULL, ", ", &tmp)) {
1650                 if (sort_dimension__add(tok, &sort_list) < 0) {
1651                         error("Unknown --sort key: `%s'", tok);
1652                         usage_with_options(sched_usage, options);
1653                 }
1654         }
1655
1656         free(str);
1657
1658         sort_dimension__add((char *)"pid", &cmp_pid);
1659 }
1660
1661 int cmd_sched(int argc, const char **argv, const char *prefix __used)
1662 {
1663         symbol__init();
1664         page_size = getpagesize();
1665
1666         argc = parse_options(argc, argv, options, sched_usage, 0);
1667         if (argc) {
1668                 /*
1669                  * Special case: if there's an argument left then assume tha
1670                  * it's a symbol filter:
1671                  */
1672                 if (argc > 1)
1673                         usage_with_options(sched_usage, options);
1674         }
1675
1676         if (replay_mode)
1677                 trace_handler = &replay_ops;
1678         else if (lat_mode)
1679                 trace_handler = &lat_ops;
1680         else
1681                 usage_with_options(sched_usage, options);
1682
1683         setup_sorting();
1684
1685         if (replay_mode)
1686                 __cmd_replay();
1687         else if (lat_mode)
1688                 __cmd_lat();
1689
1690         return 0;
1691 }