1 // SPDX-License-Identifier: GPL-2.0
5 #include "util/build-id.h"
6 #include "util/evsel.h"
7 #include "util/evlist.h"
9 #include "util/symbol.h"
10 #include "util/thread.h"
11 #include "util/header.h"
12 #include "util/session.h"
13 #include "util/intlist.h"
14 #include <subcmd/pager.h>
15 #include <subcmd/parse-options.h>
16 #include "util/trace-event.h"
17 #include "util/debug.h"
18 #include "util/tool.h"
19 #include "util/stat.h"
21 #include "util/data.h"
22 #include "util/ordered-events.h"
25 #include <sys/prctl.h>
26 #ifdef HAVE_TIMERFD_SUPPORT
27 #include <sys/timerfd.h>
30 #include <sys/types.h>
34 #include <linux/kernel.h>
35 #include <linux/string.h>
36 #include <linux/time64.h>
37 #include <linux/zalloc.h>
42 #include <semaphore.h>
46 static const char *get_filename_for_perf_kvm(void)
50 if (perf_host && !perf_guest)
51 filename = strdup("perf.data.host");
52 else if (!perf_host && perf_guest)
53 filename = strdup("perf.data.guest");
55 filename = strdup("perf.data.kvm");
60 #ifdef HAVE_KVM_STAT_SUPPORT
61 #include "util/kvm-stat.h"
63 void exit_event_get_key(struct evsel *evsel,
64 struct perf_sample *sample,
65 struct event_key *key)
68 key->key = perf_evsel__intval(evsel, sample, kvm_exit_reason);
71 bool kvm_exit_event(struct evsel *evsel)
73 return !strcmp(evsel->name, kvm_exit_trace);
76 bool exit_event_begin(struct evsel *evsel,
77 struct perf_sample *sample, struct event_key *key)
79 if (kvm_exit_event(evsel)) {
80 exit_event_get_key(evsel, sample, key);
87 bool kvm_entry_event(struct evsel *evsel)
89 return !strcmp(evsel->name, kvm_entry_trace);
92 bool exit_event_end(struct evsel *evsel,
93 struct perf_sample *sample __maybe_unused,
94 struct event_key *key __maybe_unused)
96 return kvm_entry_event(evsel);
99 static const char *get_exit_reason(struct perf_kvm_stat *kvm,
100 struct exit_reasons_table *tbl,
103 while (tbl->reason != NULL) {
104 if (tbl->exit_code == exit_code)
109 pr_err("unknown kvm exit code:%lld on %s\n",
110 (unsigned long long)exit_code, kvm->exit_reasons_isa);
114 void exit_event_decode_key(struct perf_kvm_stat *kvm,
115 struct event_key *key,
118 const char *exit_reason = get_exit_reason(kvm, key->exit_reasons,
121 scnprintf(decode, decode_str_len, "%s", exit_reason);
124 static bool register_kvm_events_ops(struct perf_kvm_stat *kvm)
126 struct kvm_reg_events_ops *events_ops = kvm_reg_events_ops;
128 for (events_ops = kvm_reg_events_ops; events_ops->name; events_ops++) {
129 if (!strcmp(events_ops->name, kvm->report_event)) {
130 kvm->events_ops = events_ops->ops;
138 struct vcpu_event_record {
141 struct kvm_event *last_event;
145 static void init_kvm_event_record(struct perf_kvm_stat *kvm)
149 for (i = 0; i < EVENTS_CACHE_SIZE; i++)
150 INIT_LIST_HEAD(&kvm->kvm_events_cache[i]);
153 #ifdef HAVE_TIMERFD_SUPPORT
154 static void clear_events_cache_stats(struct list_head *kvm_events_cache)
156 struct list_head *head;
157 struct kvm_event *event;
161 for (i = 0; i < EVENTS_CACHE_SIZE; i++) {
162 head = &kvm_events_cache[i];
163 list_for_each_entry(event, head, hash_entry) {
164 /* reset stats for event */
165 event->total.time = 0;
166 init_stats(&event->total.stats);
168 for (j = 0; j < event->max_vcpu; ++j) {
169 event->vcpu[j].time = 0;
170 init_stats(&event->vcpu[j].stats);
177 static int kvm_events_hash_fn(u64 key)
179 return key & (EVENTS_CACHE_SIZE - 1);
182 static bool kvm_event_expand(struct kvm_event *event, int vcpu_id)
184 int old_max_vcpu = event->max_vcpu;
187 if (vcpu_id < event->max_vcpu)
190 while (event->max_vcpu <= vcpu_id)
191 event->max_vcpu += DEFAULT_VCPU_NUM;
194 event->vcpu = realloc(event->vcpu,
195 event->max_vcpu * sizeof(*event->vcpu));
198 pr_err("Not enough memory\n");
202 memset(event->vcpu + old_max_vcpu, 0,
203 (event->max_vcpu - old_max_vcpu) * sizeof(*event->vcpu));
207 static struct kvm_event *kvm_alloc_init_event(struct event_key *key)
209 struct kvm_event *event;
211 event = zalloc(sizeof(*event));
213 pr_err("Not enough memory\n");
218 init_stats(&event->total.stats);
222 static struct kvm_event *find_create_kvm_event(struct perf_kvm_stat *kvm,
223 struct event_key *key)
225 struct kvm_event *event;
226 struct list_head *head;
228 BUG_ON(key->key == INVALID_KEY);
230 head = &kvm->kvm_events_cache[kvm_events_hash_fn(key->key)];
231 list_for_each_entry(event, head, hash_entry) {
232 if (event->key.key == key->key && event->key.info == key->info)
236 event = kvm_alloc_init_event(key);
240 list_add(&event->hash_entry, head);
244 static bool handle_begin_event(struct perf_kvm_stat *kvm,
245 struct vcpu_event_record *vcpu_record,
246 struct event_key *key, u64 timestamp)
248 struct kvm_event *event = NULL;
250 if (key->key != INVALID_KEY)
251 event = find_create_kvm_event(kvm, key);
253 vcpu_record->last_event = event;
254 vcpu_record->start_time = timestamp;
259 kvm_update_event_stats(struct kvm_event_stats *kvm_stats, u64 time_diff)
261 kvm_stats->time += time_diff;
262 update_stats(&kvm_stats->stats, time_diff);
265 static double kvm_event_rel_stddev(int vcpu_id, struct kvm_event *event)
267 struct kvm_event_stats *kvm_stats = &event->total;
270 kvm_stats = &event->vcpu[vcpu_id];
272 return rel_stddev_stats(stddev_stats(&kvm_stats->stats),
273 avg_stats(&kvm_stats->stats));
276 static bool update_kvm_event(struct kvm_event *event, int vcpu_id,
280 kvm_update_event_stats(&event->total, time_diff);
284 if (!kvm_event_expand(event, vcpu_id))
287 kvm_update_event_stats(&event->vcpu[vcpu_id], time_diff);
291 static bool is_child_event(struct perf_kvm_stat *kvm,
293 struct perf_sample *sample,
294 struct event_key *key)
296 struct child_event_ops *child_ops;
298 child_ops = kvm->events_ops->child_ops;
303 for (; child_ops->name; child_ops++) {
304 if (!strcmp(evsel->name, child_ops->name)) {
305 child_ops->get_key(evsel, sample, key);
313 static bool handle_child_event(struct perf_kvm_stat *kvm,
314 struct vcpu_event_record *vcpu_record,
315 struct event_key *key,
316 struct perf_sample *sample __maybe_unused)
318 struct kvm_event *event = NULL;
320 if (key->key != INVALID_KEY)
321 event = find_create_kvm_event(kvm, key);
323 vcpu_record->last_event = event;
328 static bool skip_event(const char *event)
330 const char * const *skip_events;
332 for (skip_events = kvm_skip_events; *skip_events; skip_events++)
333 if (!strcmp(event, *skip_events))
339 static bool handle_end_event(struct perf_kvm_stat *kvm,
340 struct vcpu_event_record *vcpu_record,
341 struct event_key *key,
342 struct perf_sample *sample)
344 struct kvm_event *event;
345 u64 time_begin, time_diff;
348 if (kvm->trace_vcpu == -1)
351 vcpu = vcpu_record->vcpu_id;
353 event = vcpu_record->last_event;
354 time_begin = vcpu_record->start_time;
356 /* The begin event is not caught. */
361 * In some case, the 'begin event' only records the start timestamp,
362 * the actual event is recognized in the 'end event' (e.g. mmio-event).
365 /* Both begin and end events did not get the key. */
366 if (!event && key->key == INVALID_KEY)
370 event = find_create_kvm_event(kvm, key);
375 vcpu_record->last_event = NULL;
376 vcpu_record->start_time = 0;
378 /* seems to happen once in a while during live mode */
379 if (sample->time < time_begin) {
380 pr_debug("End time before begin time; skipping event.\n");
384 time_diff = sample->time - time_begin;
386 if (kvm->duration && time_diff > kvm->duration) {
387 char decode[decode_str_len];
389 kvm->events_ops->decode_key(kvm, &event->key, decode);
390 if (!skip_event(decode)) {
391 pr_info("%" PRIu64 " VM %d, vcpu %d: %s event took %" PRIu64 "usec\n",
392 sample->time, sample->pid, vcpu_record->vcpu_id,
393 decode, time_diff / NSEC_PER_USEC);
397 return update_kvm_event(event, vcpu, time_diff);
401 struct vcpu_event_record *per_vcpu_record(struct thread *thread,
403 struct perf_sample *sample)
405 /* Only kvm_entry records vcpu id. */
406 if (!thread__priv(thread) && kvm_entry_event(evsel)) {
407 struct vcpu_event_record *vcpu_record;
409 vcpu_record = zalloc(sizeof(*vcpu_record));
411 pr_err("%s: Not enough memory\n", __func__);
415 vcpu_record->vcpu_id = perf_evsel__intval(evsel, sample,
417 thread__set_priv(thread, vcpu_record);
420 return thread__priv(thread);
423 static bool handle_kvm_event(struct perf_kvm_stat *kvm,
424 struct thread *thread,
426 struct perf_sample *sample)
428 struct vcpu_event_record *vcpu_record;
429 struct event_key key = { .key = INVALID_KEY,
430 .exit_reasons = kvm->exit_reasons };
432 vcpu_record = per_vcpu_record(thread, evsel, sample);
436 /* only process events for vcpus user cares about */
437 if ((kvm->trace_vcpu != -1) &&
438 (kvm->trace_vcpu != vcpu_record->vcpu_id))
441 if (kvm->events_ops->is_begin_event(evsel, sample, &key))
442 return handle_begin_event(kvm, vcpu_record, &key, sample->time);
444 if (is_child_event(kvm, evsel, sample, &key))
445 return handle_child_event(kvm, vcpu_record, &key, sample);
447 if (kvm->events_ops->is_end_event(evsel, sample, &key))
448 return handle_end_event(kvm, vcpu_record, &key, sample);
453 #define GET_EVENT_KEY(func, field) \
454 static u64 get_event_ ##func(struct kvm_event *event, int vcpu) \
457 return event->total.field; \
459 if (vcpu >= event->max_vcpu) \
462 return event->vcpu[vcpu].field; \
465 #define COMPARE_EVENT_KEY(func, field) \
466 GET_EVENT_KEY(func, field) \
467 static int compare_kvm_event_ ## func(struct kvm_event *one, \
468 struct kvm_event *two, int vcpu)\
470 return get_event_ ##func(one, vcpu) > \
471 get_event_ ##func(two, vcpu); \
474 GET_EVENT_KEY(time, time);
475 COMPARE_EVENT_KEY(count, stats.n);
476 COMPARE_EVENT_KEY(mean, stats.mean);
477 GET_EVENT_KEY(max, stats.max);
478 GET_EVENT_KEY(min, stats.min);
480 #define DEF_SORT_NAME_KEY(name, compare_key) \
481 { #name, compare_kvm_event_ ## compare_key }
483 static struct kvm_event_key keys[] = {
484 DEF_SORT_NAME_KEY(sample, count),
485 DEF_SORT_NAME_KEY(time, mean),
489 static bool select_key(struct perf_kvm_stat *kvm)
493 for (i = 0; keys[i].name; i++) {
494 if (!strcmp(keys[i].name, kvm->sort_key)) {
495 kvm->compare = keys[i].key;
500 pr_err("Unknown compare key:%s\n", kvm->sort_key);
504 static void insert_to_result(struct rb_root *result, struct kvm_event *event,
505 key_cmp_fun bigger, int vcpu)
507 struct rb_node **rb = &result->rb_node;
508 struct rb_node *parent = NULL;
512 p = container_of(*rb, struct kvm_event, rb);
515 if (bigger(event, p, vcpu))
516 rb = &(*rb)->rb_left;
518 rb = &(*rb)->rb_right;
521 rb_link_node(&event->rb, parent, rb);
522 rb_insert_color(&event->rb, result);
526 update_total_count(struct perf_kvm_stat *kvm, struct kvm_event *event)
528 int vcpu = kvm->trace_vcpu;
530 kvm->total_count += get_event_count(event, vcpu);
531 kvm->total_time += get_event_time(event, vcpu);
534 static bool event_is_valid(struct kvm_event *event, int vcpu)
536 return !!get_event_count(event, vcpu);
539 static void sort_result(struct perf_kvm_stat *kvm)
542 int vcpu = kvm->trace_vcpu;
543 struct kvm_event *event;
545 for (i = 0; i < EVENTS_CACHE_SIZE; i++) {
546 list_for_each_entry(event, &kvm->kvm_events_cache[i], hash_entry) {
547 if (event_is_valid(event, vcpu)) {
548 update_total_count(kvm, event);
549 insert_to_result(&kvm->result, event,
556 /* returns left most element of result, and erase it */
557 static struct kvm_event *pop_from_result(struct rb_root *result)
559 struct rb_node *node = rb_first(result);
564 rb_erase(node, result);
565 return container_of(node, struct kvm_event, rb);
568 static void print_vcpu_info(struct perf_kvm_stat *kvm)
570 int vcpu = kvm->trace_vcpu;
572 pr_info("Analyze events for ");
574 if (kvm->opts.target.system_wide)
575 pr_info("all VMs, ");
576 else if (kvm->opts.target.pid)
577 pr_info("pid(s) %s, ", kvm->opts.target.pid);
579 pr_info("dazed and confused on what is monitored, ");
582 pr_info("all VCPUs:\n\n");
584 pr_info("VCPU %d:\n\n", vcpu);
587 static void show_timeofday(void)
593 gettimeofday(&tv, NULL);
594 if (localtime_r(&tv.tv_sec, <ime)) {
595 strftime(date, sizeof(date), "%H:%M:%S", <ime);
596 pr_info("%s.%06ld", date, tv.tv_usec);
598 pr_info("00:00:00.000000");
603 static void print_result(struct perf_kvm_stat *kvm)
605 char decode[decode_str_len];
606 struct kvm_event *event;
607 int vcpu = kvm->trace_vcpu;
615 print_vcpu_info(kvm);
616 pr_info("%*s ", decode_str_len, kvm->events_ops->name);
617 pr_info("%10s ", "Samples");
618 pr_info("%9s ", "Samples%");
620 pr_info("%9s ", "Time%");
621 pr_info("%11s ", "Min Time");
622 pr_info("%11s ", "Max Time");
623 pr_info("%16s ", "Avg time");
626 while ((event = pop_from_result(&kvm->result))) {
627 u64 ecount, etime, max, min;
629 ecount = get_event_count(event, vcpu);
630 etime = get_event_time(event, vcpu);
631 max = get_event_max(event, vcpu);
632 min = get_event_min(event, vcpu);
634 kvm->events_ops->decode_key(kvm, &event->key, decode);
635 pr_info("%*s ", decode_str_len, decode);
636 pr_info("%10llu ", (unsigned long long)ecount);
637 pr_info("%8.2f%% ", (double)ecount / kvm->total_count * 100);
638 pr_info("%8.2f%% ", (double)etime / kvm->total_time * 100);
639 pr_info("%9.2fus ", (double)min / NSEC_PER_USEC);
640 pr_info("%9.2fus ", (double)max / NSEC_PER_USEC);
641 pr_info("%9.2fus ( +-%7.2f%% )", (double)etime / ecount / NSEC_PER_USEC,
642 kvm_event_rel_stddev(vcpu, event));
646 pr_info("\nTotal Samples:%" PRIu64 ", Total events handled time:%.2fus.\n\n",
647 kvm->total_count, kvm->total_time / (double)NSEC_PER_USEC);
649 if (kvm->lost_events)
650 pr_info("\nLost events: %" PRIu64 "\n\n", kvm->lost_events);
653 #ifdef HAVE_TIMERFD_SUPPORT
654 static int process_lost_event(struct perf_tool *tool,
655 union perf_event *event __maybe_unused,
656 struct perf_sample *sample __maybe_unused,
657 struct machine *machine __maybe_unused)
659 struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat, tool);
666 static bool skip_sample(struct perf_kvm_stat *kvm,
667 struct perf_sample *sample)
669 if (kvm->pid_list && intlist__find(kvm->pid_list, sample->pid) == NULL)
675 static int process_sample_event(struct perf_tool *tool,
676 union perf_event *event,
677 struct perf_sample *sample,
679 struct machine *machine)
682 struct thread *thread;
683 struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat,
686 if (skip_sample(kvm, sample))
689 thread = machine__findnew_thread(machine, sample->pid, sample->tid);
690 if (thread == NULL) {
691 pr_debug("problem processing %d event, skipping it.\n",
696 if (!handle_kvm_event(kvm, thread, evsel, sample))
703 static int cpu_isa_config(struct perf_kvm_stat *kvm)
705 char buf[64], *cpuid;
709 err = get_cpuid(buf, sizeof(buf));
711 pr_err("Failed to look up CPU type\n");
716 cpuid = kvm->session->header.env.cpuid;
719 pr_err("Failed to look up CPU type\n");
723 err = cpu_isa_init(kvm, cpuid);
725 pr_err("CPU %s is not supported.\n", cpuid);
730 static bool verify_vcpu(int vcpu)
732 if (vcpu != -1 && vcpu < 0) {
733 pr_err("Invalid vcpu:%d.\n", vcpu);
740 #ifdef HAVE_TIMERFD_SUPPORT
741 /* keeping the max events to a modest level to keep
742 * the processing of samples per mmap smooth.
744 #define PERF_KVM__MAX_EVENTS_PER_MMAP 25
746 static s64 perf_kvm__mmap_read_idx(struct perf_kvm_stat *kvm, int idx,
749 struct evlist *evlist = kvm->evlist;
750 union perf_event *event;
751 struct perf_mmap *md;
756 *mmap_time = ULLONG_MAX;
757 md = &evlist->mmap[idx];
758 err = perf_mmap__read_init(md);
760 return (err == -EAGAIN) ? 0 : -1;
762 while ((event = perf_mmap__read_event(md)) != NULL) {
763 err = perf_evlist__parse_sample_timestamp(evlist, event, ×tamp);
765 perf_mmap__consume(md);
766 pr_err("Failed to parse sample\n");
770 err = perf_session__queue_event(kvm->session, event, timestamp, 0);
772 * FIXME: Here we can't consume the event, as perf_session__queue_event will
773 * point to it, and it'll get possibly overwritten by the kernel.
775 perf_mmap__consume(md);
778 pr_err("Failed to enqueue sample: %d\n", err);
782 /* save time stamp of our first sample for this mmap */
784 *mmap_time = timestamp;
786 /* limit events per mmap handled all at once */
788 if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
792 perf_mmap__read_done(md);
796 static int perf_kvm__mmap_read(struct perf_kvm_stat *kvm)
798 int i, err, throttled = 0;
800 u64 flush_time = ULLONG_MAX, mmap_time;
802 for (i = 0; i < kvm->evlist->nr_mmaps; i++) {
803 n = perf_kvm__mmap_read_idx(kvm, i, &mmap_time);
807 /* flush time is going to be the minimum of all the individual
808 * mmap times. Essentially, we flush all the samples queued up
809 * from the last pass under our minimal start time -- that leaves
810 * a very small race for samples to come in with a lower timestamp.
811 * The ioctl to return the perf_clock timestamp should close the
814 if (mmap_time < flush_time)
815 flush_time = mmap_time;
818 if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
822 /* flush queue after each round in which we processed events */
824 struct ordered_events *oe = &kvm->session->ordered_events;
826 oe->next_flush = flush_time;
827 err = ordered_events__flush(oe, OE_FLUSH__ROUND);
829 if (kvm->lost_events)
830 pr_info("\nLost events: %" PRIu64 "\n\n",
839 static volatile int done;
841 static void sig_handler(int sig __maybe_unused)
846 static int perf_kvm__timerfd_create(struct perf_kvm_stat *kvm)
848 struct itimerspec new_value;
851 kvm->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
852 if (kvm->timerfd < 0) {
853 pr_err("timerfd_create failed\n");
857 new_value.it_value.tv_sec = kvm->display_time;
858 new_value.it_value.tv_nsec = 0;
859 new_value.it_interval.tv_sec = kvm->display_time;
860 new_value.it_interval.tv_nsec = 0;
862 if (timerfd_settime(kvm->timerfd, 0, &new_value, NULL) != 0) {
863 pr_err("timerfd_settime failed: %d\n", errno);
873 static int perf_kvm__handle_timerfd(struct perf_kvm_stat *kvm)
878 rc = read(kvm->timerfd, &c, sizeof(uint64_t));
883 pr_err("Failed to read timer fd: %d\n", errno);
887 if (rc != sizeof(uint64_t)) {
888 pr_err("Error reading timer fd - invalid size returned\n");
893 pr_debug("Missed timer beats: %" PRIu64 "\n", c-1);
900 clear_events_cache_stats(kvm->kvm_events_cache);
901 kvm->total_count = 0;
903 kvm->lost_events = 0;
908 static int fd_set_nonblock(int fd)
912 arg = fcntl(fd, F_GETFL);
914 pr_err("Failed to get current flags for fd %d\n", fd);
918 if (fcntl(fd, F_SETFL, arg | O_NONBLOCK) < 0) {
919 pr_err("Failed to set non-block option on fd %d\n", fd);
926 static int perf_kvm__handle_stdin(void)
937 static int kvm_events_live_report(struct perf_kvm_stat *kvm)
939 int nr_stdin, ret, err = -EINVAL;
942 /* live flag must be set first */
945 ret = cpu_isa_config(kvm);
949 if (!verify_vcpu(kvm->trace_vcpu) ||
951 !register_kvm_events_ops(kvm)) {
955 set_term_quiet_input(&save);
956 init_kvm_event_record(kvm);
958 signal(SIGINT, sig_handler);
959 signal(SIGTERM, sig_handler);
962 if (perf_kvm__timerfd_create(kvm) < 0) {
967 if (perf_evlist__add_pollfd(kvm->evlist, kvm->timerfd) < 0)
970 nr_stdin = perf_evlist__add_pollfd(kvm->evlist, fileno(stdin));
974 if (fd_set_nonblock(fileno(stdin)) != 0)
977 /* everything is good - enable the events and process */
978 evlist__enable(kvm->evlist);
981 struct fdarray *fda = &kvm->evlist->pollfd;
984 rc = perf_kvm__mmap_read(kvm);
988 err = perf_kvm__handle_timerfd(kvm);
992 if (fda->entries[nr_stdin].revents & POLLIN)
993 done = perf_kvm__handle_stdin();
996 err = fdarray__poll(fda, 100);
999 evlist__disable(kvm->evlist);
1007 if (kvm->timerfd >= 0)
1008 close(kvm->timerfd);
1010 tcsetattr(0, TCSAFLUSH, &save);
1014 static int kvm_live_open_events(struct perf_kvm_stat *kvm)
1018 struct evlist *evlist = kvm->evlist;
1019 char sbuf[STRERR_BUFSIZE];
1021 perf_evlist__config(evlist, &kvm->opts, NULL);
1024 * Note: exclude_{guest,host} do not apply here.
1025 * This command processes KVM tracepoints from host only
1027 evlist__for_each_entry(evlist, pos) {
1028 struct perf_event_attr *attr = &pos->core.attr;
1030 /* make sure these *are* set */
1031 perf_evsel__set_sample_bit(pos, TID);
1032 perf_evsel__set_sample_bit(pos, TIME);
1033 perf_evsel__set_sample_bit(pos, CPU);
1034 perf_evsel__set_sample_bit(pos, RAW);
1035 /* make sure these are *not*; want as small a sample as possible */
1036 perf_evsel__reset_sample_bit(pos, PERIOD);
1037 perf_evsel__reset_sample_bit(pos, IP);
1038 perf_evsel__reset_sample_bit(pos, CALLCHAIN);
1039 perf_evsel__reset_sample_bit(pos, ADDR);
1040 perf_evsel__reset_sample_bit(pos, READ);
1045 attr->sample_period = 1;
1047 attr->watermark = 0;
1048 attr->wakeup_events = 1000;
1050 /* will enable all once we are ready */
1054 err = evlist__open(evlist);
1056 printf("Couldn't create the events: %s\n",
1057 str_error_r(errno, sbuf, sizeof(sbuf)));
1061 if (perf_evlist__mmap(evlist, kvm->opts.mmap_pages) < 0) {
1062 ui__error("Failed to mmap the events: %s\n",
1063 str_error_r(errno, sbuf, sizeof(sbuf)));
1064 evlist__close(evlist);
1075 static int read_events(struct perf_kvm_stat *kvm)
1079 struct perf_tool eops = {
1080 .sample = process_sample_event,
1081 .comm = perf_event__process_comm,
1082 .namespaces = perf_event__process_namespaces,
1083 .ordered_events = true,
1085 struct perf_data file = {
1086 .path = kvm->file_name,
1087 .mode = PERF_DATA_MODE_READ,
1088 .force = kvm->force,
1092 kvm->session = perf_session__new(&file, false, &kvm->tool);
1093 if (!kvm->session) {
1094 pr_err("Initializing perf session failed\n");
1098 symbol__init(&kvm->session->header.env);
1100 if (!perf_session__has_traces(kvm->session, "kvm record")) {
1106 * Do not use 'isa' recorded in kvm_exit tracepoint since it is not
1107 * traced in the old kernel.
1109 ret = cpu_isa_config(kvm);
1113 ret = perf_session__process_events(kvm->session);
1116 perf_session__delete(kvm->session);
1120 static int parse_target_str(struct perf_kvm_stat *kvm)
1122 if (kvm->opts.target.pid) {
1123 kvm->pid_list = intlist__new(kvm->opts.target.pid);
1124 if (kvm->pid_list == NULL) {
1125 pr_err("Error parsing process id string\n");
1133 static int kvm_events_report_vcpu(struct perf_kvm_stat *kvm)
1136 int vcpu = kvm->trace_vcpu;
1138 if (parse_target_str(kvm) != 0)
1141 if (!verify_vcpu(vcpu))
1144 if (!select_key(kvm))
1147 if (!register_kvm_events_ops(kvm))
1150 init_kvm_event_record(kvm);
1153 ret = read_events(kvm);
1164 #define STRDUP_FAIL_EXIT(s) \
1172 int __weak setup_kvm_events_tp(struct perf_kvm_stat *kvm __maybe_unused)
1178 kvm_events_record(struct perf_kvm_stat *kvm, int argc, const char **argv)
1180 unsigned int rec_argc, i, j, events_tp_size;
1181 const char **rec_argv;
1182 const char * const record_args[] = {
1188 const char * const kvm_stat_record_usage[] = {
1189 "perf kvm stat record [<options>]",
1192 const char * const *events_tp;
1196 ret = setup_kvm_events_tp(kvm);
1198 pr_err("Unable to setup the kvm tracepoints\n");
1202 for (events_tp = kvm_events_tp; *events_tp; events_tp++)
1205 rec_argc = ARRAY_SIZE(record_args) + argc + 2 +
1207 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1209 if (rec_argv == NULL)
1212 for (i = 0; i < ARRAY_SIZE(record_args); i++)
1213 rec_argv[i] = STRDUP_FAIL_EXIT(record_args[i]);
1215 for (j = 0; j < events_tp_size; j++) {
1216 rec_argv[i++] = "-e";
1217 rec_argv[i++] = STRDUP_FAIL_EXIT(kvm_events_tp[j]);
1220 rec_argv[i++] = STRDUP_FAIL_EXIT("-o");
1221 rec_argv[i++] = STRDUP_FAIL_EXIT(kvm->file_name);
1223 for (j = 1; j < (unsigned int)argc; j++, i++)
1224 rec_argv[i] = argv[j];
1226 set_option_flag(record_options, 'e', "event", PARSE_OPT_HIDDEN);
1227 set_option_flag(record_options, 0, "filter", PARSE_OPT_HIDDEN);
1228 set_option_flag(record_options, 'R', "raw-samples", PARSE_OPT_HIDDEN);
1230 set_option_flag(record_options, 'F', "freq", PARSE_OPT_DISABLED);
1231 set_option_flag(record_options, 0, "group", PARSE_OPT_DISABLED);
1232 set_option_flag(record_options, 'g', NULL, PARSE_OPT_DISABLED);
1233 set_option_flag(record_options, 0, "call-graph", PARSE_OPT_DISABLED);
1234 set_option_flag(record_options, 'd', "data", PARSE_OPT_DISABLED);
1235 set_option_flag(record_options, 'T', "timestamp", PARSE_OPT_DISABLED);
1236 set_option_flag(record_options, 'P', "period", PARSE_OPT_DISABLED);
1237 set_option_flag(record_options, 'n', "no-samples", PARSE_OPT_DISABLED);
1238 set_option_flag(record_options, 'N', "no-buildid-cache", PARSE_OPT_DISABLED);
1239 set_option_flag(record_options, 'B', "no-buildid", PARSE_OPT_DISABLED);
1240 set_option_flag(record_options, 'G', "cgroup", PARSE_OPT_DISABLED);
1241 set_option_flag(record_options, 'b', "branch-any", PARSE_OPT_DISABLED);
1242 set_option_flag(record_options, 'j', "branch-filter", PARSE_OPT_DISABLED);
1243 set_option_flag(record_options, 'W', "weight", PARSE_OPT_DISABLED);
1244 set_option_flag(record_options, 0, "transaction", PARSE_OPT_DISABLED);
1246 record_usage = kvm_stat_record_usage;
1247 return cmd_record(i, rec_argv);
1251 kvm_events_report(struct perf_kvm_stat *kvm, int argc, const char **argv)
1253 const struct option kvm_events_report_options[] = {
1254 OPT_STRING(0, "event", &kvm->report_event, "report event",
1255 "event for reporting: vmexit, "
1256 "mmio (x86 only), ioport (x86 only)"),
1257 OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
1258 "vcpu id to report"),
1259 OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
1260 "key for sorting: sample(sort by samples number)"
1261 " time (sort by avg time)"),
1262 OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
1263 "analyze events only for given process id(s)"),
1264 OPT_BOOLEAN('f', "force", &kvm->force, "don't complain, do it"),
1268 const char * const kvm_events_report_usage[] = {
1269 "perf kvm stat report [<options>]",
1274 argc = parse_options(argc, argv,
1275 kvm_events_report_options,
1276 kvm_events_report_usage, 0);
1278 usage_with_options(kvm_events_report_usage,
1279 kvm_events_report_options);
1282 if (!kvm->opts.target.pid)
1283 kvm->opts.target.system_wide = true;
1285 return kvm_events_report_vcpu(kvm);
1288 #ifdef HAVE_TIMERFD_SUPPORT
1289 static struct evlist *kvm_live_event_list(void)
1291 struct evlist *evlist;
1292 char *tp, *name, *sys;
1294 const char * const *events_tp;
1296 evlist = evlist__new();
1300 for (events_tp = kvm_events_tp; *events_tp; events_tp++) {
1302 tp = strdup(*events_tp);
1306 /* split tracepoint into subsystem and name */
1308 name = strchr(tp, ':');
1310 pr_err("Error parsing %s tracepoint: subsystem delimiter not found\n",
1318 if (perf_evlist__add_newtp(evlist, sys, name, NULL)) {
1319 pr_err("Failed to add %s tracepoint to the list\n", *events_tp);
1331 evlist__delete(evlist);
1338 static int kvm_events_live(struct perf_kvm_stat *kvm,
1339 int argc, const char **argv)
1341 char errbuf[BUFSIZ];
1344 const struct option live_options[] = {
1345 OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
1346 "record events on existing process id"),
1347 OPT_CALLBACK('m', "mmap-pages", &kvm->opts.mmap_pages, "pages",
1348 "number of mmap data pages",
1349 perf_evlist__parse_mmap_pages),
1350 OPT_INCR('v', "verbose", &verbose,
1351 "be more verbose (show counter open errors, etc)"),
1352 OPT_BOOLEAN('a', "all-cpus", &kvm->opts.target.system_wide,
1353 "system-wide collection from all CPUs"),
1354 OPT_UINTEGER('d', "display", &kvm->display_time,
1355 "time in seconds between display updates"),
1356 OPT_STRING(0, "event", &kvm->report_event, "report event",
1357 "event for reporting: "
1358 "vmexit, mmio (x86 only), ioport (x86 only)"),
1359 OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
1360 "vcpu id to report"),
1361 OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
1362 "key for sorting: sample(sort by samples number)"
1363 " time (sort by avg time)"),
1364 OPT_U64(0, "duration", &kvm->duration,
1365 "show events other than"
1366 " HLT (x86 only) or Wait state (s390 only)"
1367 " that take longer than duration usecs"),
1368 OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout,
1369 "per thread proc mmap processing timeout in ms"),
1372 const char * const live_usage[] = {
1373 "perf kvm stat live [<options>]",
1376 struct perf_data data = {
1377 .mode = PERF_DATA_MODE_WRITE,
1381 /* event handling */
1382 kvm->tool.sample = process_sample_event;
1383 kvm->tool.comm = perf_event__process_comm;
1384 kvm->tool.exit = perf_event__process_exit;
1385 kvm->tool.fork = perf_event__process_fork;
1386 kvm->tool.lost = process_lost_event;
1387 kvm->tool.namespaces = perf_event__process_namespaces;
1388 kvm->tool.ordered_events = true;
1389 perf_tool__fill_defaults(&kvm->tool);
1392 kvm->display_time = 1;
1393 kvm->opts.user_interval = 1;
1394 kvm->opts.mmap_pages = 512;
1395 kvm->opts.target.uses_mmap = false;
1396 kvm->opts.target.uid_str = NULL;
1397 kvm->opts.target.uid = UINT_MAX;
1400 disable_buildid_cache();
1405 argc = parse_options(argc, argv, live_options,
1408 usage_with_options(live_usage, live_options);
1411 kvm->duration *= NSEC_PER_USEC; /* convert usec to nsec */
1414 * target related setups
1416 err = target__validate(&kvm->opts.target);
1418 target__strerror(&kvm->opts.target, err, errbuf, BUFSIZ);
1419 ui__warning("%s", errbuf);
1422 if (target__none(&kvm->opts.target))
1423 kvm->opts.target.system_wide = true;
1427 * generate the event list
1429 err = setup_kvm_events_tp(kvm);
1431 pr_err("Unable to setup the kvm tracepoints\n");
1435 kvm->evlist = kvm_live_event_list();
1436 if (kvm->evlist == NULL) {
1441 if (perf_evlist__create_maps(kvm->evlist, &kvm->opts.target) < 0)
1442 usage_with_options(live_usage, live_options);
1447 kvm->session = perf_session__new(&data, false, &kvm->tool);
1448 if (kvm->session == NULL) {
1452 kvm->session->evlist = kvm->evlist;
1453 perf_session__set_id_hdr_size(kvm->session);
1454 ordered_events__set_copy_on_queue(&kvm->session->ordered_events, true);
1455 machine__synthesize_threads(&kvm->session->machines.host, &kvm->opts.target,
1456 kvm->evlist->core.threads, false, 1);
1457 err = kvm_live_open_events(kvm);
1461 err = kvm_events_live_report(kvm);
1464 perf_session__delete(kvm->session);
1465 kvm->session = NULL;
1466 evlist__delete(kvm->evlist);
1472 static void print_kvm_stat_usage(void)
1474 printf("Usage: perf kvm stat <command>\n\n");
1476 printf("# Available commands:\n");
1477 printf("\trecord: record kvm events\n");
1478 printf("\treport: report statistical data of kvm events\n");
1479 printf("\tlive: live reporting of statistical data of kvm events\n");
1481 printf("\nOtherwise, it is the alias of 'perf stat':\n");
1484 static int kvm_cmd_stat(const char *file_name, int argc, const char **argv)
1486 struct perf_kvm_stat kvm = {
1487 .file_name = file_name,
1490 .report_event = "vmexit",
1491 .sort_key = "sample",
1496 print_kvm_stat_usage();
1500 if (!strncmp(argv[1], "rec", 3))
1501 return kvm_events_record(&kvm, argc - 1, argv + 1);
1503 if (!strncmp(argv[1], "rep", 3))
1504 return kvm_events_report(&kvm, argc - 1 , argv + 1);
1506 #ifdef HAVE_TIMERFD_SUPPORT
1507 if (!strncmp(argv[1], "live", 4))
1508 return kvm_events_live(&kvm, argc - 1 , argv + 1);
1512 return cmd_stat(argc, argv);
1514 #endif /* HAVE_KVM_STAT_SUPPORT */
1516 static int __cmd_record(const char *file_name, int argc, const char **argv)
1518 int rec_argc, i = 0, j;
1519 const char **rec_argv;
1521 rec_argc = argc + 2;
1522 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1523 rec_argv[i++] = strdup("record");
1524 rec_argv[i++] = strdup("-o");
1525 rec_argv[i++] = strdup(file_name);
1526 for (j = 1; j < argc; j++, i++)
1527 rec_argv[i] = argv[j];
1529 BUG_ON(i != rec_argc);
1531 return cmd_record(i, rec_argv);
1534 static int __cmd_report(const char *file_name, int argc, const char **argv)
1536 int rec_argc, i = 0, j;
1537 const char **rec_argv;
1539 rec_argc = argc + 2;
1540 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1541 rec_argv[i++] = strdup("report");
1542 rec_argv[i++] = strdup("-i");
1543 rec_argv[i++] = strdup(file_name);
1544 for (j = 1; j < argc; j++, i++)
1545 rec_argv[i] = argv[j];
1547 BUG_ON(i != rec_argc);
1549 return cmd_report(i, rec_argv);
1553 __cmd_buildid_list(const char *file_name, int argc, const char **argv)
1555 int rec_argc, i = 0, j;
1556 const char **rec_argv;
1558 rec_argc = argc + 2;
1559 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1560 rec_argv[i++] = strdup("buildid-list");
1561 rec_argv[i++] = strdup("-i");
1562 rec_argv[i++] = strdup(file_name);
1563 for (j = 1; j < argc; j++, i++)
1564 rec_argv[i] = argv[j];
1566 BUG_ON(i != rec_argc);
1568 return cmd_buildid_list(i, rec_argv);
1571 int cmd_kvm(int argc, const char **argv)
1573 const char *file_name = NULL;
1574 const struct option kvm_options[] = {
1575 OPT_STRING('i', "input", &file_name, "file",
1577 OPT_STRING('o', "output", &file_name, "file",
1578 "Output file name"),
1579 OPT_BOOLEAN(0, "guest", &perf_guest,
1580 "Collect guest os data"),
1581 OPT_BOOLEAN(0, "host", &perf_host,
1582 "Collect host os data"),
1583 OPT_STRING(0, "guestmount", &symbol_conf.guestmount, "directory",
1584 "guest mount directory under which every guest os"
1585 " instance has a subdir"),
1586 OPT_STRING(0, "guestvmlinux", &symbol_conf.default_guest_vmlinux_name,
1587 "file", "file saving guest os vmlinux"),
1588 OPT_STRING(0, "guestkallsyms", &symbol_conf.default_guest_kallsyms,
1589 "file", "file saving guest os /proc/kallsyms"),
1590 OPT_STRING(0, "guestmodules", &symbol_conf.default_guest_modules,
1591 "file", "file saving guest os /proc/modules"),
1592 OPT_INCR('v', "verbose", &verbose,
1593 "be more verbose (show counter open errors, etc)"),
1597 const char *const kvm_subcommands[] = { "top", "record", "report", "diff",
1598 "buildid-list", "stat", NULL };
1599 const char *kvm_usage[] = { NULL, NULL };
1604 argc = parse_options_subcommand(argc, argv, kvm_options, kvm_subcommands, kvm_usage,
1605 PARSE_OPT_STOP_AT_NON_OPTION);
1607 usage_with_options(kvm_usage, kvm_options);
1613 file_name = get_filename_for_perf_kvm();
1616 pr_err("Failed to allocate memory for filename\n");
1621 if (!strncmp(argv[0], "rec", 3))
1622 return __cmd_record(file_name, argc, argv);
1623 else if (!strncmp(argv[0], "rep", 3))
1624 return __cmd_report(file_name, argc, argv);
1625 else if (!strncmp(argv[0], "diff", 4))
1626 return cmd_diff(argc, argv);
1627 else if (!strncmp(argv[0], "top", 3))
1628 return cmd_top(argc, argv);
1629 else if (!strncmp(argv[0], "buildid-list", 12))
1630 return __cmd_buildid_list(file_name, argc, argv);
1631 #ifdef HAVE_KVM_STAT_SUPPORT
1632 else if (!strncmp(argv[0], "stat", 4))
1633 return kvm_cmd_stat(file_name, argc, argv);
1636 usage_with_options(kvm_usage, kvm_options);