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