4 #include "util/evsel.h"
5 #include "util/evlist.h"
8 #include "util/cache.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/parse-options.h>
15 #include "util/trace-event.h"
16 #include "util/debug.h"
17 #include "util/tool.h"
18 #include "util/stat.h"
20 #include "util/data.h"
21 #include "util/ordered-events.h"
23 #include <sys/prctl.h>
24 #ifdef HAVE_TIMERFD_SUPPORT
25 #include <sys/timerfd.h>
29 #include <linux/kernel.h>
30 #include <linux/time64.h>
35 #include <semaphore.h>
40 static const char *get_filename_for_perf_kvm(void)
44 if (perf_host && !perf_guest)
45 filename = strdup("perf.data.host");
46 else if (!perf_host && perf_guest)
47 filename = strdup("perf.data.guest");
49 filename = strdup("perf.data.kvm");
54 #ifdef HAVE_KVM_STAT_SUPPORT
55 #include "util/kvm-stat.h"
57 void exit_event_get_key(struct perf_evsel *evsel,
58 struct perf_sample *sample,
59 struct event_key *key)
62 key->key = perf_evsel__intval(evsel, sample, kvm_exit_reason);
65 bool kvm_exit_event(struct perf_evsel *evsel)
67 return !strcmp(evsel->name, kvm_exit_trace);
70 bool exit_event_begin(struct perf_evsel *evsel,
71 struct perf_sample *sample, struct event_key *key)
73 if (kvm_exit_event(evsel)) {
74 exit_event_get_key(evsel, sample, key);
81 bool kvm_entry_event(struct perf_evsel *evsel)
83 return !strcmp(evsel->name, kvm_entry_trace);
86 bool exit_event_end(struct perf_evsel *evsel,
87 struct perf_sample *sample __maybe_unused,
88 struct event_key *key __maybe_unused)
90 return kvm_entry_event(evsel);
93 static const char *get_exit_reason(struct perf_kvm_stat *kvm,
94 struct exit_reasons_table *tbl,
97 while (tbl->reason != NULL) {
98 if (tbl->exit_code == exit_code)
103 pr_err("unknown kvm exit code:%lld on %s\n",
104 (unsigned long long)exit_code, kvm->exit_reasons_isa);
108 void exit_event_decode_key(struct perf_kvm_stat *kvm,
109 struct event_key *key,
112 const char *exit_reason = get_exit_reason(kvm, key->exit_reasons,
115 scnprintf(decode, decode_str_len, "%s", exit_reason);
118 static bool register_kvm_events_ops(struct perf_kvm_stat *kvm)
120 struct kvm_reg_events_ops *events_ops = kvm_reg_events_ops;
122 for (events_ops = kvm_reg_events_ops; events_ops->name; events_ops++) {
123 if (!strcmp(events_ops->name, kvm->report_event)) {
124 kvm->events_ops = events_ops->ops;
132 struct vcpu_event_record {
135 struct kvm_event *last_event;
139 static void init_kvm_event_record(struct perf_kvm_stat *kvm)
143 for (i = 0; i < EVENTS_CACHE_SIZE; i++)
144 INIT_LIST_HEAD(&kvm->kvm_events_cache[i]);
147 #ifdef HAVE_TIMERFD_SUPPORT
148 static void clear_events_cache_stats(struct list_head *kvm_events_cache)
150 struct list_head *head;
151 struct kvm_event *event;
155 for (i = 0; i < EVENTS_CACHE_SIZE; i++) {
156 head = &kvm_events_cache[i];
157 list_for_each_entry(event, head, hash_entry) {
158 /* reset stats for event */
159 event->total.time = 0;
160 init_stats(&event->total.stats);
162 for (j = 0; j < event->max_vcpu; ++j) {
163 event->vcpu[j].time = 0;
164 init_stats(&event->vcpu[j].stats);
171 static int kvm_events_hash_fn(u64 key)
173 return key & (EVENTS_CACHE_SIZE - 1);
176 static bool kvm_event_expand(struct kvm_event *event, int vcpu_id)
178 int old_max_vcpu = event->max_vcpu;
181 if (vcpu_id < event->max_vcpu)
184 while (event->max_vcpu <= vcpu_id)
185 event->max_vcpu += DEFAULT_VCPU_NUM;
188 event->vcpu = realloc(event->vcpu,
189 event->max_vcpu * sizeof(*event->vcpu));
192 pr_err("Not enough memory\n");
196 memset(event->vcpu + old_max_vcpu, 0,
197 (event->max_vcpu - old_max_vcpu) * sizeof(*event->vcpu));
201 static struct kvm_event *kvm_alloc_init_event(struct event_key *key)
203 struct kvm_event *event;
205 event = zalloc(sizeof(*event));
207 pr_err("Not enough memory\n");
212 init_stats(&event->total.stats);
216 static struct kvm_event *find_create_kvm_event(struct perf_kvm_stat *kvm,
217 struct event_key *key)
219 struct kvm_event *event;
220 struct list_head *head;
222 BUG_ON(key->key == INVALID_KEY);
224 head = &kvm->kvm_events_cache[kvm_events_hash_fn(key->key)];
225 list_for_each_entry(event, head, hash_entry) {
226 if (event->key.key == key->key && event->key.info == key->info)
230 event = kvm_alloc_init_event(key);
234 list_add(&event->hash_entry, head);
238 static bool handle_begin_event(struct perf_kvm_stat *kvm,
239 struct vcpu_event_record *vcpu_record,
240 struct event_key *key, u64 timestamp)
242 struct kvm_event *event = NULL;
244 if (key->key != INVALID_KEY)
245 event = find_create_kvm_event(kvm, key);
247 vcpu_record->last_event = event;
248 vcpu_record->start_time = timestamp;
253 kvm_update_event_stats(struct kvm_event_stats *kvm_stats, u64 time_diff)
255 kvm_stats->time += time_diff;
256 update_stats(&kvm_stats->stats, time_diff);
259 static double kvm_event_rel_stddev(int vcpu_id, struct kvm_event *event)
261 struct kvm_event_stats *kvm_stats = &event->total;
264 kvm_stats = &event->vcpu[vcpu_id];
266 return rel_stddev_stats(stddev_stats(&kvm_stats->stats),
267 avg_stats(&kvm_stats->stats));
270 static bool update_kvm_event(struct kvm_event *event, int vcpu_id,
274 kvm_update_event_stats(&event->total, time_diff);
278 if (!kvm_event_expand(event, vcpu_id))
281 kvm_update_event_stats(&event->vcpu[vcpu_id], time_diff);
285 static bool is_child_event(struct perf_kvm_stat *kvm,
286 struct perf_evsel *evsel,
287 struct perf_sample *sample,
288 struct event_key *key)
290 struct child_event_ops *child_ops;
292 child_ops = kvm->events_ops->child_ops;
297 for (; child_ops->name; child_ops++) {
298 if (!strcmp(evsel->name, child_ops->name)) {
299 child_ops->get_key(evsel, sample, key);
307 static bool handle_child_event(struct perf_kvm_stat *kvm,
308 struct vcpu_event_record *vcpu_record,
309 struct event_key *key,
310 struct perf_sample *sample __maybe_unused)
312 struct kvm_event *event = NULL;
314 if (key->key != INVALID_KEY)
315 event = find_create_kvm_event(kvm, key);
317 vcpu_record->last_event = event;
322 static bool skip_event(const char *event)
324 const char * const *skip_events;
326 for (skip_events = kvm_skip_events; *skip_events; skip_events++)
327 if (!strcmp(event, *skip_events))
333 static bool handle_end_event(struct perf_kvm_stat *kvm,
334 struct vcpu_event_record *vcpu_record,
335 struct event_key *key,
336 struct perf_sample *sample)
338 struct kvm_event *event;
339 u64 time_begin, time_diff;
342 if (kvm->trace_vcpu == -1)
345 vcpu = vcpu_record->vcpu_id;
347 event = vcpu_record->last_event;
348 time_begin = vcpu_record->start_time;
350 /* The begin event is not caught. */
355 * In some case, the 'begin event' only records the start timestamp,
356 * the actual event is recognized in the 'end event' (e.g. mmio-event).
359 /* Both begin and end events did not get the key. */
360 if (!event && key->key == INVALID_KEY)
364 event = find_create_kvm_event(kvm, key);
369 vcpu_record->last_event = NULL;
370 vcpu_record->start_time = 0;
372 /* seems to happen once in a while during live mode */
373 if (sample->time < time_begin) {
374 pr_debug("End time before begin time; skipping event.\n");
378 time_diff = sample->time - time_begin;
380 if (kvm->duration && time_diff > kvm->duration) {
381 char decode[decode_str_len];
383 kvm->events_ops->decode_key(kvm, &event->key, decode);
384 if (!skip_event(decode)) {
385 pr_info("%" PRIu64 " VM %d, vcpu %d: %s event took %" PRIu64 "usec\n",
386 sample->time, sample->pid, vcpu_record->vcpu_id,
387 decode, time_diff / NSEC_PER_USEC);
391 return update_kvm_event(event, vcpu, time_diff);
395 struct vcpu_event_record *per_vcpu_record(struct thread *thread,
396 struct perf_evsel *evsel,
397 struct perf_sample *sample)
399 /* Only kvm_entry records vcpu id. */
400 if (!thread__priv(thread) && kvm_entry_event(evsel)) {
401 struct vcpu_event_record *vcpu_record;
403 vcpu_record = zalloc(sizeof(*vcpu_record));
405 pr_err("%s: Not enough memory\n", __func__);
409 vcpu_record->vcpu_id = perf_evsel__intval(evsel, sample,
411 thread__set_priv(thread, vcpu_record);
414 return thread__priv(thread);
417 static bool handle_kvm_event(struct perf_kvm_stat *kvm,
418 struct thread *thread,
419 struct perf_evsel *evsel,
420 struct perf_sample *sample)
422 struct vcpu_event_record *vcpu_record;
423 struct event_key key = { .key = INVALID_KEY,
424 .exit_reasons = kvm->exit_reasons };
426 vcpu_record = per_vcpu_record(thread, evsel, sample);
430 /* only process events for vcpus user cares about */
431 if ((kvm->trace_vcpu != -1) &&
432 (kvm->trace_vcpu != vcpu_record->vcpu_id))
435 if (kvm->events_ops->is_begin_event(evsel, sample, &key))
436 return handle_begin_event(kvm, vcpu_record, &key, sample->time);
438 if (is_child_event(kvm, evsel, sample, &key))
439 return handle_child_event(kvm, vcpu_record, &key, sample);
441 if (kvm->events_ops->is_end_event(evsel, sample, &key))
442 return handle_end_event(kvm, vcpu_record, &key, sample);
447 #define GET_EVENT_KEY(func, field) \
448 static u64 get_event_ ##func(struct kvm_event *event, int vcpu) \
451 return event->total.field; \
453 if (vcpu >= event->max_vcpu) \
456 return event->vcpu[vcpu].field; \
459 #define COMPARE_EVENT_KEY(func, field) \
460 GET_EVENT_KEY(func, field) \
461 static int compare_kvm_event_ ## func(struct kvm_event *one, \
462 struct kvm_event *two, int vcpu)\
464 return get_event_ ##func(one, vcpu) > \
465 get_event_ ##func(two, vcpu); \
468 GET_EVENT_KEY(time, time);
469 COMPARE_EVENT_KEY(count, stats.n);
470 COMPARE_EVENT_KEY(mean, stats.mean);
471 GET_EVENT_KEY(max, stats.max);
472 GET_EVENT_KEY(min, stats.min);
474 #define DEF_SORT_NAME_KEY(name, compare_key) \
475 { #name, compare_kvm_event_ ## compare_key }
477 static struct kvm_event_key keys[] = {
478 DEF_SORT_NAME_KEY(sample, count),
479 DEF_SORT_NAME_KEY(time, mean),
483 static bool select_key(struct perf_kvm_stat *kvm)
487 for (i = 0; keys[i].name; i++) {
488 if (!strcmp(keys[i].name, kvm->sort_key)) {
489 kvm->compare = keys[i].key;
494 pr_err("Unknown compare key:%s\n", kvm->sort_key);
498 static void insert_to_result(struct rb_root *result, struct kvm_event *event,
499 key_cmp_fun bigger, int vcpu)
501 struct rb_node **rb = &result->rb_node;
502 struct rb_node *parent = NULL;
506 p = container_of(*rb, struct kvm_event, rb);
509 if (bigger(event, p, vcpu))
510 rb = &(*rb)->rb_left;
512 rb = &(*rb)->rb_right;
515 rb_link_node(&event->rb, parent, rb);
516 rb_insert_color(&event->rb, result);
520 update_total_count(struct perf_kvm_stat *kvm, struct kvm_event *event)
522 int vcpu = kvm->trace_vcpu;
524 kvm->total_count += get_event_count(event, vcpu);
525 kvm->total_time += get_event_time(event, vcpu);
528 static bool event_is_valid(struct kvm_event *event, int vcpu)
530 return !!get_event_count(event, vcpu);
533 static void sort_result(struct perf_kvm_stat *kvm)
536 int vcpu = kvm->trace_vcpu;
537 struct kvm_event *event;
539 for (i = 0; i < EVENTS_CACHE_SIZE; i++) {
540 list_for_each_entry(event, &kvm->kvm_events_cache[i], hash_entry) {
541 if (event_is_valid(event, vcpu)) {
542 update_total_count(kvm, event);
543 insert_to_result(&kvm->result, event,
550 /* returns left most element of result, and erase it */
551 static struct kvm_event *pop_from_result(struct rb_root *result)
553 struct rb_node *node = rb_first(result);
558 rb_erase(node, result);
559 return container_of(node, struct kvm_event, rb);
562 static void print_vcpu_info(struct perf_kvm_stat *kvm)
564 int vcpu = kvm->trace_vcpu;
566 pr_info("Analyze events for ");
568 if (kvm->opts.target.system_wide)
569 pr_info("all VMs, ");
570 else if (kvm->opts.target.pid)
571 pr_info("pid(s) %s, ", kvm->opts.target.pid);
573 pr_info("dazed and confused on what is monitored, ");
576 pr_info("all VCPUs:\n\n");
578 pr_info("VCPU %d:\n\n", vcpu);
581 static void show_timeofday(void)
587 gettimeofday(&tv, NULL);
588 if (localtime_r(&tv.tv_sec, <ime)) {
589 strftime(date, sizeof(date), "%H:%M:%S", <ime);
590 pr_info("%s.%06ld", date, tv.tv_usec);
592 pr_info("00:00:00.000000");
597 static void print_result(struct perf_kvm_stat *kvm)
599 char decode[decode_str_len];
600 struct kvm_event *event;
601 int vcpu = kvm->trace_vcpu;
609 print_vcpu_info(kvm);
610 pr_info("%*s ", decode_str_len, kvm->events_ops->name);
611 pr_info("%10s ", "Samples");
612 pr_info("%9s ", "Samples%");
614 pr_info("%9s ", "Time%");
615 pr_info("%11s ", "Min Time");
616 pr_info("%11s ", "Max Time");
617 pr_info("%16s ", "Avg time");
620 while ((event = pop_from_result(&kvm->result))) {
621 u64 ecount, etime, max, min;
623 ecount = get_event_count(event, vcpu);
624 etime = get_event_time(event, vcpu);
625 max = get_event_max(event, vcpu);
626 min = get_event_min(event, vcpu);
628 kvm->events_ops->decode_key(kvm, &event->key, decode);
629 pr_info("%*s ", decode_str_len, decode);
630 pr_info("%10llu ", (unsigned long long)ecount);
631 pr_info("%8.2f%% ", (double)ecount / kvm->total_count * 100);
632 pr_info("%8.2f%% ", (double)etime / kvm->total_time * 100);
633 pr_info("%9.2fus ", (double)min / NSEC_PER_USEC);
634 pr_info("%9.2fus ", (double)max / NSEC_PER_USEC);
635 pr_info("%9.2fus ( +-%7.2f%% )", (double)etime / ecount / NSEC_PER_USEC,
636 kvm_event_rel_stddev(vcpu, event));
640 pr_info("\nTotal Samples:%" PRIu64 ", Total events handled time:%.2fus.\n\n",
641 kvm->total_count, kvm->total_time / (double)NSEC_PER_USEC);
643 if (kvm->lost_events)
644 pr_info("\nLost events: %" PRIu64 "\n\n", kvm->lost_events);
647 #ifdef HAVE_TIMERFD_SUPPORT
648 static int process_lost_event(struct perf_tool *tool,
649 union perf_event *event __maybe_unused,
650 struct perf_sample *sample __maybe_unused,
651 struct machine *machine __maybe_unused)
653 struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat, tool);
660 static bool skip_sample(struct perf_kvm_stat *kvm,
661 struct perf_sample *sample)
663 if (kvm->pid_list && intlist__find(kvm->pid_list, sample->pid) == NULL)
669 static int process_sample_event(struct perf_tool *tool,
670 union perf_event *event,
671 struct perf_sample *sample,
672 struct perf_evsel *evsel,
673 struct machine *machine)
676 struct thread *thread;
677 struct perf_kvm_stat *kvm = container_of(tool, struct perf_kvm_stat,
680 if (skip_sample(kvm, sample))
683 thread = machine__findnew_thread(machine, sample->pid, sample->tid);
684 if (thread == NULL) {
685 pr_debug("problem processing %d event, skipping it.\n",
690 if (!handle_kvm_event(kvm, thread, evsel, sample))
697 static int cpu_isa_config(struct perf_kvm_stat *kvm)
699 char buf[64], *cpuid;
703 err = get_cpuid(buf, sizeof(buf));
705 pr_err("Failed to look up CPU type\n");
710 cpuid = kvm->session->header.env.cpuid;
713 pr_err("Failed to look up CPU type\n");
717 err = cpu_isa_init(kvm, cpuid);
719 pr_err("CPU %s is not supported.\n", cpuid);
724 static bool verify_vcpu(int vcpu)
726 if (vcpu != -1 && vcpu < 0) {
727 pr_err("Invalid vcpu:%d.\n", vcpu);
734 #ifdef HAVE_TIMERFD_SUPPORT
735 /* keeping the max events to a modest level to keep
736 * the processing of samples per mmap smooth.
738 #define PERF_KVM__MAX_EVENTS_PER_MMAP 25
740 static s64 perf_kvm__mmap_read_idx(struct perf_kvm_stat *kvm, int idx,
743 union perf_event *event;
744 struct perf_sample sample;
748 *mmap_time = ULLONG_MAX;
749 while ((event = perf_evlist__mmap_read(kvm->evlist, idx)) != NULL) {
750 err = perf_evlist__parse_sample(kvm->evlist, event, &sample);
752 perf_evlist__mmap_consume(kvm->evlist, idx);
753 pr_err("Failed to parse sample\n");
757 err = perf_session__queue_event(kvm->session, event, &sample, 0);
759 * FIXME: Here we can't consume the event, as perf_session__queue_event will
760 * point to it, and it'll get possibly overwritten by the kernel.
762 perf_evlist__mmap_consume(kvm->evlist, idx);
765 pr_err("Failed to enqueue sample: %d\n", err);
769 /* save time stamp of our first sample for this mmap */
771 *mmap_time = sample.time;
773 /* limit events per mmap handled all at once */
775 if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
782 static int perf_kvm__mmap_read(struct perf_kvm_stat *kvm)
784 int i, err, throttled = 0;
786 u64 flush_time = ULLONG_MAX, mmap_time;
788 for (i = 0; i < kvm->evlist->nr_mmaps; i++) {
789 n = perf_kvm__mmap_read_idx(kvm, i, &mmap_time);
793 /* flush time is going to be the minimum of all the individual
794 * mmap times. Essentially, we flush all the samples queued up
795 * from the last pass under our minimal start time -- that leaves
796 * a very small race for samples to come in with a lower timestamp.
797 * The ioctl to return the perf_clock timestamp should close the
800 if (mmap_time < flush_time)
801 flush_time = mmap_time;
804 if (n == PERF_KVM__MAX_EVENTS_PER_MMAP)
808 /* flush queue after each round in which we processed events */
810 struct ordered_events *oe = &kvm->session->ordered_events;
812 oe->next_flush = flush_time;
813 err = ordered_events__flush(oe, OE_FLUSH__ROUND);
815 if (kvm->lost_events)
816 pr_info("\nLost events: %" PRIu64 "\n\n",
825 static volatile int done;
827 static void sig_handler(int sig __maybe_unused)
832 static int perf_kvm__timerfd_create(struct perf_kvm_stat *kvm)
834 struct itimerspec new_value;
837 kvm->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
838 if (kvm->timerfd < 0) {
839 pr_err("timerfd_create failed\n");
843 new_value.it_value.tv_sec = kvm->display_time;
844 new_value.it_value.tv_nsec = 0;
845 new_value.it_interval.tv_sec = kvm->display_time;
846 new_value.it_interval.tv_nsec = 0;
848 if (timerfd_settime(kvm->timerfd, 0, &new_value, NULL) != 0) {
849 pr_err("timerfd_settime failed: %d\n", errno);
859 static int perf_kvm__handle_timerfd(struct perf_kvm_stat *kvm)
864 rc = read(kvm->timerfd, &c, sizeof(uint64_t));
869 pr_err("Failed to read timer fd: %d\n", errno);
873 if (rc != sizeof(uint64_t)) {
874 pr_err("Error reading timer fd - invalid size returned\n");
879 pr_debug("Missed timer beats: %" PRIu64 "\n", c-1);
886 clear_events_cache_stats(kvm->kvm_events_cache);
887 kvm->total_count = 0;
889 kvm->lost_events = 0;
894 static int fd_set_nonblock(int fd)
898 arg = fcntl(fd, F_GETFL);
900 pr_err("Failed to get current flags for fd %d\n", fd);
904 if (fcntl(fd, F_SETFL, arg | O_NONBLOCK) < 0) {
905 pr_err("Failed to set non-block option on fd %d\n", fd);
912 static int perf_kvm__handle_stdin(void)
923 static int kvm_events_live_report(struct perf_kvm_stat *kvm)
925 int nr_stdin, ret, err = -EINVAL;
928 /* live flag must be set first */
931 ret = cpu_isa_config(kvm);
935 if (!verify_vcpu(kvm->trace_vcpu) ||
937 !register_kvm_events_ops(kvm)) {
941 set_term_quiet_input(&save);
942 init_kvm_event_record(kvm);
944 signal(SIGINT, sig_handler);
945 signal(SIGTERM, sig_handler);
948 if (perf_kvm__timerfd_create(kvm) < 0) {
953 if (perf_evlist__add_pollfd(kvm->evlist, kvm->timerfd) < 0)
956 nr_stdin = perf_evlist__add_pollfd(kvm->evlist, fileno(stdin));
960 if (fd_set_nonblock(fileno(stdin)) != 0)
963 /* everything is good - enable the events and process */
964 perf_evlist__enable(kvm->evlist);
967 struct fdarray *fda = &kvm->evlist->pollfd;
970 rc = perf_kvm__mmap_read(kvm);
974 err = perf_kvm__handle_timerfd(kvm);
978 if (fda->entries[nr_stdin].revents & POLLIN)
979 done = perf_kvm__handle_stdin();
982 err = fdarray__poll(fda, 100);
985 perf_evlist__disable(kvm->evlist);
993 if (kvm->timerfd >= 0)
996 tcsetattr(0, TCSAFLUSH, &save);
1000 static int kvm_live_open_events(struct perf_kvm_stat *kvm)
1003 struct perf_evsel *pos;
1004 struct perf_evlist *evlist = kvm->evlist;
1005 char sbuf[STRERR_BUFSIZE];
1007 perf_evlist__config(evlist, &kvm->opts, NULL);
1010 * Note: exclude_{guest,host} do not apply here.
1011 * This command processes KVM tracepoints from host only
1013 evlist__for_each_entry(evlist, pos) {
1014 struct perf_event_attr *attr = &pos->attr;
1016 /* make sure these *are* set */
1017 perf_evsel__set_sample_bit(pos, TID);
1018 perf_evsel__set_sample_bit(pos, TIME);
1019 perf_evsel__set_sample_bit(pos, CPU);
1020 perf_evsel__set_sample_bit(pos, RAW);
1021 /* make sure these are *not*; want as small a sample as possible */
1022 perf_evsel__reset_sample_bit(pos, PERIOD);
1023 perf_evsel__reset_sample_bit(pos, IP);
1024 perf_evsel__reset_sample_bit(pos, CALLCHAIN);
1025 perf_evsel__reset_sample_bit(pos, ADDR);
1026 perf_evsel__reset_sample_bit(pos, READ);
1031 attr->sample_period = 1;
1033 attr->watermark = 0;
1034 attr->wakeup_events = 1000;
1036 /* will enable all once we are ready */
1040 err = perf_evlist__open(evlist);
1042 printf("Couldn't create the events: %s\n",
1043 str_error_r(errno, sbuf, sizeof(sbuf)));
1047 if (perf_evlist__mmap(evlist, kvm->opts.mmap_pages, false) < 0) {
1048 ui__error("Failed to mmap the events: %s\n",
1049 str_error_r(errno, sbuf, sizeof(sbuf)));
1050 perf_evlist__close(evlist);
1061 static int read_events(struct perf_kvm_stat *kvm)
1065 struct perf_tool eops = {
1066 .sample = process_sample_event,
1067 .comm = perf_event__process_comm,
1068 .namespaces = perf_event__process_namespaces,
1069 .ordered_events = true,
1071 struct perf_data_file file = {
1072 .path = kvm->file_name,
1073 .mode = PERF_DATA_MODE_READ,
1074 .force = kvm->force,
1078 kvm->session = perf_session__new(&file, false, &kvm->tool);
1079 if (!kvm->session) {
1080 pr_err("Initializing perf session failed\n");
1084 symbol__init(&kvm->session->header.env);
1086 if (!perf_session__has_traces(kvm->session, "kvm record")) {
1092 * Do not use 'isa' recorded in kvm_exit tracepoint since it is not
1093 * traced in the old kernel.
1095 ret = cpu_isa_config(kvm);
1099 ret = perf_session__process_events(kvm->session);
1102 perf_session__delete(kvm->session);
1106 static int parse_target_str(struct perf_kvm_stat *kvm)
1108 if (kvm->opts.target.pid) {
1109 kvm->pid_list = intlist__new(kvm->opts.target.pid);
1110 if (kvm->pid_list == NULL) {
1111 pr_err("Error parsing process id string\n");
1119 static int kvm_events_report_vcpu(struct perf_kvm_stat *kvm)
1122 int vcpu = kvm->trace_vcpu;
1124 if (parse_target_str(kvm) != 0)
1127 if (!verify_vcpu(vcpu))
1130 if (!select_key(kvm))
1133 if (!register_kvm_events_ops(kvm))
1136 init_kvm_event_record(kvm);
1139 ret = read_events(kvm);
1150 #define STRDUP_FAIL_EXIT(s) \
1158 int __weak setup_kvm_events_tp(struct perf_kvm_stat *kvm __maybe_unused)
1164 kvm_events_record(struct perf_kvm_stat *kvm, int argc, const char **argv)
1166 unsigned int rec_argc, i, j, events_tp_size;
1167 const char **rec_argv;
1168 const char * const record_args[] = {
1174 const char * const kvm_stat_record_usage[] = {
1175 "perf kvm stat record [<options>]",
1178 const char * const *events_tp;
1182 ret = setup_kvm_events_tp(kvm);
1184 pr_err("Unable to setup the kvm tracepoints\n");
1188 for (events_tp = kvm_events_tp; *events_tp; events_tp++)
1191 rec_argc = ARRAY_SIZE(record_args) + argc + 2 +
1193 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1195 if (rec_argv == NULL)
1198 for (i = 0; i < ARRAY_SIZE(record_args); i++)
1199 rec_argv[i] = STRDUP_FAIL_EXIT(record_args[i]);
1201 for (j = 0; j < events_tp_size; j++) {
1202 rec_argv[i++] = "-e";
1203 rec_argv[i++] = STRDUP_FAIL_EXIT(kvm_events_tp[j]);
1206 rec_argv[i++] = STRDUP_FAIL_EXIT("-o");
1207 rec_argv[i++] = STRDUP_FAIL_EXIT(kvm->file_name);
1209 for (j = 1; j < (unsigned int)argc; j++, i++)
1210 rec_argv[i] = argv[j];
1212 set_option_flag(record_options, 'e', "event", PARSE_OPT_HIDDEN);
1213 set_option_flag(record_options, 0, "filter", PARSE_OPT_HIDDEN);
1214 set_option_flag(record_options, 'R', "raw-samples", PARSE_OPT_HIDDEN);
1216 set_option_flag(record_options, 'F', "freq", PARSE_OPT_DISABLED);
1217 set_option_flag(record_options, 0, "group", PARSE_OPT_DISABLED);
1218 set_option_flag(record_options, 'g', NULL, PARSE_OPT_DISABLED);
1219 set_option_flag(record_options, 0, "call-graph", PARSE_OPT_DISABLED);
1220 set_option_flag(record_options, 'd', "data", PARSE_OPT_DISABLED);
1221 set_option_flag(record_options, 'T', "timestamp", PARSE_OPT_DISABLED);
1222 set_option_flag(record_options, 'P', "period", PARSE_OPT_DISABLED);
1223 set_option_flag(record_options, 'n', "no-samples", PARSE_OPT_DISABLED);
1224 set_option_flag(record_options, 'N', "no-buildid-cache", PARSE_OPT_DISABLED);
1225 set_option_flag(record_options, 'B', "no-buildid", PARSE_OPT_DISABLED);
1226 set_option_flag(record_options, 'G', "cgroup", PARSE_OPT_DISABLED);
1227 set_option_flag(record_options, 'b', "branch-any", PARSE_OPT_DISABLED);
1228 set_option_flag(record_options, 'j', "branch-filter", PARSE_OPT_DISABLED);
1229 set_option_flag(record_options, 'W', "weight", PARSE_OPT_DISABLED);
1230 set_option_flag(record_options, 0, "transaction", PARSE_OPT_DISABLED);
1232 record_usage = kvm_stat_record_usage;
1233 return cmd_record(i, rec_argv);
1237 kvm_events_report(struct perf_kvm_stat *kvm, int argc, const char **argv)
1239 const struct option kvm_events_report_options[] = {
1240 OPT_STRING(0, "event", &kvm->report_event, "report event",
1241 "event for reporting: vmexit, "
1242 "mmio (x86 only), ioport (x86 only)"),
1243 OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
1244 "vcpu id to report"),
1245 OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
1246 "key for sorting: sample(sort by samples number)"
1247 " time (sort by avg time)"),
1248 OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
1249 "analyze events only for given process id(s)"),
1250 OPT_BOOLEAN('f', "force", &kvm->force, "don't complain, do it"),
1254 const char * const kvm_events_report_usage[] = {
1255 "perf kvm stat report [<options>]",
1260 argc = parse_options(argc, argv,
1261 kvm_events_report_options,
1262 kvm_events_report_usage, 0);
1264 usage_with_options(kvm_events_report_usage,
1265 kvm_events_report_options);
1268 if (!kvm->opts.target.pid)
1269 kvm->opts.target.system_wide = true;
1271 return kvm_events_report_vcpu(kvm);
1274 #ifdef HAVE_TIMERFD_SUPPORT
1275 static struct perf_evlist *kvm_live_event_list(void)
1277 struct perf_evlist *evlist;
1278 char *tp, *name, *sys;
1280 const char * const *events_tp;
1282 evlist = perf_evlist__new();
1286 for (events_tp = kvm_events_tp; *events_tp; events_tp++) {
1288 tp = strdup(*events_tp);
1292 /* split tracepoint into subsystem and name */
1294 name = strchr(tp, ':');
1296 pr_err("Error parsing %s tracepoint: subsystem delimiter not found\n",
1304 if (perf_evlist__add_newtp(evlist, sys, name, NULL)) {
1305 pr_err("Failed to add %s tracepoint to the list\n", *events_tp);
1317 perf_evlist__delete(evlist);
1324 static int kvm_events_live(struct perf_kvm_stat *kvm,
1325 int argc, const char **argv)
1327 char errbuf[BUFSIZ];
1330 const struct option live_options[] = {
1331 OPT_STRING('p', "pid", &kvm->opts.target.pid, "pid",
1332 "record events on existing process id"),
1333 OPT_CALLBACK('m', "mmap-pages", &kvm->opts.mmap_pages, "pages",
1334 "number of mmap data pages",
1335 perf_evlist__parse_mmap_pages),
1336 OPT_INCR('v', "verbose", &verbose,
1337 "be more verbose (show counter open errors, etc)"),
1338 OPT_BOOLEAN('a', "all-cpus", &kvm->opts.target.system_wide,
1339 "system-wide collection from all CPUs"),
1340 OPT_UINTEGER('d', "display", &kvm->display_time,
1341 "time in seconds between display updates"),
1342 OPT_STRING(0, "event", &kvm->report_event, "report event",
1343 "event for reporting: "
1344 "vmexit, mmio (x86 only), ioport (x86 only)"),
1345 OPT_INTEGER(0, "vcpu", &kvm->trace_vcpu,
1346 "vcpu id to report"),
1347 OPT_STRING('k', "key", &kvm->sort_key, "sort-key",
1348 "key for sorting: sample(sort by samples number)"
1349 " time (sort by avg time)"),
1350 OPT_U64(0, "duration", &kvm->duration,
1351 "show events other than"
1352 " HLT (x86 only) or Wait state (s390 only)"
1353 " that take longer than duration usecs"),
1354 OPT_UINTEGER(0, "proc-map-timeout", &kvm->opts.proc_map_timeout,
1355 "per thread proc mmap processing timeout in ms"),
1358 const char * const live_usage[] = {
1359 "perf kvm stat live [<options>]",
1362 struct perf_data_file file = {
1363 .mode = PERF_DATA_MODE_WRITE,
1367 /* event handling */
1368 kvm->tool.sample = process_sample_event;
1369 kvm->tool.comm = perf_event__process_comm;
1370 kvm->tool.exit = perf_event__process_exit;
1371 kvm->tool.fork = perf_event__process_fork;
1372 kvm->tool.lost = process_lost_event;
1373 kvm->tool.namespaces = perf_event__process_namespaces;
1374 kvm->tool.ordered_events = true;
1375 perf_tool__fill_defaults(&kvm->tool);
1378 kvm->display_time = 1;
1379 kvm->opts.user_interval = 1;
1380 kvm->opts.mmap_pages = 512;
1381 kvm->opts.target.uses_mmap = false;
1382 kvm->opts.target.uid_str = NULL;
1383 kvm->opts.target.uid = UINT_MAX;
1384 kvm->opts.proc_map_timeout = 500;
1387 disable_buildid_cache();
1392 argc = parse_options(argc, argv, live_options,
1395 usage_with_options(live_usage, live_options);
1398 kvm->duration *= NSEC_PER_USEC; /* convert usec to nsec */
1401 * target related setups
1403 err = target__validate(&kvm->opts.target);
1405 target__strerror(&kvm->opts.target, err, errbuf, BUFSIZ);
1406 ui__warning("%s", errbuf);
1409 if (target__none(&kvm->opts.target))
1410 kvm->opts.target.system_wide = true;
1414 * generate the event list
1416 err = setup_kvm_events_tp(kvm);
1418 pr_err("Unable to setup the kvm tracepoints\n");
1422 kvm->evlist = kvm_live_event_list();
1423 if (kvm->evlist == NULL) {
1428 symbol_conf.nr_events = kvm->evlist->nr_entries;
1430 if (perf_evlist__create_maps(kvm->evlist, &kvm->opts.target) < 0)
1431 usage_with_options(live_usage, live_options);
1436 kvm->session = perf_session__new(&file, false, &kvm->tool);
1437 if (kvm->session == NULL) {
1441 kvm->session->evlist = kvm->evlist;
1442 perf_session__set_id_hdr_size(kvm->session);
1443 ordered_events__set_copy_on_queue(&kvm->session->ordered_events, true);
1444 machine__synthesize_threads(&kvm->session->machines.host, &kvm->opts.target,
1445 kvm->evlist->threads, false, kvm->opts.proc_map_timeout);
1446 err = kvm_live_open_events(kvm);
1450 err = kvm_events_live_report(kvm);
1453 perf_session__delete(kvm->session);
1454 kvm->session = NULL;
1455 perf_evlist__delete(kvm->evlist);
1461 static void print_kvm_stat_usage(void)
1463 printf("Usage: perf kvm stat <command>\n\n");
1465 printf("# Available commands:\n");
1466 printf("\trecord: record kvm events\n");
1467 printf("\treport: report statistical data of kvm events\n");
1468 printf("\tlive: live reporting of statistical data of kvm events\n");
1470 printf("\nOtherwise, it is the alias of 'perf stat':\n");
1473 static int kvm_cmd_stat(const char *file_name, int argc, const char **argv)
1475 struct perf_kvm_stat kvm = {
1476 .file_name = file_name,
1479 .report_event = "vmexit",
1480 .sort_key = "sample",
1485 print_kvm_stat_usage();
1489 if (!strncmp(argv[1], "rec", 3))
1490 return kvm_events_record(&kvm, argc - 1, argv + 1);
1492 if (!strncmp(argv[1], "rep", 3))
1493 return kvm_events_report(&kvm, argc - 1 , argv + 1);
1495 #ifdef HAVE_TIMERFD_SUPPORT
1496 if (!strncmp(argv[1], "live", 4))
1497 return kvm_events_live(&kvm, argc - 1 , argv + 1);
1501 return cmd_stat(argc, argv);
1503 #endif /* HAVE_KVM_STAT_SUPPORT */
1505 static int __cmd_record(const char *file_name, int argc, const char **argv)
1507 int rec_argc, i = 0, j;
1508 const char **rec_argv;
1510 rec_argc = argc + 2;
1511 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1512 rec_argv[i++] = strdup("record");
1513 rec_argv[i++] = strdup("-o");
1514 rec_argv[i++] = strdup(file_name);
1515 for (j = 1; j < argc; j++, i++)
1516 rec_argv[i] = argv[j];
1518 BUG_ON(i != rec_argc);
1520 return cmd_record(i, rec_argv);
1523 static int __cmd_report(const char *file_name, int argc, const char **argv)
1525 int rec_argc, i = 0, j;
1526 const char **rec_argv;
1528 rec_argc = argc + 2;
1529 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1530 rec_argv[i++] = strdup("report");
1531 rec_argv[i++] = strdup("-i");
1532 rec_argv[i++] = strdup(file_name);
1533 for (j = 1; j < argc; j++, i++)
1534 rec_argv[i] = argv[j];
1536 BUG_ON(i != rec_argc);
1538 return cmd_report(i, rec_argv);
1542 __cmd_buildid_list(const char *file_name, int argc, const char **argv)
1544 int rec_argc, i = 0, j;
1545 const char **rec_argv;
1547 rec_argc = argc + 2;
1548 rec_argv = calloc(rec_argc + 1, sizeof(char *));
1549 rec_argv[i++] = strdup("buildid-list");
1550 rec_argv[i++] = strdup("-i");
1551 rec_argv[i++] = strdup(file_name);
1552 for (j = 1; j < argc; j++, i++)
1553 rec_argv[i] = argv[j];
1555 BUG_ON(i != rec_argc);
1557 return cmd_buildid_list(i, rec_argv);
1560 int cmd_kvm(int argc, const char **argv)
1562 const char *file_name = NULL;
1563 const struct option kvm_options[] = {
1564 OPT_STRING('i', "input", &file_name, "file",
1566 OPT_STRING('o', "output", &file_name, "file",
1567 "Output file name"),
1568 OPT_BOOLEAN(0, "guest", &perf_guest,
1569 "Collect guest os data"),
1570 OPT_BOOLEAN(0, "host", &perf_host,
1571 "Collect host os data"),
1572 OPT_STRING(0, "guestmount", &symbol_conf.guestmount, "directory",
1573 "guest mount directory under which every guest os"
1574 " instance has a subdir"),
1575 OPT_STRING(0, "guestvmlinux", &symbol_conf.default_guest_vmlinux_name,
1576 "file", "file saving guest os vmlinux"),
1577 OPT_STRING(0, "guestkallsyms", &symbol_conf.default_guest_kallsyms,
1578 "file", "file saving guest os /proc/kallsyms"),
1579 OPT_STRING(0, "guestmodules", &symbol_conf.default_guest_modules,
1580 "file", "file saving guest os /proc/modules"),
1581 OPT_INCR('v', "verbose", &verbose,
1582 "be more verbose (show counter open errors, etc)"),
1586 const char *const kvm_subcommands[] = { "top", "record", "report", "diff",
1587 "buildid-list", "stat", NULL };
1588 const char *kvm_usage[] = { NULL, NULL };
1593 argc = parse_options_subcommand(argc, argv, kvm_options, kvm_subcommands, kvm_usage,
1594 PARSE_OPT_STOP_AT_NON_OPTION);
1596 usage_with_options(kvm_usage, kvm_options);
1602 file_name = get_filename_for_perf_kvm();
1605 pr_err("Failed to allocate memory for filename\n");
1610 if (!strncmp(argv[0], "rec", 3))
1611 return __cmd_record(file_name, argc, argv);
1612 else if (!strncmp(argv[0], "rep", 3))
1613 return __cmd_report(file_name, argc, argv);
1614 else if (!strncmp(argv[0], "diff", 4))
1615 return cmd_diff(argc, argv);
1616 else if (!strncmp(argv[0], "top", 3))
1617 return cmd_top(argc, argv);
1618 else if (!strncmp(argv[0], "buildid-list", 12))
1619 return __cmd_buildid_list(file_name, argc, argv);
1620 #ifdef HAVE_KVM_STAT_SUPPORT
1621 else if (!strncmp(argv[0], "stat", 4))
1622 return kvm_cmd_stat(file_name, argc, argv);
1625 usage_with_options(kvm_usage, kvm_options);