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