perf sched: Output runtime and context switch totals
[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
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 void __cmd_replay(void)
624 {
625         long nr_iterations = 10, i;
626
627         calibrate_run_measurement_overhead();
628         calibrate_sleep_measurement_overhead();
629
630         test_calibrations();
631
632         read_events();
633
634         printf("nr_run_events:        %ld\n", nr_run_events);
635         printf("nr_sleep_events:      %ld\n", nr_sleep_events);
636         printf("nr_wakeup_events:     %ld\n", nr_wakeup_events);
637
638         if (targetless_wakeups)
639                 printf("target-less wakeups:  %ld\n", targetless_wakeups);
640         if (multitarget_wakeups)
641                 printf("multi-target wakeups: %ld\n", multitarget_wakeups);
642         if (nr_run_events_optimized)
643                 printf("run events optimized: %ld\n",
644                         nr_run_events_optimized);
645
646         print_task_traces();
647         add_cross_task_wakeups();
648
649         create_tasks();
650         printf("------------------------------------------------------------\n");
651         for (i = 0; i < nr_iterations; i++)
652                 run_one_test();
653 }
654
655 static int
656 process_comm_event(event_t *event, unsigned long offset, unsigned long head)
657 {
658         struct thread *thread;
659
660         thread = threads__findnew(event->comm.pid, &threads, &last_match);
661
662         dump_printf("%p [%p]: PERF_EVENT_COMM: %s:%d\n",
663                 (void *)(offset + head),
664                 (void *)(long)(event->header.size),
665                 event->comm.comm, event->comm.pid);
666
667         if (thread == NULL ||
668             thread__set_comm(thread, event->comm.comm)) {
669                 dump_printf("problem processing PERF_EVENT_COMM, skipping event.\n");
670                 return -1;
671         }
672         total_comm++;
673
674         return 0;
675 }
676
677
678 struct raw_event_sample {
679         u32 size;
680         char data[0];
681 };
682
683 #define FILL_FIELD(ptr, field, event, data)     \
684         ptr.field = (typeof(ptr.field)) raw_field_value(event, #field, data)
685
686 #define FILL_ARRAY(ptr, array, event, data)                     \
687 do {                                                            \
688         void *__array = raw_field_ptr(event, #array, data);     \
689         memcpy(ptr.array, __array, sizeof(ptr.array));  \
690 } while(0)
691
692 #define FILL_COMMON_FIELDS(ptr, event, data)                    \
693 do {                                                            \
694         FILL_FIELD(ptr, common_type, event, data);              \
695         FILL_FIELD(ptr, common_flags, event, data);             \
696         FILL_FIELD(ptr, common_preempt_count, event, data);     \
697         FILL_FIELD(ptr, common_pid, event, data);               \
698         FILL_FIELD(ptr, common_tgid, event, data);              \
699 } while (0)
700
701
702
703 struct trace_switch_event {
704         u32 size;
705
706         u16 common_type;
707         u8 common_flags;
708         u8 common_preempt_count;
709         u32 common_pid;
710         u32 common_tgid;
711
712         char prev_comm[16];
713         u32 prev_pid;
714         u32 prev_prio;
715         u64 prev_state;
716         char next_comm[16];
717         u32 next_pid;
718         u32 next_prio;
719 };
720
721
722 struct trace_wakeup_event {
723         u32 size;
724
725         u16 common_type;
726         u8 common_flags;
727         u8 common_preempt_count;
728         u32 common_pid;
729         u32 common_tgid;
730
731         char comm[16];
732         u32 pid;
733
734         u32 prio;
735         u32 success;
736         u32 cpu;
737 };
738
739 struct trace_fork_event {
740         u32 size;
741
742         u16 common_type;
743         u8 common_flags;
744         u8 common_preempt_count;
745         u32 common_pid;
746         u32 common_tgid;
747
748         char parent_comm[16];
749         u32 parent_pid;
750         char child_comm[16];
751         u32 child_pid;
752 };
753
754 struct trace_sched_handler {
755         void (*switch_event)(struct trace_switch_event *,
756                              struct event *,
757                              int cpu,
758                              u64 timestamp,
759                              struct thread *thread);
760
761         void (*wakeup_event)(struct trace_wakeup_event *,
762                              struct event *,
763                              int cpu,
764                              u64 timestamp,
765                              struct thread *thread);
766
767         void (*fork_event)(struct trace_fork_event *,
768                            struct event *,
769                            int cpu,
770                            u64 timestamp,
771                            struct thread *thread);
772 };
773
774
775 static void
776 replay_wakeup_event(struct trace_wakeup_event *wakeup_event,
777                     struct event *event,
778                     int cpu __used,
779                     u64 timestamp __used,
780                     struct thread *thread __used)
781 {
782         struct task_desc *waker, *wakee;
783
784         if (verbose) {
785                 printf("sched_wakeup event %p\n", event);
786
787                 printf(" ... pid %d woke up %s/%d\n",
788                         wakeup_event->common_pid,
789                         wakeup_event->comm,
790                         wakeup_event->pid);
791         }
792
793         waker = register_pid(wakeup_event->common_pid, "<unknown>");
794         wakee = register_pid(wakeup_event->pid, wakeup_event->comm);
795
796         add_sched_event_wakeup(waker, timestamp, wakee);
797 }
798
799 static unsigned long cpu_last_switched[MAX_CPUS];
800
801 static void
802 replay_switch_event(struct trace_switch_event *switch_event,
803                     struct event *event,
804                     int cpu,
805                     u64 timestamp,
806                     struct thread *thread __used)
807 {
808         struct task_desc *prev, *next;
809         u64 timestamp0;
810         s64 delta;
811
812         if (verbose)
813                 printf("sched_switch event %p\n", event);
814
815         if (cpu >= MAX_CPUS || cpu < 0)
816                 return;
817
818         timestamp0 = cpu_last_switched[cpu];
819         if (timestamp0)
820                 delta = timestamp - timestamp0;
821         else
822                 delta = 0;
823
824         if (delta < 0)
825                 die("hm, delta: %Ld < 0 ?\n", delta);
826
827         if (verbose) {
828                 printf(" ... switch from %s/%d to %s/%d [ran %Ld nsecs]\n",
829                         switch_event->prev_comm, switch_event->prev_pid,
830                         switch_event->next_comm, switch_event->next_pid,
831                         delta);
832         }
833
834         prev = register_pid(switch_event->prev_pid, switch_event->prev_comm);
835         next = register_pid(switch_event->next_pid, switch_event->next_comm);
836
837         cpu_last_switched[cpu] = timestamp;
838
839         add_sched_event_run(prev, timestamp, delta);
840         add_sched_event_sleep(prev, timestamp, switch_event->prev_state);
841 }
842
843
844 static void
845 replay_fork_event(struct trace_fork_event *fork_event,
846                   struct event *event,
847                   int cpu __used,
848                   u64 timestamp __used,
849                   struct thread *thread __used)
850 {
851         if (verbose) {
852                 printf("sched_fork event %p\n", event);
853                 printf("... parent: %s/%d\n", fork_event->parent_comm, fork_event->parent_pid);
854                 printf("...  child: %s/%d\n", fork_event->child_comm, fork_event->child_pid);
855         }
856         register_pid(fork_event->parent_pid, fork_event->parent_comm);
857         register_pid(fork_event->child_pid, fork_event->child_comm);
858 }
859
860 static struct trace_sched_handler replay_ops  = {
861         .wakeup_event           = replay_wakeup_event,
862         .switch_event           = replay_switch_event,
863         .fork_event             = replay_fork_event,
864 };
865
866 #define TASK_STATE_TO_CHAR_STR "RSDTtZX"
867
868 enum thread_state {
869         THREAD_SLEEPING,
870         THREAD_WAKED_UP,
871         THREAD_SCHED_IN,
872         THREAD_IGNORE
873 };
874
875 struct lat_snapshot {
876         struct list_head        list;
877         enum thread_state       state;
878         u64                     wake_up_time;
879         u64                     sched_in_time;
880         u64                     runtime;
881 };
882
883 struct thread_latency {
884         struct list_head        snapshot_list;
885         struct thread           *thread;
886         struct rb_node          node;
887 };
888
889 static struct rb_root lat_snapshot_root;
890
891 static struct thread_latency *
892 thread_latency_search(struct rb_root *root, struct thread *thread)
893 {
894         struct rb_node *node = root->rb_node;
895
896         while (node) {
897                 struct thread_latency *lat;
898
899                 lat = container_of(node, struct thread_latency, node);
900                 if (thread->pid < lat->thread->pid)
901                         node = node->rb_left;
902                 else if (thread->pid > lat->thread->pid)
903                         node = node->rb_right;
904                 else {
905                         return lat;
906                 }
907         }
908         return NULL;
909 }
910
911 static void
912 __thread_latency_insert(struct rb_root *root, struct thread_latency *data)
913 {
914         struct rb_node **new = &(root->rb_node), *parent = NULL;
915
916         while (*new) {
917                 struct thread_latency *this;
918
919                 this = container_of(*new, struct thread_latency, node);
920                 parent = *new;
921                 if (data->thread->pid < this->thread->pid)
922                         new = &((*new)->rb_left);
923                 else if (data->thread->pid > this->thread->pid)
924                         new = &((*new)->rb_right);
925                 else
926                         die("Double thread insertion\n");
927         }
928
929         rb_link_node(&data->node, parent, new);
930         rb_insert_color(&data->node, root);
931 }
932
933 static void thread_latency_insert(struct thread *thread)
934 {
935         struct thread_latency *lat;
936         lat = calloc(sizeof(*lat), 1);
937         if (!lat)
938                 die("No memory");
939
940         lat->thread = thread;
941         INIT_LIST_HEAD(&lat->snapshot_list);
942         __thread_latency_insert(&lat_snapshot_root, lat);
943 }
944
945 static void
946 latency_fork_event(struct trace_fork_event *fork_event __used,
947                    struct event *event __used,
948                    int cpu __used,
949                    u64 timestamp __used,
950                    struct thread *thread __used)
951 {
952         /* should insert the newcomer */
953 }
954
955 __used
956 static char sched_out_state(struct trace_switch_event *switch_event)
957 {
958         const char *str = TASK_STATE_TO_CHAR_STR;
959
960         return str[switch_event->prev_state];
961 }
962
963 static void
964 lat_sched_out(struct thread_latency *lat,
965              struct trace_switch_event *switch_event __used, u64 delta)
966 {
967         struct lat_snapshot *snapshot;
968
969         snapshot = calloc(sizeof(*snapshot), 1);
970         if (!snapshot)
971                 die("Non memory");
972
973         snapshot->runtime = delta;
974         list_add_tail(&snapshot->list, &lat->snapshot_list);
975 }
976
977 static void
978 lat_sched_in(struct thread_latency *lat, u64 timestamp)
979 {
980         struct lat_snapshot *snapshot;
981
982         if (list_empty(&lat->snapshot_list))
983                 return;
984
985         snapshot = list_entry(lat->snapshot_list.prev, struct lat_snapshot,
986                               list);
987
988         if (snapshot->state != THREAD_WAKED_UP)
989                 return;
990
991         if (timestamp < snapshot->wake_up_time) {
992                 snapshot->state = THREAD_IGNORE;
993                 return;
994         }
995
996         snapshot->state = THREAD_SCHED_IN;
997         snapshot->sched_in_time = timestamp;
998 }
999
1000 static void
1001 latency_switch_event(struct trace_switch_event *switch_event,
1002                      struct event *event __used,
1003                      int cpu,
1004                      u64 timestamp,
1005                      struct thread *thread __used)
1006 {
1007         struct thread_latency *out_lat, *in_lat;
1008         struct thread *sched_out, *sched_in;
1009         u64 timestamp0;
1010         s64 delta;
1011
1012         if (cpu >= MAX_CPUS || cpu < 0)
1013                 return;
1014
1015         timestamp0 = cpu_last_switched[cpu];
1016         cpu_last_switched[cpu] = timestamp;
1017         if (timestamp0)
1018                 delta = timestamp - timestamp0;
1019         else
1020                 delta = 0;
1021
1022         if (delta < 0)
1023                 die("hm, delta: %Ld < 0 ?\n", delta);
1024
1025
1026         sched_out = threads__findnew(switch_event->prev_pid, &threads, &last_match);
1027         sched_in = threads__findnew(switch_event->next_pid, &threads, &last_match);
1028
1029         in_lat = thread_latency_search(&lat_snapshot_root, sched_in);
1030         if (!in_lat) {
1031                 thread_latency_insert(sched_in);
1032                 in_lat = thread_latency_search(&lat_snapshot_root, sched_in);
1033                 if (!in_lat)
1034                         die("Internal latency tree error");
1035         }
1036
1037         out_lat = thread_latency_search(&lat_snapshot_root, sched_out);
1038         if (!out_lat) {
1039                 thread_latency_insert(sched_out);
1040                 out_lat = thread_latency_search(&lat_snapshot_root, sched_out);
1041                 if (!out_lat)
1042                         die("Internal latency tree error");
1043         }
1044
1045         lat_sched_in(in_lat, timestamp);
1046         lat_sched_out(out_lat, switch_event, delta);
1047 }
1048
1049 static void
1050 latency_wakeup_event(struct trace_wakeup_event *wakeup_event,
1051                      struct event *event __used,
1052                      int cpu __used,
1053                      u64 timestamp,
1054                      struct thread *thread __used)
1055 {
1056         struct thread_latency *lat;
1057         struct lat_snapshot *snapshot;
1058         struct thread *wakee;
1059
1060         /* Note for later, it may be interesting to observe the failing cases */
1061         if (!wakeup_event->success)
1062                 return;
1063
1064         wakee = threads__findnew(wakeup_event->pid, &threads, &last_match);
1065         lat = thread_latency_search(&lat_snapshot_root, wakee);
1066         if (!lat) {
1067                 thread_latency_insert(wakee);
1068                 return;
1069         }
1070
1071         if (list_empty(&lat->snapshot_list))
1072                 return;
1073
1074         snapshot = list_entry(lat->snapshot_list.prev, struct lat_snapshot,
1075                               list);
1076
1077         if (snapshot->state != THREAD_SLEEPING)
1078                 return;
1079
1080         snapshot->state = THREAD_WAKED_UP;
1081         snapshot->wake_up_time = timestamp;
1082 }
1083
1084 static struct trace_sched_handler lat_ops  = {
1085         .wakeup_event           = latency_wakeup_event,
1086         .switch_event           = latency_switch_event,
1087         .fork_event             = latency_fork_event,
1088 };
1089
1090 static u64 all_runtime;
1091 static u64 all_count;
1092
1093 static void output_lat_thread(struct thread_latency *lat)
1094 {
1095         struct lat_snapshot *shot;
1096         int count = 0;
1097         int i;
1098         int ret;
1099         u64 max = 0, avg;
1100         u64 total = 0, delta;
1101         u64 total_runtime = 0;
1102
1103         list_for_each_entry(shot, &lat->snapshot_list, list) {
1104                 total_runtime += shot->runtime;
1105
1106                 if (shot->state != THREAD_SCHED_IN)
1107                         continue;
1108
1109                 count++;
1110
1111                 delta = shot->sched_in_time - shot->wake_up_time;
1112                 if (delta > max)
1113                         max = delta;
1114                 total += delta;
1115         }
1116
1117         all_runtime += total_runtime;
1118         all_count += count;
1119
1120         if (!count)
1121                 return;
1122
1123         ret = printf(" %s ", lat->thread->comm);
1124
1125         for (i = 0; i < 19 - ret; i++)
1126                 printf(" ");
1127
1128         avg = total / count;
1129
1130         printf("|%9.3f ms |%9d | avg:%9.3f ms | max:%9.3f ms |\n",
1131                 (double)total_runtime/1e9, count, (double)avg/1e9, (double)max/1e9);
1132 }
1133
1134 static void __cmd_lat(void)
1135 {
1136         struct rb_node *next;
1137
1138         setup_pager();
1139         read_events();
1140
1141         printf("-----------------------------------------------------------------------------------\n");
1142         printf(" Task              |  Runtime ms | Switches | Average delay ms | Maximum delay ms |\n");
1143         printf("-----------------------------------------------------------------------------------\n");
1144
1145         next = rb_first(&lat_snapshot_root);
1146
1147         while (next) {
1148                 struct thread_latency *lat;
1149
1150                 lat = rb_entry(next, struct thread_latency, node);
1151                 output_lat_thread(lat);
1152                 next = rb_next(next);
1153         }
1154
1155         printf("-----------------------------------------------------------------------------------\n");
1156         printf(" TOTAL:            |%9.3f ms |%9Ld |\n",
1157                 (double)all_runtime/1e9, all_count);
1158         printf("---------------------------------------------\n");
1159 }
1160
1161 static struct trace_sched_handler *trace_handler;
1162
1163 static void
1164 process_sched_wakeup_event(struct raw_event_sample *raw,
1165                            struct event *event,
1166                            int cpu __used,
1167                            u64 timestamp __used,
1168                            struct thread *thread __used)
1169 {
1170         struct trace_wakeup_event wakeup_event;
1171
1172         FILL_COMMON_FIELDS(wakeup_event, event, raw->data);
1173
1174         FILL_ARRAY(wakeup_event, comm, event, raw->data);
1175         FILL_FIELD(wakeup_event, pid, event, raw->data);
1176         FILL_FIELD(wakeup_event, prio, event, raw->data);
1177         FILL_FIELD(wakeup_event, success, event, raw->data);
1178         FILL_FIELD(wakeup_event, cpu, event, raw->data);
1179
1180         trace_handler->wakeup_event(&wakeup_event, event, cpu, timestamp, thread);
1181 }
1182
1183 static void
1184 process_sched_switch_event(struct raw_event_sample *raw,
1185                            struct event *event,
1186                            int cpu __used,
1187                            u64 timestamp __used,
1188                            struct thread *thread __used)
1189 {
1190         struct trace_switch_event switch_event;
1191
1192         FILL_COMMON_FIELDS(switch_event, event, raw->data);
1193
1194         FILL_ARRAY(switch_event, prev_comm, event, raw->data);
1195         FILL_FIELD(switch_event, prev_pid, event, raw->data);
1196         FILL_FIELD(switch_event, prev_prio, event, raw->data);
1197         FILL_FIELD(switch_event, prev_state, event, raw->data);
1198         FILL_ARRAY(switch_event, next_comm, event, raw->data);
1199         FILL_FIELD(switch_event, next_pid, event, raw->data);
1200         FILL_FIELD(switch_event, next_prio, event, raw->data);
1201
1202         trace_handler->switch_event(&switch_event, event, cpu, timestamp, thread);
1203 }
1204
1205 static void
1206 process_sched_fork_event(struct raw_event_sample *raw,
1207                          struct event *event,
1208                          int cpu __used,
1209                          u64 timestamp __used,
1210                          struct thread *thread __used)
1211 {
1212         struct trace_fork_event fork_event;
1213
1214         FILL_COMMON_FIELDS(fork_event, event, raw->data);
1215
1216         FILL_ARRAY(fork_event, parent_comm, event, raw->data);
1217         FILL_FIELD(fork_event, parent_pid, event, raw->data);
1218         FILL_ARRAY(fork_event, child_comm, event, raw->data);
1219         FILL_FIELD(fork_event, child_pid, event, raw->data);
1220
1221         trace_handler->fork_event(&fork_event, event, cpu, timestamp, thread);
1222 }
1223
1224 static void
1225 process_sched_exit_event(struct event *event,
1226                          int cpu __used,
1227                          u64 timestamp __used,
1228                          struct thread *thread __used)
1229 {
1230         if (verbose)
1231                 printf("sched_exit event %p\n", event);
1232 }
1233
1234 static void
1235 process_raw_event(event_t *raw_event __used, void *more_data,
1236                   int cpu, u64 timestamp, struct thread *thread)
1237 {
1238         struct raw_event_sample *raw = more_data;
1239         struct event *event;
1240         int type;
1241
1242         type = trace_parse_common_type(raw->data);
1243         event = trace_find_event(type);
1244
1245         if (!strcmp(event->name, "sched_switch"))
1246                 process_sched_switch_event(raw, event, cpu, timestamp, thread);
1247         if (!strcmp(event->name, "sched_wakeup"))
1248                 process_sched_wakeup_event(raw, event, cpu, timestamp, thread);
1249         if (!strcmp(event->name, "sched_wakeup_new"))
1250                 process_sched_wakeup_event(raw, event, cpu, timestamp, thread);
1251         if (!strcmp(event->name, "sched_process_fork"))
1252                 process_sched_fork_event(raw, event, cpu, timestamp, thread);
1253         if (!strcmp(event->name, "sched_process_exit"))
1254                 process_sched_exit_event(event, cpu, timestamp, thread);
1255 }
1256
1257 static int
1258 process_sample_event(event_t *event, unsigned long offset, unsigned long head)
1259 {
1260         char level;
1261         int show = 0;
1262         struct dso *dso = NULL;
1263         struct thread *thread;
1264         u64 ip = event->ip.ip;
1265         u64 timestamp = -1;
1266         u32 cpu = -1;
1267         u64 period = 1;
1268         void *more_data = event->ip.__more_data;
1269         int cpumode;
1270
1271         thread = threads__findnew(event->ip.pid, &threads, &last_match);
1272
1273         if (sample_type & PERF_SAMPLE_TIME) {
1274                 timestamp = *(u64 *)more_data;
1275                 more_data += sizeof(u64);
1276         }
1277
1278         if (sample_type & PERF_SAMPLE_CPU) {
1279                 cpu = *(u32 *)more_data;
1280                 more_data += sizeof(u32);
1281                 more_data += sizeof(u32); /* reserved */
1282         }
1283
1284         if (sample_type & PERF_SAMPLE_PERIOD) {
1285                 period = *(u64 *)more_data;
1286                 more_data += sizeof(u64);
1287         }
1288
1289         dump_printf("%p [%p]: PERF_EVENT_SAMPLE (IP, %d): %d/%d: %p period: %Ld\n",
1290                 (void *)(offset + head),
1291                 (void *)(long)(event->header.size),
1292                 event->header.misc,
1293                 event->ip.pid, event->ip.tid,
1294                 (void *)(long)ip,
1295                 (long long)period);
1296
1297         dump_printf(" ... thread: %s:%d\n", thread->comm, thread->pid);
1298
1299         if (thread == NULL) {
1300                 eprintf("problem processing %d event, skipping it.\n",
1301                         event->header.type);
1302                 return -1;
1303         }
1304
1305         cpumode = event->header.misc & PERF_EVENT_MISC_CPUMODE_MASK;
1306
1307         if (cpumode == PERF_EVENT_MISC_KERNEL) {
1308                 show = SHOW_KERNEL;
1309                 level = 'k';
1310
1311                 dso = kernel_dso;
1312
1313                 dump_printf(" ...... dso: %s\n", dso->name);
1314
1315         } else if (cpumode == PERF_EVENT_MISC_USER) {
1316
1317                 show = SHOW_USER;
1318                 level = '.';
1319
1320         } else {
1321                 show = SHOW_HV;
1322                 level = 'H';
1323
1324                 dso = hypervisor_dso;
1325
1326                 dump_printf(" ...... dso: [hypervisor]\n");
1327         }
1328
1329         if (sample_type & PERF_SAMPLE_RAW)
1330                 process_raw_event(event, more_data, cpu, timestamp, thread);
1331
1332         return 0;
1333 }
1334
1335 static int
1336 process_event(event_t *event, unsigned long offset, unsigned long head)
1337 {
1338         trace_event(event);
1339
1340         switch (event->header.type) {
1341         case PERF_EVENT_MMAP ... PERF_EVENT_LOST:
1342                 return 0;
1343
1344         case PERF_EVENT_COMM:
1345                 return process_comm_event(event, offset, head);
1346
1347         case PERF_EVENT_EXIT ... PERF_EVENT_READ:
1348                 return 0;
1349
1350         case PERF_EVENT_SAMPLE:
1351                 return process_sample_event(event, offset, head);
1352
1353         case PERF_EVENT_MAX:
1354         default:
1355                 return -1;
1356         }
1357
1358         return 0;
1359 }
1360
1361 static int read_events(void)
1362 {
1363         int ret, rc = EXIT_FAILURE;
1364         unsigned long offset = 0;
1365         unsigned long head = 0;
1366         struct stat perf_stat;
1367         event_t *event;
1368         uint32_t size;
1369         char *buf;
1370
1371         trace_report();
1372         register_idle_thread(&threads, &last_match);
1373
1374         input = open(input_name, O_RDONLY);
1375         if (input < 0) {
1376                 perror("failed to open file");
1377                 exit(-1);
1378         }
1379
1380         ret = fstat(input, &perf_stat);
1381         if (ret < 0) {
1382                 perror("failed to stat file");
1383                 exit(-1);
1384         }
1385
1386         if (!perf_stat.st_size) {
1387                 fprintf(stderr, "zero-sized file, nothing to do!\n");
1388                 exit(0);
1389         }
1390         header = perf_header__read(input);
1391         head = header->data_offset;
1392         sample_type = perf_header__sample_type(header);
1393
1394         if (!(sample_type & PERF_SAMPLE_RAW))
1395                 die("No trace sample to read. Did you call perf record "
1396                     "without -R?");
1397
1398         if (load_kernel() < 0) {
1399                 perror("failed to load kernel symbols");
1400                 return EXIT_FAILURE;
1401         }
1402
1403 remap:
1404         buf = (char *)mmap(NULL, page_size * mmap_window, PROT_READ,
1405                            MAP_SHARED, input, offset);
1406         if (buf == MAP_FAILED) {
1407                 perror("failed to mmap file");
1408                 exit(-1);
1409         }
1410
1411 more:
1412         event = (event_t *)(buf + head);
1413
1414         size = event->header.size;
1415         if (!size)
1416                 size = 8;
1417
1418         if (head + event->header.size >= page_size * mmap_window) {
1419                 unsigned long shift = page_size * (head / page_size);
1420                 int res;
1421
1422                 res = munmap(buf, page_size * mmap_window);
1423                 assert(res == 0);
1424
1425                 offset += shift;
1426                 head -= shift;
1427                 goto remap;
1428         }
1429
1430         size = event->header.size;
1431
1432
1433         if (!size || process_event(event, offset, head) < 0) {
1434
1435                 /*
1436                  * assume we lost track of the stream, check alignment, and
1437                  * increment a single u64 in the hope to catch on again 'soon'.
1438                  */
1439
1440                 if (unlikely(head & 7))
1441                         head &= ~7ULL;
1442
1443                 size = 8;
1444         }
1445
1446         head += size;
1447
1448         if (offset + head < (unsigned long)perf_stat.st_size)
1449                 goto more;
1450
1451         rc = EXIT_SUCCESS;
1452         close(input);
1453
1454         return rc;
1455 }
1456
1457 static const char * const sched_usage[] = {
1458         "perf sched [<options>] <command>",
1459         NULL
1460 };
1461
1462 static const struct option options[] = {
1463         OPT_BOOLEAN('D', "dump-raw-trace", &dump_trace,
1464                     "dump raw trace in ASCII"),
1465         OPT_BOOLEAN('r', "replay", &replay_mode,
1466                     "replay sched behaviour from traces"),
1467         OPT_BOOLEAN('l', "latency", &lat_mode,
1468                     "measure various latencies"),
1469         OPT_BOOLEAN('v', "verbose", &verbose,
1470                     "be more verbose (show symbol address, etc)"),
1471         OPT_END()
1472 };
1473
1474 int cmd_sched(int argc, const char **argv, const char *prefix __used)
1475 {
1476         symbol__init();
1477         page_size = getpagesize();
1478
1479         argc = parse_options(argc, argv, options, sched_usage, 0);
1480         if (argc) {
1481                 /*
1482                  * Special case: if there's an argument left then assume tha
1483                  * it's a symbol filter:
1484                  */
1485                 if (argc > 1)
1486                         usage_with_options(sched_usage, options);
1487         }
1488
1489         if (replay_mode)
1490                 trace_handler = &replay_ops;
1491         else if (lat_mode)
1492                 trace_handler = &lat_ops;
1493         else
1494                 usage_with_options(sched_usage, options);
1495
1496         if (replay_mode)
1497                 __cmd_replay();
1498         else if (lat_mode)
1499                 __cmd_lat();
1500
1501         return 0;
1502 }