perf hist: Adopt filter by dso and by thread methods from the newt browser
[safe/jmp/linux-2.6] / tools / perf / util / newt.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #undef _GNU_SOURCE
4
5 #include <stdlib.h>
6 #include <newt.h>
7 #include <sys/ttydefaults.h>
8
9 #include "cache.h"
10 #include "hist.h"
11 #include "session.h"
12 #include "sort.h"
13 #include "symbol.h"
14
15 struct ui_progress {
16         newtComponent form, scale;
17 };
18
19 struct ui_progress *ui_progress__new(const char *title, u64 total)
20 {
21         struct ui_progress *self = malloc(sizeof(*self));
22
23         if (self != NULL) {
24                 int cols;
25                 newtGetScreenSize(&cols, NULL);
26                 cols -= 4;
27                 newtCenteredWindow(cols, 1, title);
28                 self->form  = newtForm(NULL, NULL, 0);
29                 if (self->form == NULL)
30                         goto out_free_self;
31                 self->scale = newtScale(0, 0, cols, total);
32                 if (self->scale == NULL)
33                         goto out_free_form;
34                 newtFormAddComponent(self->form, self->scale);
35                 newtRefresh();
36         }
37
38         return self;
39
40 out_free_form:
41         newtFormDestroy(self->form);
42 out_free_self:
43         free(self);
44         return NULL;
45 }
46
47 void ui_progress__update(struct ui_progress *self, u64 curr)
48 {
49         newtScaleSet(self->scale, curr);
50         newtRefresh();
51 }
52
53 void ui_progress__delete(struct ui_progress *self)
54 {
55         newtFormDestroy(self->form);
56         newtPopWindow();
57         free(self);
58 }
59
60 static char browser__last_msg[1024];
61
62 int browser__show_help(const char *format, va_list ap)
63 {
64         int ret;
65         static int backlog;
66
67         ret = vsnprintf(browser__last_msg + backlog,
68                         sizeof(browser__last_msg) - backlog, format, ap);
69         backlog += ret;
70
71         if (browser__last_msg[backlog - 1] == '\n') {
72                 newtPopHelpLine();
73                 newtPushHelpLine(browser__last_msg);
74                 newtRefresh();
75                 backlog = 0;
76         }
77
78         return ret;
79 }
80
81 static void newt_form__set_exit_keys(newtComponent self)
82 {
83         newtFormAddHotKey(self, NEWT_KEY_ESCAPE);
84         newtFormAddHotKey(self, 'Q');
85         newtFormAddHotKey(self, 'q');
86         newtFormAddHotKey(self, CTRL('c'));
87 }
88
89 static newtComponent newt_form__new(void)
90 {
91         newtComponent self = newtForm(NULL, NULL, 0);
92         if (self)
93                 newt_form__set_exit_keys(self);
94         return self;
95 }
96
97 static int popup_menu(int argc, char * const argv[])
98 {
99         struct newtExitStruct es;
100         int i, rc = -1, max_len = 5;
101         newtComponent listbox, form = newt_form__new();
102
103         if (form == NULL)
104                 return -1;
105
106         listbox = newtListbox(0, 0, argc, NEWT_FLAG_RETURNEXIT);
107         if (listbox == NULL)
108                 goto out_destroy_form;
109
110         newtFormAddComponent(form, listbox);
111
112         for (i = 0; i < argc; ++i) {
113                 int len = strlen(argv[i]);
114                 if (len > max_len)
115                         max_len = len;
116                 if (newtListboxAddEntry(listbox, argv[i], (void *)(long)i))
117                         goto out_destroy_form;
118         }
119
120         newtCenteredWindow(max_len, argc, NULL);
121         newtFormRun(form, &es);
122         rc = newtListboxGetCurrent(listbox) - NULL;
123         if (es.reason == NEWT_EXIT_HOTKEY)
124                 rc = -1;
125         newtPopWindow();
126 out_destroy_form:
127         newtFormDestroy(form);
128         return rc;
129 }
130
131 static bool dialog_yesno(const char *msg)
132 {
133         /* newtWinChoice should really be accepting const char pointers... */
134         char yes[] = "Yes", no[] = "No";
135         return newtWinChoice(NULL, yes, no, (char *)msg) == 1;
136 }
137
138 /*
139  * When debugging newt problems it was useful to be able to "unroll"
140  * the calls to newtCheckBoxTreeAdd{Array,Item}, so that we can generate
141  * a source file with the sequence of calls to these methods, to then
142  * tweak the arrays to get the intended results, so I'm keeping this code
143  * here, may be useful again in the future.
144  */
145 #undef NEWT_DEBUG
146
147 static void newt_checkbox_tree__add(newtComponent tree, const char *str,
148                                     void *priv, int *indexes)
149 {
150 #ifdef NEWT_DEBUG
151         /* Print the newtCheckboxTreeAddArray to tinker with its index arrays */
152         int i = 0, len = 40 - strlen(str);
153
154         fprintf(stderr,
155                 "\tnewtCheckboxTreeAddItem(tree, %*.*s\"%s\", (void *)%p, 0, ",
156                 len, len, " ", str, priv);
157         while (indexes[i] != NEWT_ARG_LAST) {
158                 if (indexes[i] != NEWT_ARG_APPEND)
159                         fprintf(stderr, " %d,", indexes[i]);
160                 else
161                         fprintf(stderr, " %s,", "NEWT_ARG_APPEND");
162                 ++i;
163         }
164         fprintf(stderr, " %s", " NEWT_ARG_LAST);\n");
165         fflush(stderr);
166 #endif
167         newtCheckboxTreeAddArray(tree, str, priv, 0, indexes);
168 }
169
170 static char *callchain_list__sym_name(struct callchain_list *self,
171                                       char *bf, size_t bfsize)
172 {
173         if (self->ms.sym)
174                 return self->ms.sym->name;
175
176         snprintf(bf, bfsize, "%#Lx", self->ip);
177         return bf;
178 }
179
180 static void __callchain__append_graph_browser(struct callchain_node *self,
181                                               newtComponent tree, u64 total,
182                                               int *indexes, int depth)
183 {
184         struct rb_node *node;
185         u64 new_total, remaining;
186         int idx = 0;
187
188         if (callchain_param.mode == CHAIN_GRAPH_REL)
189                 new_total = self->children_hit;
190         else
191                 new_total = total;
192
193         remaining = new_total;
194         node = rb_first(&self->rb_root);
195         while (node) {
196                 struct callchain_node *child = rb_entry(node, struct callchain_node, rb_node);
197                 struct rb_node *next = rb_next(node);
198                 u64 cumul = cumul_hits(child);
199                 struct callchain_list *chain;
200                 int first = true, printed = 0;
201                 int chain_idx = -1;
202                 remaining -= cumul;
203
204                 indexes[depth] = NEWT_ARG_APPEND;
205                 indexes[depth + 1] = NEWT_ARG_LAST;
206
207                 list_for_each_entry(chain, &child->val, list) {
208                         char ipstr[BITS_PER_LONG / 4 + 1],
209                              *alloc_str = NULL;
210                         const char *str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));
211
212                         if (first) {
213                                 double percent = cumul * 100.0 / new_total;
214
215                                 first = false;
216                                 if (asprintf(&alloc_str, "%2.2f%% %s", percent, str) < 0)
217                                         str = "Not enough memory!";
218                                 else
219                                         str = alloc_str;
220                         } else {
221                                 indexes[depth] = idx;
222                                 indexes[depth + 1] = NEWT_ARG_APPEND;
223                                 indexes[depth + 2] = NEWT_ARG_LAST;
224                                 ++chain_idx;
225                         }
226                         newt_checkbox_tree__add(tree, str, &chain->ms, indexes);
227                         free(alloc_str);
228                         ++printed;
229                 }
230
231                 indexes[depth] = idx;
232                 if (chain_idx != -1)
233                         indexes[depth + 1] = chain_idx;
234                 if (printed != 0)
235                         ++idx;
236                 __callchain__append_graph_browser(child, tree, new_total, indexes,
237                                                   depth + (chain_idx != -1 ? 2 : 1));
238                 node = next;
239         }
240 }
241
242 static void callchain__append_graph_browser(struct callchain_node *self,
243                                             newtComponent tree, u64 total,
244                                             int *indexes, int parent_idx)
245 {
246         struct callchain_list *chain;
247         int i = 0;
248
249         indexes[1] = NEWT_ARG_APPEND;
250         indexes[2] = NEWT_ARG_LAST;
251
252         list_for_each_entry(chain, &self->val, list) {
253                 char ipstr[BITS_PER_LONG / 4 + 1], *str;
254
255                 if (chain->ip >= PERF_CONTEXT_MAX)
256                         continue;
257
258                 if (!i++ && sort__first_dimension == SORT_SYM)
259                         continue;
260
261                 str = callchain_list__sym_name(chain, ipstr, sizeof(ipstr));
262                 newt_checkbox_tree__add(tree, str, &chain->ms, indexes);
263         }
264
265         indexes[1] = parent_idx;
266         indexes[2] = NEWT_ARG_APPEND;
267         indexes[3] = NEWT_ARG_LAST;
268         __callchain__append_graph_browser(self, tree, total, indexes, 2);
269 }
270
271 static void hist_entry__append_callchain_browser(struct hist_entry *self,
272                                                  newtComponent tree, u64 total, int parent_idx)
273 {
274         struct rb_node *rb_node;
275         int indexes[1024] = { [0] = parent_idx, };
276         int idx = 0;
277         struct callchain_node *chain;
278
279         rb_node = rb_first(&self->sorted_chain);
280         while (rb_node) {
281                 chain = rb_entry(rb_node, struct callchain_node, rb_node);
282                 switch (callchain_param.mode) {
283                 case CHAIN_FLAT:
284                         break;
285                 case CHAIN_GRAPH_ABS: /* falldown */
286                 case CHAIN_GRAPH_REL:
287                         callchain__append_graph_browser(chain, tree, total, indexes, idx++);
288                         break;
289                 case CHAIN_NONE:
290                 default:
291                         break;
292                 }
293                 rb_node = rb_next(rb_node);
294         }
295 }
296
297 static size_t hist_entry__append_browser(struct hist_entry *self,
298                                          newtComponent tree, u64 total)
299 {
300         char s[256];
301         size_t ret;
302
303         if (symbol_conf.exclude_other && !self->parent)
304                 return 0;
305
306         ret = hist_entry__snprintf(self, s, sizeof(s), NULL,
307                                    false, 0, false, total);
308         if (symbol_conf.use_callchain) {
309                 int indexes[2];
310
311                 indexes[0] = NEWT_ARG_APPEND;
312                 indexes[1] = NEWT_ARG_LAST;
313                 newt_checkbox_tree__add(tree, s, &self->ms, indexes);
314         } else
315                 newtListboxAppendEntry(tree, s, &self->ms);
316
317         return ret;
318 }
319
320 static void map_symbol__annotate_browser(const struct map_symbol *self,
321                                          const char *input_name)
322 {
323         FILE *fp;
324         int cols, rows;
325         newtComponent form, tree;
326         struct newtExitStruct es;
327         char *str;
328         size_t line_len, max_line_len = 0;
329         size_t max_usable_width;
330         char *line = NULL;
331
332         if (self->sym == NULL)
333                 return;
334
335         if (asprintf(&str, "perf annotate -i \"%s\" -d \"%s\" %s 2>&1 | expand",
336                      input_name, self->map->dso->name, self->sym->name) < 0)
337                 return;
338
339         fp = popen(str, "r");
340         if (fp == NULL)
341                 goto out_free_str;
342
343         newtPushHelpLine("Press ESC to exit");
344         newtGetScreenSize(&cols, &rows);
345         tree = newtListbox(0, 0, rows - 5, NEWT_FLAG_SCROLL);
346
347         while (!feof(fp)) {
348                 if (getline(&line, &line_len, fp) < 0 || !line_len)
349                         break;
350                 while (line_len != 0 && isspace(line[line_len - 1]))
351                         line[--line_len] = '\0';
352
353                 if (line_len > max_line_len)
354                         max_line_len = line_len;
355                 newtListboxAppendEntry(tree, line, NULL);
356         }
357         fclose(fp);
358         free(line);
359
360         max_usable_width = cols - 22;
361         if (max_line_len > max_usable_width)
362                 max_line_len = max_usable_width;
363
364         newtListboxSetWidth(tree, max_line_len);
365
366         newtCenteredWindow(max_line_len + 2, rows - 5, self->sym->name);
367         form = newt_form__new();
368         newtFormAddComponent(form, tree);
369
370         newtFormRun(form, &es);
371         newtFormDestroy(form);
372         newtPopWindow();
373         newtPopHelpLine();
374 out_free_str:
375         free(str);
376 }
377
378 static const void *newt__symbol_tree_get_current(newtComponent self)
379 {
380         if (symbol_conf.use_callchain)
381                 return newtCheckboxTreeGetCurrent(self);
382         return newtListboxGetCurrent(self);
383 }
384
385 static void hist_browser__selection(newtComponent self, void *data)
386 {
387         const struct map_symbol **symbol_ptr = data;
388         *symbol_ptr = newt__symbol_tree_get_current(self);
389 }
390
391 struct hist_browser {
392         newtComponent           form, tree;
393         const struct map_symbol *selection;
394 };
395
396 static struct hist_browser *hist_browser__new(void)
397 {
398         struct hist_browser *self = malloc(sizeof(*self));
399
400         if (self != NULL)
401                 self->form = NULL;
402
403         return self;
404 }
405
406 static void hist_browser__delete(struct hist_browser *self)
407 {
408         newtFormDestroy(self->form);
409         newtPopWindow();
410         free(self);
411 }
412
413 static int hist_browser__populate(struct hist_browser *self, struct hists *hists,
414                                   const char *title)
415 {
416         int max_len = 0, idx, cols, rows;
417         struct ui_progress *progress;
418         struct rb_node *nd;
419         u64 curr_hist = 0;
420         char seq[] = ".";
421         char str[256];
422
423         if (self->form) {
424                 newtFormDestroy(self->form);
425                 newtPopWindow();
426         }
427
428         snprintf(str, sizeof(str), "Samples: %Ld                            ",
429                  hists->stats.total);
430         newtDrawRootText(0, 0, str);
431
432         newtGetScreenSize(NULL, &rows);
433
434         if (symbol_conf.use_callchain)
435                 self->tree = newtCheckboxTreeMulti(0, 0, rows - 5, seq,
436                                                    NEWT_FLAG_SCROLL);
437         else
438                 self->tree = newtListbox(0, 0, rows - 5,
439                                         (NEWT_FLAG_SCROLL |
440                                          NEWT_FLAG_RETURNEXIT));
441
442         newtComponentAddCallback(self->tree, hist_browser__selection,
443                                  &self->selection);
444
445         progress = ui_progress__new("Adding entries to the browser...",
446                                     hists->nr_entries);
447         if (progress == NULL)
448                 return -1;
449
450         idx = 0;
451         for (nd = rb_first(&hists->entries); nd; nd = rb_next(nd)) {
452                 struct hist_entry *h = rb_entry(nd, struct hist_entry, rb_node);
453                 int len;
454
455                 if (h->filtered)
456                         continue;
457
458                 len = hist_entry__append_browser(h, self->tree, hists->stats.total);
459                 if (len > max_len)
460                         max_len = len;
461                 if (symbol_conf.use_callchain)
462                         hist_entry__append_callchain_browser(h, self->tree,
463                                                              hists->stats.total, idx++);
464                 ++curr_hist;
465                 if (curr_hist % 5)
466                         ui_progress__update(progress, curr_hist);
467         }
468
469         ui_progress__delete(progress);
470
471         newtGetScreenSize(&cols, &rows);
472
473         if (max_len > cols)
474                 max_len = cols - 3;
475
476         if (!symbol_conf.use_callchain)
477                 newtListboxSetWidth(self->tree, max_len);
478
479         newtCenteredWindow(max_len + (symbol_conf.use_callchain ? 5 : 0),
480                            rows - 5, title);
481         self->form = newt_form__new();
482         if (self->form == NULL)
483                 return -1;
484
485         newtFormAddHotKey(self->form, 'A');
486         newtFormAddHotKey(self->form, 'a');
487         newtFormAddHotKey(self->form, NEWT_KEY_RIGHT);
488         newtFormAddComponents(self->form, self->tree, NULL);
489         self->selection = newt__symbol_tree_get_current(self->tree);
490
491         return 0;
492 }
493
494 static struct thread *hist_browser__selected_thread(struct hist_browser *self)
495 {
496         int *indexes;
497
498         if (!symbol_conf.use_callchain)
499                 goto out;
500
501         indexes = newtCheckboxTreeFindItem(self->tree, (void *)self->selection);
502         if (indexes) {
503                 bool is_hist_entry = indexes[1] == NEWT_ARG_LAST;
504                 free(indexes);
505                 if (is_hist_entry)
506                         goto out;
507         }
508         return NULL;
509 out:
510         return *(struct thread **)(self->selection + 1);
511 }
512
513 static int hist_browser__title(char *bf, size_t size, const char *input_name,
514                                const struct dso *dso, const struct thread *thread)
515 {
516         int printed = 0;
517
518         if (thread)
519                 printed += snprintf(bf + printed, size - printed,
520                                     "Thread: %s(%d)",
521                                     (thread->comm_set ?  thread->comm : ""),
522                                     thread->pid);
523         if (dso)
524                 printed += snprintf(bf + printed, size - printed,
525                                     "%sDSO: %s", thread ? " " : "",
526                                     dso->short_name);
527         return printed ?: snprintf(bf, size, "Report: %s", input_name);
528 }
529
530 int hists__browse(struct hists *self, const char *helpline, const char *input_name)
531 {
532         struct hist_browser *browser = hist_browser__new();
533         const struct thread *thread_filter = NULL;
534         const struct dso *dso_filter = NULL;
535         struct newtExitStruct es;
536         char msg[160];
537         int err = -1;
538
539         if (browser == NULL)
540                 return -1;
541
542         newtPushHelpLine(helpline);
543
544         hist_browser__title(msg, sizeof(msg), input_name,
545                             dso_filter, thread_filter);
546         if (hist_browser__populate(browser, self, msg) < 0)
547                 goto out;
548
549         while (1) {
550                 const struct thread *thread;
551                 const struct dso *dso;
552                 char *options[16];
553                 int nr_options = 0, choice = 0, i,
554                     annotate = -2, zoom_dso = -2, zoom_thread = -2;
555
556                 newtFormRun(browser->form, &es);
557                 if (es.reason == NEWT_EXIT_HOTKEY) {
558                         if (toupper(es.u.key) == 'A')
559                                 goto do_annotate;
560                         if (es.u.key == NEWT_KEY_ESCAPE ||
561                             toupper(es.u.key) == 'Q' ||
562                             es.u.key == CTRL('c')) {
563                                 if (dialog_yesno("Do you really want to exit?"))
564                                         break;
565                                 else
566                                         continue;
567                         }
568                 }
569
570                 if (browser->selection->sym != NULL &&
571                     asprintf(&options[nr_options], "Annotate %s",
572                              browser->selection->sym->name) > 0)
573                         annotate = nr_options++;
574
575                 thread = hist_browser__selected_thread(browser);
576                 if (thread != NULL &&
577                     asprintf(&options[nr_options], "Zoom %s %s(%d) thread",
578                              (thread_filter ? "out of" : "into"),
579                              (thread->comm_set ? thread->comm : ""),
580                              thread->pid) > 0)
581                         zoom_thread = nr_options++;
582
583                 dso = browser->selection->map ? browser->selection->map->dso : NULL;
584                 if (dso != NULL &&
585                     asprintf(&options[nr_options], "Zoom %s %s DSO",
586                              (dso_filter ? "out of" : "into"),
587                              (dso->kernel ? "the Kernel" : dso->short_name)) > 0)
588                         zoom_dso = nr_options++;
589
590                 options[nr_options++] = (char *)"Exit";
591
592                 choice = popup_menu(nr_options, options);
593
594                 for (i = 0; i < nr_options - 1; ++i)
595                         free(options[i]);
596
597                 if (choice == nr_options - 1)
598                         break;
599
600                 if (choice == -1)
601                         continue;
602 do_annotate:
603                 if (choice == annotate) {
604                         if (browser->selection->map->dso->origin == DSO__ORIG_KERNEL) {
605                                 newtPopHelpLine();
606                                 newtPushHelpLine("No vmlinux file found, can't "
607                                                  "annotate with just a "
608                                                  "kallsyms file");
609                                 continue;
610                         }
611                         map_symbol__annotate_browser(browser->selection, input_name);
612                 } else if (choice == zoom_dso) {
613                         if (dso_filter) {
614                                 newtPopHelpLine();
615                                 dso_filter = NULL;
616                         } else {
617                                 snprintf(msg, sizeof(msg),
618                                          "To zoom out press -> + \"Zoom out of %s DSO\"",
619                                          dso->kernel ? "the Kernel" : dso->short_name);
620                                 newtPushHelpLine(msg);
621                                 dso_filter = dso;
622                         }
623                         hists__filter_by_dso(self, dso_filter);
624                         hist_browser__title(msg, sizeof(msg), input_name,
625                                             dso_filter, thread_filter);
626                         if (hist_browser__populate(browser, self, msg) < 0)
627                                 goto out;
628                 } else if (choice == zoom_thread) {
629                         if (thread_filter) {
630                                 newtPopHelpLine();
631                                 thread_filter = NULL;
632                         } else {
633                                 snprintf(msg, sizeof(msg),
634                                          "To zoom out press -> + \"Zoom out of %s(%d) thread\"",
635                                          (thread->comm_set ? thread->comm : ""),
636                                          thread->pid);
637                                 newtPushHelpLine(msg);
638                                 thread_filter = thread;
639                         }
640                         hists__filter_by_thread(self, thread_filter);
641                         hist_browser__title(msg, sizeof(msg), input_name,
642                                             dso_filter, thread_filter);
643                         if (hist_browser__populate(browser, self, msg) < 0)
644                                 goto out;
645                 }
646         }
647         err = 0;
648 out:
649         hist_browser__delete(browser);
650         return err;
651 }
652
653 void setup_browser(void)
654 {
655         if (!isatty(1))
656                 return;
657
658         use_browser = true;
659         newtInit();
660         newtCls();
661         newtPushHelpLine(" ");
662 }
663
664 void exit_browser(bool wait_for_ok)
665 {
666         if (use_browser) {
667                 if (wait_for_ok) {
668                         char title[] = "Fatal Error", ok[] = "Ok";
669                         newtWinMessage(title, ok, browser__last_msg);
670                 }
671                 newtFinished();
672         }
673 }