perf session: Register the idle thread in perf_session__process_events
[pandora-kernel.git] / tools / perf / builtin-kmem.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 #include "util/session.h"
10
11 #include "util/parse-options.h"
12 #include "util/trace-event.h"
13
14 #include "util/debug.h"
15
16 #include <linux/rbtree.h>
17
18 struct alloc_stat;
19 typedef int (*sort_fn_t)(struct alloc_stat *, struct alloc_stat *);
20
21 static char const               *input_name = "perf.data";
22
23 static u64                      sample_type;
24
25 static int                      alloc_flag;
26 static int                      caller_flag;
27
28 static int                      alloc_lines = -1;
29 static int                      caller_lines = -1;
30
31 static bool                     raw_ip;
32
33 static char                     default_sort_order[] = "frag,hit,bytes";
34
35 static int                      *cpunode_map;
36 static int                      max_cpu_num;
37
38 struct alloc_stat {
39         u64     call_site;
40         u64     ptr;
41         u64     bytes_req;
42         u64     bytes_alloc;
43         u32     hit;
44         u32     pingpong;
45
46         short   alloc_cpu;
47
48         struct rb_node node;
49 };
50
51 static struct rb_root root_alloc_stat;
52 static struct rb_root root_alloc_sorted;
53 static struct rb_root root_caller_stat;
54 static struct rb_root root_caller_sorted;
55
56 static unsigned long total_requested, total_allocated;
57 static unsigned long nr_allocs, nr_cross_allocs;
58
59 #define PATH_SYS_NODE   "/sys/devices/system/node"
60
61 static void init_cpunode_map(void)
62 {
63         FILE *fp;
64         int i;
65
66         fp = fopen("/sys/devices/system/cpu/kernel_max", "r");
67         if (!fp) {
68                 max_cpu_num = 4096;
69                 return;
70         }
71
72         if (fscanf(fp, "%d", &max_cpu_num) < 1)
73                 die("Failed to read 'kernel_max' from sysfs");
74         max_cpu_num++;
75
76         cpunode_map = calloc(max_cpu_num, sizeof(int));
77         if (!cpunode_map)
78                 die("calloc");
79         for (i = 0; i < max_cpu_num; i++)
80                 cpunode_map[i] = -1;
81         fclose(fp);
82 }
83
84 static void setup_cpunode_map(void)
85 {
86         struct dirent *dent1, *dent2;
87         DIR *dir1, *dir2;
88         unsigned int cpu, mem;
89         char buf[PATH_MAX];
90
91         init_cpunode_map();
92
93         dir1 = opendir(PATH_SYS_NODE);
94         if (!dir1)
95                 return;
96
97         while (true) {
98                 dent1 = readdir(dir1);
99                 if (!dent1)
100                         break;
101
102                 if (sscanf(dent1->d_name, "node%u", &mem) < 1)
103                         continue;
104
105                 snprintf(buf, PATH_MAX, "%s/%s", PATH_SYS_NODE, dent1->d_name);
106                 dir2 = opendir(buf);
107                 if (!dir2)
108                         continue;
109                 while (true) {
110                         dent2 = readdir(dir2);
111                         if (!dent2)
112                                 break;
113                         if (sscanf(dent2->d_name, "cpu%u", &cpu) < 1)
114                                 continue;
115                         cpunode_map[cpu] = mem;
116                 }
117         }
118 }
119
120 static void insert_alloc_stat(unsigned long call_site, unsigned long ptr,
121                               int bytes_req, int bytes_alloc, int cpu)
122 {
123         struct rb_node **node = &root_alloc_stat.rb_node;
124         struct rb_node *parent = NULL;
125         struct alloc_stat *data = NULL;
126
127         while (*node) {
128                 parent = *node;
129                 data = rb_entry(*node, struct alloc_stat, node);
130
131                 if (ptr > data->ptr)
132                         node = &(*node)->rb_right;
133                 else if (ptr < data->ptr)
134                         node = &(*node)->rb_left;
135                 else
136                         break;
137         }
138
139         if (data && data->ptr == ptr) {
140                 data->hit++;
141                 data->bytes_req += bytes_req;
142                 data->bytes_alloc += bytes_req;
143         } else {
144                 data = malloc(sizeof(*data));
145                 if (!data)
146                         die("malloc");
147                 data->ptr = ptr;
148                 data->pingpong = 0;
149                 data->hit = 1;
150                 data->bytes_req = bytes_req;
151                 data->bytes_alloc = bytes_alloc;
152
153                 rb_link_node(&data->node, parent, node);
154                 rb_insert_color(&data->node, &root_alloc_stat);
155         }
156         data->call_site = call_site;
157         data->alloc_cpu = cpu;
158 }
159
160 static void insert_caller_stat(unsigned long call_site,
161                               int bytes_req, int bytes_alloc)
162 {
163         struct rb_node **node = &root_caller_stat.rb_node;
164         struct rb_node *parent = NULL;
165         struct alloc_stat *data = NULL;
166
167         while (*node) {
168                 parent = *node;
169                 data = rb_entry(*node, struct alloc_stat, node);
170
171                 if (call_site > data->call_site)
172                         node = &(*node)->rb_right;
173                 else if (call_site < data->call_site)
174                         node = &(*node)->rb_left;
175                 else
176                         break;
177         }
178
179         if (data && data->call_site == call_site) {
180                 data->hit++;
181                 data->bytes_req += bytes_req;
182                 data->bytes_alloc += bytes_req;
183         } else {
184                 data = malloc(sizeof(*data));
185                 if (!data)
186                         die("malloc");
187                 data->call_site = call_site;
188                 data->pingpong = 0;
189                 data->hit = 1;
190                 data->bytes_req = bytes_req;
191                 data->bytes_alloc = bytes_alloc;
192
193                 rb_link_node(&data->node, parent, node);
194                 rb_insert_color(&data->node, &root_caller_stat);
195         }
196 }
197
198 static void process_alloc_event(void *data,
199                                 struct event *event,
200                                 int cpu,
201                                 u64 timestamp __used,
202                                 struct thread *thread __used,
203                                 int node)
204 {
205         unsigned long call_site;
206         unsigned long ptr;
207         int bytes_req;
208         int bytes_alloc;
209         int node1, node2;
210
211         ptr = raw_field_value(event, "ptr", data);
212         call_site = raw_field_value(event, "call_site", data);
213         bytes_req = raw_field_value(event, "bytes_req", data);
214         bytes_alloc = raw_field_value(event, "bytes_alloc", data);
215
216         insert_alloc_stat(call_site, ptr, bytes_req, bytes_alloc, cpu);
217         insert_caller_stat(call_site, bytes_req, bytes_alloc);
218
219         total_requested += bytes_req;
220         total_allocated += bytes_alloc;
221
222         if (node) {
223                 node1 = cpunode_map[cpu];
224                 node2 = raw_field_value(event, "node", data);
225                 if (node1 != node2)
226                         nr_cross_allocs++;
227         }
228         nr_allocs++;
229 }
230
231 static int ptr_cmp(struct alloc_stat *, struct alloc_stat *);
232 static int callsite_cmp(struct alloc_stat *, struct alloc_stat *);
233
234 static struct alloc_stat *search_alloc_stat(unsigned long ptr,
235                                             unsigned long call_site,
236                                             struct rb_root *root,
237                                             sort_fn_t sort_fn)
238 {
239         struct rb_node *node = root->rb_node;
240         struct alloc_stat key = { .ptr = ptr, .call_site = call_site };
241
242         while (node) {
243                 struct alloc_stat *data;
244                 int cmp;
245
246                 data = rb_entry(node, struct alloc_stat, node);
247
248                 cmp = sort_fn(&key, data);
249                 if (cmp < 0)
250                         node = node->rb_left;
251                 else if (cmp > 0)
252                         node = node->rb_right;
253                 else
254                         return data;
255         }
256         return NULL;
257 }
258
259 static void process_free_event(void *data,
260                                struct event *event,
261                                int cpu,
262                                u64 timestamp __used,
263                                struct thread *thread __used)
264 {
265         unsigned long ptr;
266         struct alloc_stat *s_alloc, *s_caller;
267
268         ptr = raw_field_value(event, "ptr", data);
269
270         s_alloc = search_alloc_stat(ptr, 0, &root_alloc_stat, ptr_cmp);
271         if (!s_alloc)
272                 return;
273
274         if (cpu != s_alloc->alloc_cpu) {
275                 s_alloc->pingpong++;
276
277                 s_caller = search_alloc_stat(0, s_alloc->call_site,
278                                              &root_caller_stat, callsite_cmp);
279                 assert(s_caller);
280                 s_caller->pingpong++;
281         }
282         s_alloc->alloc_cpu = -1;
283 }
284
285 static void
286 process_raw_event(event_t *raw_event __used, void *data,
287                   int cpu, u64 timestamp, struct thread *thread)
288 {
289         struct event *event;
290         int type;
291
292         type = trace_parse_common_type(data);
293         event = trace_find_event(type);
294
295         if (!strcmp(event->name, "kmalloc") ||
296             !strcmp(event->name, "kmem_cache_alloc")) {
297                 process_alloc_event(data, event, cpu, timestamp, thread, 0);
298                 return;
299         }
300
301         if (!strcmp(event->name, "kmalloc_node") ||
302             !strcmp(event->name, "kmem_cache_alloc_node")) {
303                 process_alloc_event(data, event, cpu, timestamp, thread, 1);
304                 return;
305         }
306
307         if (!strcmp(event->name, "kfree") ||
308             !strcmp(event->name, "kmem_cache_free")) {
309                 process_free_event(data, event, cpu, timestamp, thread);
310                 return;
311         }
312 }
313
314 static int process_sample_event(event_t *event, struct perf_session *session __used)
315 {
316         struct sample_data data;
317         struct thread *thread;
318
319         memset(&data, 0, sizeof(data));
320         data.time = -1;
321         data.cpu = -1;
322         data.period = 1;
323
324         event__parse_sample(event, sample_type, &data);
325
326         dump_printf("(IP, %d): %d/%d: %p period: %Ld\n",
327                 event->header.misc,
328                 data.pid, data.tid,
329                 (void *)(long)data.ip,
330                 (long long)data.period);
331
332         thread = threads__findnew(event->ip.pid);
333         if (thread == NULL) {
334                 pr_debug("problem processing %d event, skipping it.\n",
335                          event->header.type);
336                 return -1;
337         }
338
339         dump_printf(" ... thread: %s:%d\n", thread->comm, thread->pid);
340
341         process_raw_event(event, data.raw_data, data.cpu,
342                           data.time, thread);
343
344         return 0;
345 }
346
347 static int sample_type_check(u64 type)
348 {
349         sample_type = type;
350
351         if (!(sample_type & PERF_SAMPLE_RAW)) {
352                 fprintf(stderr,
353                         "No trace sample to read. Did you call perf record "
354                         "without -R?");
355                 return -1;
356         }
357
358         return 0;
359 }
360
361 static struct perf_event_ops event_ops = {
362         .process_sample_event   = process_sample_event,
363         .process_comm_event     = event__process_comm,
364         .sample_type_check      = sample_type_check,
365 };
366
367 static int read_events(void)
368 {
369         int err;
370         struct perf_session *session = perf_session__new(input_name, O_RDONLY, 0);
371
372         if (session == NULL)
373                 return -ENOMEM;
374
375         err = perf_session__process_events(session, &event_ops, 0,
376                                            &event__cwdlen, &event__cwd);
377         perf_session__delete(session);
378         return err;
379 }
380
381 static double fragmentation(unsigned long n_req, unsigned long n_alloc)
382 {
383         if (n_alloc == 0)
384                 return 0.0;
385         else
386                 return 100.0 - (100.0 * n_req / n_alloc);
387 }
388
389 static void __print_result(struct rb_root *root, int n_lines, int is_caller)
390 {
391         struct rb_node *next;
392
393         printf("%.102s\n", graph_dotted_line);
394         printf(" %-34s |",  is_caller ? "Callsite": "Alloc Ptr");
395         printf(" Total_alloc/Per | Total_req/Per   | Hit   | Ping-pong | Frag\n");
396         printf("%.102s\n", graph_dotted_line);
397
398         next = rb_first(root);
399
400         while (next && n_lines--) {
401                 struct alloc_stat *data = rb_entry(next, struct alloc_stat,
402                                                    node);
403                 struct symbol *sym = NULL;
404                 char buf[BUFSIZ];
405                 u64 addr;
406
407                 if (is_caller) {
408                         addr = data->call_site;
409                         if (!raw_ip)
410                                 sym = map_groups__find_function(kmaps, addr, NULL);
411                 } else
412                         addr = data->ptr;
413
414                 if (sym != NULL)
415                         snprintf(buf, sizeof(buf), "%s+%Lx", sym->name,
416                                  addr - sym->start);
417                 else
418                         snprintf(buf, sizeof(buf), "%#Lx", addr);
419                 printf(" %-34s |", buf);
420
421                 printf(" %9llu/%-5lu | %9llu/%-5lu | %6lu | %8lu | %6.3f%%\n",
422                        (unsigned long long)data->bytes_alloc,
423                        (unsigned long)data->bytes_alloc / data->hit,
424                        (unsigned long long)data->bytes_req,
425                        (unsigned long)data->bytes_req / data->hit,
426                        (unsigned long)data->hit,
427                        (unsigned long)data->pingpong,
428                        fragmentation(data->bytes_req, data->bytes_alloc));
429
430                 next = rb_next(next);
431         }
432
433         if (n_lines == -1)
434                 printf(" ...                                | ...             | ...             | ...    | ...      | ...   \n");
435
436         printf("%.102s\n", graph_dotted_line);
437 }
438
439 static void print_summary(void)
440 {
441         printf("\nSUMMARY\n=======\n");
442         printf("Total bytes requested: %lu\n", total_requested);
443         printf("Total bytes allocated: %lu\n", total_allocated);
444         printf("Total bytes wasted on internal fragmentation: %lu\n",
445                total_allocated - total_requested);
446         printf("Internal fragmentation: %f%%\n",
447                fragmentation(total_requested, total_allocated));
448         printf("Cross CPU allocations: %lu/%lu\n", nr_cross_allocs, nr_allocs);
449 }
450
451 static void print_result(void)
452 {
453         if (caller_flag)
454                 __print_result(&root_caller_sorted, caller_lines, 1);
455         if (alloc_flag)
456                 __print_result(&root_alloc_sorted, alloc_lines, 0);
457         print_summary();
458 }
459
460 struct sort_dimension {
461         const char              name[20];
462         sort_fn_t               cmp;
463         struct list_head        list;
464 };
465
466 static LIST_HEAD(caller_sort);
467 static LIST_HEAD(alloc_sort);
468
469 static void sort_insert(struct rb_root *root, struct alloc_stat *data,
470                         struct list_head *sort_list)
471 {
472         struct rb_node **new = &(root->rb_node);
473         struct rb_node *parent = NULL;
474         struct sort_dimension *sort;
475
476         while (*new) {
477                 struct alloc_stat *this;
478                 int cmp = 0;
479
480                 this = rb_entry(*new, struct alloc_stat, node);
481                 parent = *new;
482
483                 list_for_each_entry(sort, sort_list, list) {
484                         cmp = sort->cmp(data, this);
485                         if (cmp)
486                                 break;
487                 }
488
489                 if (cmp > 0)
490                         new = &((*new)->rb_left);
491                 else
492                         new = &((*new)->rb_right);
493         }
494
495         rb_link_node(&data->node, parent, new);
496         rb_insert_color(&data->node, root);
497 }
498
499 static void __sort_result(struct rb_root *root, struct rb_root *root_sorted,
500                           struct list_head *sort_list)
501 {
502         struct rb_node *node;
503         struct alloc_stat *data;
504
505         for (;;) {
506                 node = rb_first(root);
507                 if (!node)
508                         break;
509
510                 rb_erase(node, root);
511                 data = rb_entry(node, struct alloc_stat, node);
512                 sort_insert(root_sorted, data, sort_list);
513         }
514 }
515
516 static void sort_result(void)
517 {
518         __sort_result(&root_alloc_stat, &root_alloc_sorted, &alloc_sort);
519         __sort_result(&root_caller_stat, &root_caller_sorted, &caller_sort);
520 }
521
522 static int __cmd_kmem(void)
523 {
524         setup_pager();
525         read_events();
526         sort_result();
527         print_result();
528
529         return 0;
530 }
531
532 static const char * const kmem_usage[] = {
533         "perf kmem [<options>] {record|stat}",
534         NULL
535 };
536
537 static int ptr_cmp(struct alloc_stat *l, struct alloc_stat *r)
538 {
539         if (l->ptr < r->ptr)
540                 return -1;
541         else if (l->ptr > r->ptr)
542                 return 1;
543         return 0;
544 }
545
546 static struct sort_dimension ptr_sort_dimension = {
547         .name   = "ptr",
548         .cmp    = ptr_cmp,
549 };
550
551 static int callsite_cmp(struct alloc_stat *l, struct alloc_stat *r)
552 {
553         if (l->call_site < r->call_site)
554                 return -1;
555         else if (l->call_site > r->call_site)
556                 return 1;
557         return 0;
558 }
559
560 static struct sort_dimension callsite_sort_dimension = {
561         .name   = "callsite",
562         .cmp    = callsite_cmp,
563 };
564
565 static int hit_cmp(struct alloc_stat *l, struct alloc_stat *r)
566 {
567         if (l->hit < r->hit)
568                 return -1;
569         else if (l->hit > r->hit)
570                 return 1;
571         return 0;
572 }
573
574 static struct sort_dimension hit_sort_dimension = {
575         .name   = "hit",
576         .cmp    = hit_cmp,
577 };
578
579 static int bytes_cmp(struct alloc_stat *l, struct alloc_stat *r)
580 {
581         if (l->bytes_alloc < r->bytes_alloc)
582                 return -1;
583         else if (l->bytes_alloc > r->bytes_alloc)
584                 return 1;
585         return 0;
586 }
587
588 static struct sort_dimension bytes_sort_dimension = {
589         .name   = "bytes",
590         .cmp    = bytes_cmp,
591 };
592
593 static int frag_cmp(struct alloc_stat *l, struct alloc_stat *r)
594 {
595         double x, y;
596
597         x = fragmentation(l->bytes_req, l->bytes_alloc);
598         y = fragmentation(r->bytes_req, r->bytes_alloc);
599
600         if (x < y)
601                 return -1;
602         else if (x > y)
603                 return 1;
604         return 0;
605 }
606
607 static struct sort_dimension frag_sort_dimension = {
608         .name   = "frag",
609         .cmp    = frag_cmp,
610 };
611
612 static int pingpong_cmp(struct alloc_stat *l, struct alloc_stat *r)
613 {
614         if (l->pingpong < r->pingpong)
615                 return -1;
616         else if (l->pingpong > r->pingpong)
617                 return 1;
618         return 0;
619 }
620
621 static struct sort_dimension pingpong_sort_dimension = {
622         .name   = "pingpong",
623         .cmp    = pingpong_cmp,
624 };
625
626 static struct sort_dimension *avail_sorts[] = {
627         &ptr_sort_dimension,
628         &callsite_sort_dimension,
629         &hit_sort_dimension,
630         &bytes_sort_dimension,
631         &frag_sort_dimension,
632         &pingpong_sort_dimension,
633 };
634
635 #define NUM_AVAIL_SORTS \
636         (int)(sizeof(avail_sorts) / sizeof(struct sort_dimension *))
637
638 static int sort_dimension__add(const char *tok, struct list_head *list)
639 {
640         struct sort_dimension *sort;
641         int i;
642
643         for (i = 0; i < NUM_AVAIL_SORTS; i++) {
644                 if (!strcmp(avail_sorts[i]->name, tok)) {
645                         sort = malloc(sizeof(*sort));
646                         if (!sort)
647                                 die("malloc");
648                         memcpy(sort, avail_sorts[i], sizeof(*sort));
649                         list_add_tail(&sort->list, list);
650                         return 0;
651                 }
652         }
653
654         return -1;
655 }
656
657 static int setup_sorting(struct list_head *sort_list, const char *arg)
658 {
659         char *tok;
660         char *str = strdup(arg);
661
662         if (!str)
663                 die("strdup");
664
665         while (true) {
666                 tok = strsep(&str, ",");
667                 if (!tok)
668                         break;
669                 if (sort_dimension__add(tok, sort_list) < 0) {
670                         error("Unknown --sort key: '%s'", tok);
671                         return -1;
672                 }
673         }
674
675         free(str);
676         return 0;
677 }
678
679 static int parse_sort_opt(const struct option *opt __used,
680                           const char *arg, int unset __used)
681 {
682         if (!arg)
683                 return -1;
684
685         if (caller_flag > alloc_flag)
686                 return setup_sorting(&caller_sort, arg);
687         else
688                 return setup_sorting(&alloc_sort, arg);
689
690         return 0;
691 }
692
693 static int parse_caller_opt(const struct option *opt __used,
694                           const char *arg __used, int unset __used)
695 {
696         caller_flag = (alloc_flag + 1);
697         return 0;
698 }
699
700 static int parse_alloc_opt(const struct option *opt __used,
701                           const char *arg __used, int unset __used)
702 {
703         alloc_flag = (caller_flag + 1);
704         return 0;
705 }
706
707 static int parse_line_opt(const struct option *opt __used,
708                           const char *arg, int unset __used)
709 {
710         int lines;
711
712         if (!arg)
713                 return -1;
714
715         lines = strtoul(arg, NULL, 10);
716
717         if (caller_flag > alloc_flag)
718                 caller_lines = lines;
719         else
720                 alloc_lines = lines;
721
722         return 0;
723 }
724
725 static const struct option kmem_options[] = {
726         OPT_STRING('i', "input", &input_name, "file",
727                    "input file name"),
728         OPT_CALLBACK_NOOPT(0, "caller", NULL, NULL,
729                            "show per-callsite statistics",
730                            parse_caller_opt),
731         OPT_CALLBACK_NOOPT(0, "alloc", NULL, NULL,
732                            "show per-allocation statistics",
733                            parse_alloc_opt),
734         OPT_CALLBACK('s', "sort", NULL, "key[,key2...]",
735                      "sort by keys: ptr, call_site, bytes, hit, pingpong, frag",
736                      parse_sort_opt),
737         OPT_CALLBACK('l', "line", NULL, "num",
738                      "show n lines",
739                      parse_line_opt),
740         OPT_BOOLEAN(0, "raw-ip", &raw_ip, "show raw ip instead of symbol"),
741         OPT_END()
742 };
743
744 static const char *record_args[] = {
745         "record",
746         "-a",
747         "-R",
748         "-M",
749         "-f",
750         "-c", "1",
751         "-e", "kmem:kmalloc",
752         "-e", "kmem:kmalloc_node",
753         "-e", "kmem:kfree",
754         "-e", "kmem:kmem_cache_alloc",
755         "-e", "kmem:kmem_cache_alloc_node",
756         "-e", "kmem:kmem_cache_free",
757 };
758
759 static int __cmd_record(int argc, const char **argv)
760 {
761         unsigned int rec_argc, i, j;
762         const char **rec_argv;
763
764         rec_argc = ARRAY_SIZE(record_args) + argc - 1;
765         rec_argv = calloc(rec_argc + 1, sizeof(char *));
766
767         for (i = 0; i < ARRAY_SIZE(record_args); i++)
768                 rec_argv[i] = strdup(record_args[i]);
769
770         for (j = 1; j < (unsigned int)argc; j++, i++)
771                 rec_argv[i] = argv[j];
772
773         return cmd_record(i, rec_argv, NULL);
774 }
775
776 int cmd_kmem(int argc, const char **argv, const char *prefix __used)
777 {
778         symbol__init(0);
779
780         argc = parse_options(argc, argv, kmem_options, kmem_usage, 0);
781
782         if (!argc)
783                 usage_with_options(kmem_usage, kmem_options);
784
785         if (!strncmp(argv[0], "rec", 3)) {
786                 return __cmd_record(argc, argv);
787         } else if (!strcmp(argv[0], "stat")) {
788                 setup_cpunode_map();
789
790                 if (list_empty(&caller_sort))
791                         setup_sorting(&caller_sort, default_sort_order);
792                 if (list_empty(&alloc_sort))
793                         setup_sorting(&alloc_sort, default_sort_order);
794
795                 return __cmd_kmem();
796         }
797
798         return 0;
799 }
800