61dbe5cd9187527eb2ca45cc9a76149ee774e098
[vpp.git] / src / plugins / perfmon / perfmon.c
1 /*
2  * perfmon.c - skeleton vpp engine plug-in
3  *
4  * Copyright (c) <current-year> <your-organization>
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <vnet/vnet.h>
19 #include <vnet/plugin/plugin.h>
20 #include <perfmon/perfmon.h>
21
22 #include <vlibapi/api.h>
23 #include <vlibmemory/api.h>
24 #include <vpp/app/version.h>
25 #include <linux/limits.h>
26
27 perfmon_main_t perfmon_main;
28
29 static char *perfmon_json_path = "/usr/share/vpp/plugins/perfmon";
30
31 static void
32 set_perfmon_json_path ()
33 {
34   char *p, path[PATH_MAX];
35   int rv;
36   u8 *s;
37
38   /* find executable path */
39   if ((rv = readlink ("/proc/self/exe", path, PATH_MAX - 1)) == -1)
40     return;
41
42   /* readlink doesn't provide null termination */
43   path[rv] = 0;
44
45   /* strip filename */
46   if ((p = strrchr (path, '/')) == 0)
47     return;
48   *p = 0;
49
50   /* strip bin/ */
51   if ((p = strrchr (path, '/')) == 0)
52     return;
53   *p = 0;
54
55   /* cons up the .json file path */
56   s = format (0, "%s/share/vpp/plugins/perfmon", path);
57   vec_add1 (s, 0);
58   perfmon_json_path = (char *) s;
59 }
60
61 #define foreach_cpuid_table                     \
62 _(0x0306C3, haswell_core_v28.json)              \
63 _(0x0306F2, haswell_core_v28.json)              \
64 _(0x0406E3, skylake_core_v42.json)              \
65 _(0x0506E3, skylake_core_v42.json)
66
67 static inline u32
68 get_cpuid (void)
69 {
70 #if defined(__x86_64__)
71   u32 cpuid;
72   asm volatile ("mov $1, %%eax; cpuid; mov %%eax, %0":"=r" (cpuid)::"%eax",
73                 "%edx", "%ecx", "%rbx");
74   return cpuid;
75 #else
76   return 0;
77 #endif
78 }
79
80 static clib_error_t *
81 perfmon_init (vlib_main_t * vm)
82 {
83   perfmon_main_t *pm = &perfmon_main;
84   clib_error_t *error = 0;
85   u32 cpuid;
86   uword *ht;
87   int found_a_table = 0;
88
89   pm->vlib_main = vm;
90   pm->vnet_main = vnet_get_main ();
91
92   pm->capture_by_thread_and_node_name =
93     hash_create_string (0, sizeof (uword));
94
95   pm->log_class = vlib_log_register_class ("perfmon", 0);
96
97   /* Default data collection interval */
98   pm->timeout_interval = 3.0;
99   vec_validate (pm->pm_fds, vec_len (vlib_mains) - 1);
100   vec_validate (pm->perf_event_pages, vec_len (vlib_mains) - 1);
101   vec_validate (pm->rdpmc_indices, vec_len (vlib_mains) - 1);
102   pm->page_size = getpagesize ();
103
104   ht = pm->perfmon_table = 0;
105
106   set_perfmon_json_path ();
107
108   cpuid = get_cpuid ();
109
110   if (0)
111     {
112     }
113 #define _(id,table)                                             \
114   else if (cpuid == id)                                         \
115     {                                                           \
116       vlib_log_debug (pm->log_class, "Found table %s", #table); \
117       ht = perfmon_parse_table (pm, perfmon_json_path, #table); \
118       found_a_table = 1;                                        \
119     }
120   foreach_cpuid_table;
121 #undef _
122
123   pm->perfmon_table = ht;
124
125   if (found_a_table == 0)
126     vlib_log_err (pm->log_class, "No table for cpuid %x", cpuid);
127
128   return error;
129 }
130
131 VLIB_INIT_FUNCTION (perfmon_init);
132
133 /* *INDENT-OFF* */
134 VLIB_PLUGIN_REGISTER () =
135 {
136   .version = VPP_BUILD_VER,
137   .description = "Performance monitor plugin",
138 #if !defined(__x86_64__)
139   .default_disabled = 1,
140 #endif
141 };
142 /* *INDENT-ON* */
143
144 static uword
145 atox (u8 * s)
146 {
147   uword rv = 0;
148
149   while (*s)
150     {
151       if (*s >= '0' && *s <= '9')
152         rv = (rv << 4) | (*s - '0');
153       else if (*s >= 'a' && *s <= 'f')
154         rv = (rv << 4) | (*s - 'a' + 10);
155       else if (*s >= 'A' && *s <= 'A')
156         rv = (rv << 4) | (*s - 'A' + 10);
157       else if (*s == 'x')
158         ;
159       else
160         break;
161       s++;
162     }
163   return rv;
164 }
165
166 static uword
167 unformat_processor_event (unformat_input_t * input, va_list * args)
168 {
169   perfmon_main_t *pm = va_arg (*args, perfmon_main_t *);
170   perfmon_event_config_t *ep = va_arg (*args, perfmon_event_config_t *);
171   u8 *s = 0;
172   name_value_pair_t **nvps, *nvp;
173   hash_pair_t *hp;
174   int i;
175   int set_values = 0;
176   u32 pe_config = 0;
177
178   if (pm->perfmon_table == 0)
179     return 0;
180
181   if (!unformat (input, "%s", &s))
182     return 0;
183
184   hp = hash_get_pair_mem (pm->perfmon_table, s);
185
186   vec_free (s);
187
188   if (hp == 0)
189     return 0;
190
191   nvps = (name_value_pair_t **) (hp->value[0]);
192
193   for (i = 0; i < vec_len (nvps); i++)
194     {
195       nvp = nvps[i];
196       if (!strncmp ((char *) nvp->name, "EventCode", 9))
197         {
198           pe_config |= atox (nvp->value);
199           set_values++;
200         }
201       else if (!strncmp ((char *) nvp->name, "UMask", 5))
202         {
203           pe_config |= (atox (nvp->value) << 8);
204           set_values++;
205         }
206       if (set_values == 2)
207         break;
208     }
209
210   if (set_values != 2)
211     {
212       clib_warning ("BUG: only found %d values", set_values);
213       return 0;
214     }
215
216   ep->name = (char *) hp->key;
217   ep->pe_type = PERF_TYPE_RAW;
218   ep->pe_config = pe_config;
219   return 1;
220 }
221
222 static clib_error_t *
223 set_pmc_command_fn (vlib_main_t * vm,
224                     unformat_input_t * input, vlib_cli_command_t * cmd)
225 {
226   perfmon_main_t *pm = &perfmon_main;
227   unformat_input_t _line_input, *line_input = &_line_input;
228   perfmon_event_config_t ec;
229   u32 timeout_seconds;
230   u32 deadman;
231
232   vec_reset_length (pm->events_to_collect);
233   pm->ipc_event_index = ~0;
234   pm->mispredict_event_index = ~0;
235
236   if (!unformat_user (input, unformat_line_input, line_input))
237     return clib_error_return (0, "counter names required...");
238
239   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
240     {
241       if (unformat (line_input, "timeout %u", &timeout_seconds))
242         pm->timeout_interval = (f64) timeout_seconds;
243       else if (unformat (line_input, "instructions-per-clock"))
244         {
245           ec.name = "instructions";
246           ec.pe_type = PERF_TYPE_HARDWARE;
247           ec.pe_config = PERF_COUNT_HW_INSTRUCTIONS;
248           pm->ipc_event_index = vec_len (pm->events_to_collect);
249           vec_add1 (pm->events_to_collect, ec);
250           ec.name = "cpu-cycles";
251           ec.pe_type = PERF_TYPE_HARDWARE;
252           ec.pe_config = PERF_COUNT_HW_CPU_CYCLES;
253           vec_add1 (pm->events_to_collect, ec);
254         }
255       else if (unformat (line_input, "branch-mispredict-rate"))
256         {
257           ec.name = "branch-misses";
258           ec.pe_type = PERF_TYPE_HARDWARE;
259           ec.pe_config = PERF_COUNT_HW_BRANCH_MISSES;
260           pm->mispredict_event_index = vec_len (pm->events_to_collect);
261           vec_add1 (pm->events_to_collect, ec);
262           ec.name = "branches";
263           ec.pe_type = PERF_TYPE_HARDWARE;
264           ec.pe_config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
265           vec_add1 (pm->events_to_collect, ec);
266         }
267       else if (unformat (line_input, "%U", unformat_processor_event, pm, &ec))
268         {
269           vec_add1 (pm->events_to_collect, ec);
270         }
271 #define _(type,event,str)                       \
272       else if (unformat (line_input, str))      \
273         {                                       \
274           ec.name = str;                        \
275           ec.pe_type = type;                    \
276           ec.pe_config = event;                 \
277           vec_add1 (pm->events_to_collect, ec); \
278         }
279       foreach_perfmon_event
280 #undef _
281         else
282         return clib_error_return (0, "unknown input '%U'",
283                                   format_unformat_error, line_input);
284     }
285
286   if (vec_len (pm->events_to_collect) == 0)
287     return clib_error_return (0, "no events specified...");
288
289   vlib_cli_output (vm, "Start collection for %d events, wait %.2f seconds",
290                    vec_len (pm->events_to_collect),
291                    (f64) (vec_len (pm->events_to_collect))
292                    * pm->timeout_interval);
293
294   vlib_process_signal_event (pm->vlib_main, perfmon_periodic_node.index,
295                              PERFMON_START, 0);
296
297   /* Coarse-grained wait */
298   vlib_process_suspend (vm,
299                         ((f64) (vec_len (pm->events_to_collect)
300                                 * pm->timeout_interval)));
301
302   deadman = 0;
303   /* Reasonable to guess that collection may not be quite done... */
304   while (pm->state == PERFMON_STATE_RUNNING)
305     {
306       vlib_process_suspend (vm, 10e-3);
307       if (deadman++ > 200)
308         {
309           vlib_cli_output (vm, "DEADMAN: collection still running...");
310           break;
311         }
312     }
313
314   vlib_cli_output (vm, "Data collection complete...");
315   return 0;
316 }
317
318 /* *INDENT-OFF* */
319 VLIB_CLI_COMMAND (set_pmc_command, static) =
320 {
321   .path = "set pmc",
322   .short_help = "set pmc c1 [..., use \"show pmc events\"]",
323   .function = set_pmc_command_fn,
324   .is_mp_safe = 1,
325 };
326 /* *INDENT-ON* */
327
328 static int
329 capture_name_sort (void *a1, void *a2)
330 {
331   perfmon_capture_t *c1 = a1;
332   perfmon_capture_t *c2 = a2;
333
334   return strcmp ((char *) c1->thread_and_node_name,
335                  (char *) c2->thread_and_node_name);
336 }
337
338 static u8 *
339 format_capture (u8 * s, va_list * args)
340 {
341   perfmon_main_t *pm = va_arg (*args, perfmon_main_t *);
342   perfmon_capture_t *c = va_arg (*args, perfmon_capture_t *);
343   int verbose __attribute__ ((unused)) = va_arg (*args, int);
344   f64 ticks_per_pkt;
345   int i;
346
347   if (c == 0)
348     {
349       s = format (s, "%=40s%=20s%=16s%=16s%=16s",
350                   "Name", "Counter", "Count", "Pkts", "Counts/Pkt");
351       return s;
352     }
353
354   for (i = 0; i < vec_len (c->counter_names); i++)
355     {
356       u8 *name;
357
358       if (i == 0)
359         name = c->thread_and_node_name;
360       else
361         {
362           vec_add1 (s, '\n');
363           name = (u8 *) "";
364         }
365
366       /* Deal with synthetic events right here */
367       if (i == pm->ipc_event_index)
368         {
369           f64 ipc_rate;
370           ASSERT (i + 1 < vec_len (c->counter_names));
371
372           if (c->counter_values[i + 1] > 0)
373             ipc_rate = (f64) c->counter_values[i]
374               / (f64) c->counter_values[i + 1];
375           else
376             ipc_rate = 0.0;
377
378           s = format (s, "%-40s%+20s%+16llu%+16llu%+16.2e\n",
379                       name, "instructions-per-clock",
380                       c->counter_values[i],
381                       c->counter_values[i + 1], ipc_rate);
382           name = (u8 *) "";
383         }
384
385       if (i == pm->mispredict_event_index)
386         {
387           f64 mispredict_rate;
388           ASSERT (i + 1 < vec_len (c->counter_names));
389
390           if (c->counter_values[i + 1] > 0)
391             mispredict_rate = (f64) c->counter_values[i]
392               / (f64) c->counter_values[i + 1];
393           else
394             mispredict_rate = 0.0;
395
396           s = format (s, "%-40s%+20s%+16llu%+16llu%+16.2e\n",
397                       name, "branch-mispredict-rate",
398                       c->counter_values[i],
399                       c->counter_values[i + 1], mispredict_rate);
400           name = (u8 *) "";
401         }
402
403       if (c->vectors_this_counter[i])
404         ticks_per_pkt =
405           ((f64) c->counter_values[i]) / ((f64) c->vectors_this_counter[i]);
406       else
407         ticks_per_pkt = 0.0;
408
409       s = format (s, "%-40s%+20s%+16llu%+16llu%+16.2e",
410                   name, c->counter_names[i],
411                   c->counter_values[i],
412                   c->vectors_this_counter[i], ticks_per_pkt);
413     }
414   return s;
415 }
416
417 static u8 *
418 format_generic_events (u8 * s, va_list * args)
419 {
420   int verbose = va_arg (*args, int);
421
422 #define _(type,config,name)                             \
423   if (verbose == 0)                                     \
424     s = format (s, "\n  %s", name);                     \
425   else                                                  \
426     s = format (s, "\n  %s (%d, %d)", name, type, config);
427   foreach_perfmon_event;
428 #undef _
429   return s;
430 }
431
432 typedef struct
433 {
434   u8 *name;
435   name_value_pair_t **nvps;
436 } sort_nvp_t;
437
438 static int
439 sort_nvps_by_name (void *a1, void *a2)
440 {
441   sort_nvp_t *nvp1 = a1;
442   sort_nvp_t *nvp2 = a2;
443
444   return strcmp ((char *) nvp1->name, (char *) nvp2->name);
445 }
446
447 static u8 *
448 format_processor_events (u8 * s, va_list * args)
449 {
450   perfmon_main_t *pm = va_arg (*args, perfmon_main_t *);
451   int verbose = va_arg (*args, int);
452   int i, j;
453   sort_nvp_t *sort_nvps = 0;
454   sort_nvp_t *sn;
455   u8 *key;
456   name_value_pair_t **value;
457
458   /* *INDENT-OFF* */
459   hash_foreach_mem (key, value, pm->perfmon_table,
460   ({
461     vec_add2 (sort_nvps, sn, 1);
462     sn->name = key;
463     sn->nvps = value;
464   }));
465
466   vec_sort_with_function (sort_nvps, sort_nvps_by_name);
467
468   if (verbose == 0)
469     {
470       for (i = 0; i < vec_len (sort_nvps); i++)
471         s = format (s, "\n  %s ", sort_nvps[i].name);
472     }
473   else
474     {
475       for (i = 0; i < vec_len (sort_nvps); i++)
476         {
477           name_value_pair_t **nvps;
478           s = format (s, "\n  %s:", sort_nvps[i].name);
479
480           nvps = sort_nvps[i].nvps;
481
482           for (j = 0; j < vec_len (nvps); j++)
483             s = format (s, "\n    %s = %s", nvps[j]->name, nvps[j]->value);
484         }
485     }
486   vec_free (sort_nvps);
487   return s;
488 }
489
490
491 static clib_error_t *
492 show_pmc_command_fn (vlib_main_t * vm,
493                      unformat_input_t * input, vlib_cli_command_t * cmd)
494 {
495   perfmon_main_t *pm = &perfmon_main;
496   int verbose = 0;
497   int events = 0;
498   int i;
499   perfmon_capture_t *c;
500   perfmon_capture_t *captures = 0;
501
502   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
503     {
504       if (unformat (input, "events"))
505         events = 1;
506       else if (unformat (input, "verbose"))
507         verbose = 1;
508       else
509         break;
510     }
511
512   if (events)
513     {
514       vlib_cli_output (vm, "Generic Events %U",
515                        format_generic_events, verbose);
516       vlib_cli_output (vm, "Synthetic Events");
517       vlib_cli_output (vm, "  instructions-per-clock");
518       vlib_cli_output (vm, "  branch-mispredict-rate");
519       if (pm->perfmon_table)
520         vlib_cli_output (vm, "Processor Events %U",
521                          format_processor_events, pm, verbose);
522       return 0;
523     }
524
525   if (pm->state == PERFMON_STATE_RUNNING)
526     {
527       vlib_cli_output (vm, "Data collection in progress...");
528       return 0;
529     }
530
531   if (pool_elts (pm->capture_pool) == 0)
532     {
533       vlib_cli_output (vm, "No data...");
534       return 0;
535     }
536
537   /* *INDENT-OFF* */
538   pool_foreach (c, pm->capture_pool,
539   ({
540     vec_add1 (captures, *c);
541   }));
542   /* *INDENT-ON* */
543
544   vec_sort_with_function (captures, capture_name_sort);
545
546   vlib_cli_output (vm, "%U", format_capture, pm, 0 /* header */ ,
547                    0 /* verbose */ );
548
549   for (i = 0; i < vec_len (captures); i++)
550     {
551       c = captures + i;
552
553       vlib_cli_output (vm, "%U", format_capture, pm, c, verbose);
554     }
555
556   vec_free (captures);
557
558   return 0;
559 }
560
561 /* *INDENT-OFF* */
562 VLIB_CLI_COMMAND (show_pmc_command, static) =
563 {
564   .path = "show pmc",
565   .short_help = "show pmc [verbose]",
566   .function = show_pmc_command_fn,
567   .is_mp_safe = 1,
568 };
569 /* *INDENT-ON* */
570
571 static clib_error_t *
572 clear_pmc_command_fn (vlib_main_t * vm,
573                       unformat_input_t * input, vlib_cli_command_t * cmd)
574 {
575   perfmon_main_t *pm = &perfmon_main;
576   u8 *key;
577   u32 *value;
578
579   if (pm->state == PERFMON_STATE_RUNNING)
580     {
581       vlib_cli_output (vm, "Performance monitor is still running...");
582       return 0;
583     }
584
585   pool_free (pm->capture_pool);
586
587   /* *INDENT-OFF* */
588   hash_foreach_mem (key, value, pm->capture_by_thread_and_node_name,
589   ({
590     vec_free (key);
591   }));
592   /* *INDENT-ON* */
593   hash_free (pm->capture_by_thread_and_node_name);
594   pm->capture_by_thread_and_node_name =
595     hash_create_string (0, sizeof (uword));
596   return 0;
597 }
598
599 /* *INDENT-OFF* */
600 VLIB_CLI_COMMAND (clear_pmc_command, static) =
601 {
602   .path = "clear pmc",
603   .short_help = "clear the performance monitor counters",
604   .function = clear_pmc_command_fn,
605 };
606 /* *INDENT-ON* */
607
608
609 /*
610  * fd.io coding-style-patch-verification: ON
611  *
612  * Local Variables:
613  * eval: (c-set-style "gnu")
614  * End:
615  */