Skip to contentSkip to conversation

Initial trace-cmd perf support

PATCH In review Tzvetomir Stoyanov (VMware) 3 participants 13 messages Dec 3, 2020 – Feb 19, 2021 Kbuild

lore
Share & tools
lore
#0 lore raw

cover Initial trace-cmd perf support

Initial implementation of trace-cmd perf subcommand. It collects call traces of a given PID and resolves collected addresses to function names. Still work in progress.
What it has till now:
- Configures and runs perf to collect call traces of the given PID.
- Runs per CPU thread to read perf buffers and store traces in temp files.
- Resolves collected addresses to function names (well, at least tries to do it). This includes also dynamic libraries, loaded runtime during the trace.
What should be implemented:
- Store the results in a trace.dat file. Should think about how to extend its format to hold these traces.
- Visualise the call stack from trace.dat file with trace-cmd report and KernelShark.

Tzvetomir Stoyanov (VMware) (5):
trace-cmd: Internal refactoring of pid address map logic
trace-cmd: Make read_file_string() non static
trace-cmd: New internal APIs for reading ELF header
trace-cmd: Add a new option in trace.dat file for the address to
function name mapping
[WIP] trace-cmd: Add new subcomand "trace-cmd perf"

 Makefile                                      |  10 +
 .../include/private/trace-cmd-private.h       |   5 +
 lib/trace-cmd/trace-input.c                   | 144 +++
 tracecmd/Makefile                             |   2 +
 tracecmd/include/trace-local.h                |  46 +-
 tracecmd/trace-cmd.c                          |   1 +
 tracecmd/trace-dump.c                         |   9 +-
 tracecmd/trace-obj-debug.c                    | 907 ++++++++++++++++++
 tracecmd/trace-perf.c                         | 726 ++++++++++++++
 tracecmd/trace-record.c                       | 107 +--
 10 files changed, 1841 insertions(+), 116 deletions(-)
 create mode 100644 tracecmd/trace-obj-debug.c
 create mode 100644 tracecmd/trace-perf.c
Signature · 1 line
2.28.0
#1 lore raw

PATCH 1/5 trace-cmd: Internal refactoring of pid address map logic

Make functions for collecting file to memory map of a PID non static, so they can be reused in the trace-cmd application context. Created new file trace-obj-debug.c with these functions.

---
 tracecmd/Makefile              |   1 +
 tracecmd/include/trace-local.h |  19 +++--
 tracecmd/trace-obj-debug.c     | 138 +++++++++++++++++++++++++++++++++
 tracecmd/trace-record.c        | 107 +------------------------
 4 files changed, 152 insertions(+), 113 deletions(-)
 create mode 100644 tracecmd/trace-obj-debug.c
tracecmd/Makefile +1 -0
index 01f36c61..5a16a5e5 100644
@@ -32,6 +32,7 @@ TRACE_CMD_OBJS += trace-list.o
 TRACE_CMD_OBJS += trace-usage.o
 TRACE_CMD_OBJS += trace-dump.o
 TRACE_CMD_OBJS += trace-clear.o
+TRACE_CMD_OBJS += trace-obj-debug.o
 ifeq ($(VSOCK_DEFINED), 1)
 TRACE_CMD_OBJS += trace-tsync.o
 endif
tracecmd/include/trace-local.h +11 -8
index 85c7e03e..8b2d4c21 100644
@@ -179,14 +179,6 @@ struct func_list {
 	const char *mod;
 };
 
-struct pid_addr_maps {
-	struct pid_addr_maps		*next;
-	struct tracecmd_proc_addr_map	*lib_maps;
-	unsigned int			nr_lib_maps;
-	char				*proc_name;
-	int				pid;
-};
-
 struct opt_list {
 	struct opt_list *next;
 	const char	*option;
@@ -315,4 +307,15 @@ void *malloc_or_die(unsigned int size); /* Can be overridden */
 void __noreturn __die(const char *fmt, ...);
 void __noreturn _vdie(const char *fmt, va_list ap);
 
+/* --- Debug symbols--- */
+struct pid_addr_maps {
+	struct pid_addr_maps	*next;
+	struct tracecmd_proc_addr_map	*lib_maps;
+	unsigned int			nr_lib_maps;
+	char				*proc_name;
+	int				pid;
+};
+int trace_debug_get_filemap(struct pid_addr_maps **file_maps, int pid);
+void trace_debug_free_filemap(struct pid_addr_maps *maps);
+
 #endif /* __TRACE_LOCAL_H */
tracecmd/trace-obj-debug.c new file +138 -0

138 lines not on this page · raw message

tracecmd/trace-record.c +2 -105

125 lines not on this page · raw message

Signature · 1 line
2.28.0
#2 lore raw

PATCH 2/5 trace-cmd: Make read_file_string() non static

In reply to Tzvetomir Stoyanov (VMware)

This helper function is used to read strings from a binary file locally in trace-dump.c context. The same functionality could be useful for other trace-cmd logics. Made the function non static and prefix it with "trace_", so it could be used in trace-cmd application context.

---
 tracecmd/include/trace-local.h | 1 +
 tracecmd/trace-dump.c          | 6 +++---
 2 files changed, 4 insertions(+), 3 deletions(-)
tracecmd/include/trace-local.h +1 -0
index 8b2d4c21..109c3328 100644
@@ -318,4 +318,5 @@ struct pid_addr_maps {
 int trace_debug_get_filemap(struct pid_addr_maps **file_maps, int pid);
 void trace_debug_free_filemap(struct pid_addr_maps *maps);
 
+int trace_read_file_string(int fd, char *dst, int len);
 #endif /* __TRACE_LOCAL_H */
tracecmd/trace-dump.c +3 -3
index 5642f12a..c55e2389 100644
@@ -49,7 +49,7 @@ enum dump_items verbosity;
 			tracecmd_plog(fmt, ##__VA_ARGS__);	\
 	} while (0)
 
-static int read_file_string(int fd, char *dst, int len)
+int trace_read_file_string(int fd, char *dst, int len)
 {
 	size_t size = 0;
 	int r;
@@ -160,7 +160,7 @@ static void dump_initial_format(int fd)
 		die("wrong tracing string: %s", buf);
 
 	/* get file version */
-	if (read_file_string(fd, buf, DUMP_SIZE))
+	if (trace_read_file_string(fd, buf, DUMP_SIZE))
 		die("no version string");
 
 	do_print(SUMMARY, "\t\t%s\t[Version]\n", buf);
@@ -260,7 +260,7 @@ static void dump_events_format(int fd)
 
 	while (systems) {
 
-		if (read_file_string(fd, buf, DUMP_SIZE))
+		if (trace_read_file_string(fd, buf, DUMP_SIZE))
 			die("cannot read the name of the $dth system", systems);
 		if (read_file_number(fd, &events, 4))
 			die("cannot read the count of the events in system %s",
Signature · 1 line
2.28.0
#3 lore raw

PATCH 3/5 trace-cmd: New internal APIs for reading ELF header

In reply to Tzvetomir Stoyanov (VMware)

Implemented new trace-cmd internal APIs for parsing ELF header and resolving VMA to function name and function name to VMA and file offset. The bfd library is used to read and parse the binary file. The new APIs are part of trace-cmd application and are visible only inside its context.

---
 Makefile                       |  10 +
 tracecmd/include/trace-local.h |  24 +
 tracecmd/trace-obj-debug.c     | 769 +++++++++++++++++++++++++++++++++
 3 files changed, 803 insertions(+)
Makefile +10 -0
index 8626b91b..1ca933a7 100644
@@ -246,6 +246,16 @@ endif
 CUNIT_INSTALLED := $(shell if (printf "$(pound)include <CUnit/Basic.h>\n void main(){CU_initialize_registry();}" | $(CC) -x c - -lcunit >/dev/null 2>&1) ; then echo 1; else echo 0 ; fi)
 export CUNIT_INSTALLED
 
+BFD_INSTALLED := $(shell if (echo -e "$(pound)include <bfd.h>\n void main(){bfd_init();}" | $(CC) -o /dev/null -xc  - -lbfd >/dev/null 2>&1) ; then echo 1; else echo 0 ; fi)
+
+export BFD_INSTALLED
+ifeq ($(BFD_INSTALLED), 1)
+CFLAGS += -DBFD_INSTALLED
+LIBS += -lbfd
+else
+$(warning libbfd is not installed)
+endif
+
 export CFLAGS
 export INCLUDES
 
tracecmd/include/trace-local.h +24 -0
index 109c3328..cd2d34a4 100644
@@ -318,5 +318,29 @@ struct pid_addr_maps {
 int trace_debug_get_filemap(struct pid_addr_maps **file_maps, int pid);
 void trace_debug_free_filemap(struct pid_addr_maps *maps);
 
+struct tracecmd_debug_symbols {
+	char *name;			/* symbol's name */
+	char *fname;			/* symbol's file */
+	unsigned long long vma_start;	/* symbol's start VMA */
+	unsigned long long vma_near;	/* symbol's requested VMA */
+	unsigned long long foffset;	/* symbol's offset in the binary file*/
+};
+struct trace_debug_object;
+struct trace_debug_object *trace_debug_obj_create_file(char *file, bool libs);
+struct trace_debug_object *trace_debug_obj_create_pid(int pid);
+void trace_debug_obj_destroy(struct trace_debug_object *debug);
+int trace_debug_obj_add_file(struct trace_debug_object *dbg, char *file_name,
+			     unsigned long long vmem_start,
+			     unsigned long long vmem_end,
+			     unsigned long long pgoff);
+
+int trace_debug_resolve_symbols(struct trace_debug_object *obj);
+int trace_debug_add_resolve_symbol(struct trace_debug_object *obj,
+				   unsigned long long vma, char *name);
+
+void trace_debug_walk_resolved_symbols(struct trace_debug_object *obj,
+				       int (*callback)(struct tracecmd_debug_symbols *, void *),
+				       void *context);
+
 int trace_read_file_string(int fd, char *dst, int len);
 #endif /* __TRACE_LOCAL_H */
tracecmd/trace-obj-debug.c +769 -0

779 lines not on this page · raw message

Signature · 1 line
2.28.0
#4 lore raw

PATCH 4/5 trace-cmd: Add a new option in trace.dat file for the address to function name mapping

In reply to Tzvetomir Stoyanov (VMware)

There are cases where resolving a user space address recorded in the trace file to function name is required, when this file is visualised. This mapping is available during the trace. A new trace.dat file option TRACECMD_OPTION_PID_SYMBOLS is added, for storing the mapping in the file. A new API is introduced, to resolve address to name, using information stored in the TRACECMD_OPTION_PID_SYMBOLS option:

struct tracecmd_debug_symbols * tracecmd_search_task_symbol(struct tracecmd_input *handle,

			     int pid, unsigned long long addr);
---
 .../include/private/trace-cmd-private.h       |   5 +
 lib/trace-cmd/trace-input.c                   | 144 ++++++++++++++++++
 tracecmd/trace-dump.c                         |   3 +
 3 files changed, 152 insertions(+)
lib/trace-cmd/include/private/trace-cmd-private.h +5 -0
index a0dac5da..8c99faa3 100644
@@ -112,6 +112,7 @@ enum {
 	TRACECMD_OPTION_TRACEID,
 	TRACECMD_OPTION_TIME_SHIFT,
 	TRACECMD_OPTION_GUEST,
+	TRACECMD_OPTION_PID_SYMBOLS,
 };
 
 enum {
@@ -231,6 +232,10 @@ unsigned int tracecmd_record_ts_delta(struct tracecmd_input *handle,
 struct tracecmd_proc_addr_map *
 tracecmd_search_task_map(struct tracecmd_input *handle,
 			 int pid, unsigned long long addr);
+
+struct tracecmd_debug_symbols *
+tracecmd_search_task_symbol(struct tracecmd_input *handle,
+			    int pid, unsigned long long addr);
 #ifndef SWIG
 /* hack for function graph work around */
 extern __thread struct tracecmd_input *tracecmd_curr_thread_handle;
lib/trace-cmd/trace-input.c +144 -0

186 lines not on this page · raw message

tracecmd/trace-dump.c +3 -0
index c55e2389..a3e7acf7 100644
@@ -530,6 +530,9 @@ static void dump_options(int fd)
 		case TRACECMD_OPTION_GUEST:
 			dump_option_guest(fd, size);
 			break;
+		case TRACECMD_OPTION_PID_SYMBOLS:
+			dump_option_string(fd, size, "PIDSYMBOLS");
+			break;
 		default:
 			do_print(OPTIONS, " %d %d\t[Unknown option, size - skipping]\n",
 				 option, size);
Signature · 1 line
2.28.0
#5 lore raw

PATCH 5/5 trace-cmd: Add new subcomand "trace-cmd perf"

In reply to Tzvetomir Stoyanov (VMware)

The new sub command uses perf to collect performance information of the selected process. It has one mandatory argument:
trace-cmd perf --pid <PID>

---
 tracecmd/Makefile              |   1 +
 tracecmd/include/trace-local.h |   2 +
 tracecmd/trace-cmd.c           |   1 +
 tracecmd/trace-perf.c          | 726 +++++++++++++++++++++++++++++++++
 4 files changed, 730 insertions(+)
 create mode 100644 tracecmd/trace-perf.c
tracecmd/Makefile +1 -0
index 5a16a5e5..3fda6de8 100644
@@ -33,6 +33,7 @@ TRACE_CMD_OBJS += trace-usage.o
 TRACE_CMD_OBJS += trace-dump.o
 TRACE_CMD_OBJS += trace-clear.o
 TRACE_CMD_OBJS += trace-obj-debug.o
+TRACE_CMD_OBJS += trace-perf.o
 ifeq ($(VSOCK_DEFINED), 1)
 TRACE_CMD_OBJS += trace-tsync.o
 endif
tracecmd/include/trace-local.h +2 -0
index cd2d34a4..b0d03900 100644
@@ -102,6 +102,8 @@ void trace_usage(int argc, char **argv);
 
 void trace_dump(int argc, char **argv);
 
+void trace_perf(int argc, char **argv);
+
 int trace_record_agent(struct tracecmd_msg_handle *msg_handle,
 		       int cpus, int *fds,
 		       int argc, char **argv, bool use_fifos,
tracecmd/trace-cmd.c +1 -0
index 7376c5a5..0c5b324f 100644
@@ -104,6 +104,7 @@ struct command commands[] = {
 	{"list", trace_list},
 	{"help", trace_usage},
 	{"dump", trace_dump},
+	{"perf", trace_perf},
 	{"-h", trace_usage},
 };
 
tracecmd/trace-perf.c new file +726 -0

726 lines not on this page · raw message

Signature · 1 line
2.28.0
#6 lore raw

Re: [PATCH 5/5] [WIP] trace-cmd: Add new subcomand "trace-cmd perf"

tracecmd/trace-perf.c line 360

Quoted 11 lines · On Thu, 3 Dec 2020 08:02:26 +0200 "Tzvetomir Stoyanov (VMware)"…
tracecmd/trace-perf.c new file +11 -0
+static int perf_mmap(struct perf_cpu *perf)
+{
+	mmap_mask = NUM_PAGES * getpagesize() - 1;
+
+	/* associate a buffer with the file */
+	perf->mpage = mmap(NULL, (NUM_PAGES + 1) * getpagesize(),
+			PROT_READ | PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
+	if (perf->mpage == MAP_FAILED)
+		return -1;
+	return 0;
+}

BTW, I found that the above holds the conversions we need for the local clock!

        printf("time_shift=%d\n", perf->mpage->time_shift);
        printf("time_mult=%d\n", perf->mpage->time_mult);
        printf("time_offset=%lld\n", perf->mpage->time_offset);

Which gives me:

time_shift=31
time_mult=633046315
time_offset=-115773323084683

[ one for each CPU ]

The ftrace local clock is defined by:

u64 notrace trace_clock_local(void)

{
	u64 clock;
	preempt_disable_notrace();
	clock = sched_clock();
	preempt_enable_notrace();
	return clock;
}

Where

u64 sched_clock(void)

{
	if (static_branch_likely(&__use_tsc)) { // true
		u64 tsc_now = rdtsc();

		/* return the value in ns */
		return cycles_2_ns(tsc_now);
	}

and

static __always_inline unsigned long long cycles_2_ns(unsigned long long cyc)

{
	struct cyc2ns_data data;
	unsigned long long ns;

	cyc2ns_read_begin(&data); // <- this is where the data comes from

	ns = data.cyc2ns_offset;
	ns += mul_u64_u32_shr(cyc, data.cyc2ns_mul, data.cyc2ns_shift);

	cyc2ns_read_end();

	return ns;
}

__always_inline void cyc2ns_read_begin(struct cyc2ns_data *data)

{
	int seq, idx;

	preempt_disable_notrace();

	do {
		seq = this_cpu_read(cyc2ns.seq.seqcount.sequence);
		idx = seq & 1;

		data->cyc2ns_offset = this_cpu_read(cyc2ns.data[idx].cyc2ns_offset);
		data->cyc2ns_mul    = this_cpu_read(cyc2ns.data[idx].cyc2ns_mul);
		data->cyc2ns_shift  = this_cpu_read(cyc2ns.data[idx].cyc2ns_shift);

	} while (unlikely(seq != this_cpu_read(cyc2ns.seq.seqcount.sequence)));
}

The offset, multiplier and shift are from the cyc2ns.data[idx] (per cpu) is what determines the conversion from x86 cycles to nanoseconds.

Does user space have access to that? Yes! Via perf!

void arch_perf_update_userpage(struct perf_event *event,
struct perf_event_mmap_page *userpg, u64 now)
{
[..]

	cyc2ns_read_begin(&data);

	offset = data.cyc2ns_offset + __sched_clock_offset;

	/*
	 * Internal timekeeping for enabled/running/stopped times
	 * is always in the local_clock domain.
	 */
	userpg->cap_user_time = 1;
	userpg->time_mult = data.cyc2ns_mul;
	userpg->time_shift = data.cyc2ns_shift;
	userpg->time_offset = offset - now;

Those above values are the ones I printed at the beginning of this email.

Hence, we can use x86-tsc as the clock for both the host and guest, and then using perf find out how to convert that to what the 'local' clock would produce. At least the multiplier and the shfit.

-- Steve

#7 lore raw

Re: [PATCH 5/5] [WIP] trace-cmd: Add new subcomand "trace-cmd perf"

Quoted 3 lines · On Thu, 18 Feb 2021 21:03:52 -0500 Steven Rostedt <[email protected]> wrote:

Hence, we can use x86-tsc as the clock for both the host and guest, and then using perf find out how to convert that to what the 'local' clock would produce. At least the multiplier and the shfit.

I just tried this out:

http://rostedt.org/private/perf-trace.c

Where I did:

 # trace-cmd record -M 1 -C local -e irq -e sched taskset -c 0 ./perf-trace
time_shift=31
time_mult=633046315
time_offset=-125757047487632
 # trace-cmd report |grep print         taskset-34857 [000] 125742.260276: print:                tracing_mark_write: [426606557411358] [125757.283123254] - <idle>-0 [0] softirq_raise: vec=9 [action=RCU]
         taskset-34857 [000] 125742.260283: print:                tracing_mark_write: [426606557431758] [125757.283129268] - <idle>-0 [0] softirq_entry: vec=9 [action=RCU]
         taskset-34857 [000] 125742.260289: print:                tracing_mark_write: [426606557580560] [125757.283173133] - <idle>-0 [0] softirq_exit: vec=9 [action=RCU]
         taskset-34857 [000] 125742.260295: print:                tracing_mark_write: [426606560784758] [125757.284117683] - <idle>-0 [0] softirq_raise: vec=7 [action=SCHED]

The time offset is slightly different, but we don't care. We only want to convert the cycles into nanoseconds, and this appears to do the job!

-- Steve

#8 lore raw

Re: [PATCH 5/5] [WIP] trace-cmd: Add new subcomand "trace-cmd perf"

Hey guys,

Quoted 13 lines · Steven Rostedt
Quoted 5 lines · On Thu, 18 Feb 2021 21:03:52 -0500 Steven Rostedt <[email protected]> wrote:

Hence, we can use x86-tsc as the clock for both the host and guest, and
then using perf find out how to convert that to what the 'local' clock
would produce. At least the multiplier and the shfit.

I just tried this out:

 http://rostedt.org/private/perf-trace.c

Quoted 8 lines

Where I did:

 # trace-cmd record -M 1 -C local -e irq -e sched taskset -c 0
./perf-trace
time_shift=31
time_mult=633046315
time_offset=-125757047487632

Let me ask something really really stupid: where was this run?

Host? Gust? Both?

This seems very interesting... But I definitely need to stare more at your code (while scratching my head, at least for now :-P).

Thanks and Regards

Signature · 6 lines
Dario Faggioli, Ph.D
http://about.me/dario.faggioli
Virtualization Software Engineer
SUSE Labs, SUSE https://www.suse.com/
-------------------------------------------------------------------
<<This happens because _I_ choose it to happen!>> (Raistlin Majere)
#9 lore raw

Re: [PATCH 5/5] [WIP] trace-cmd: Add new subcomand "trace-cmd perf"

In reply to Steven Rostedt

Hi Steven,

Quoted 23 lines · Steven Rostedt

tracecmd/trace-perf.c line 360

Quoted 11 lines · On Thu, 3 Dec 2020 08:02:26 +0200 "Tzvetomir Stoyanov (VMware)"…
tracecmd/trace-perf.c new file +11 -0
+static int perf_mmap(struct perf_cpu *perf)
+{
+     mmap_mask = NUM_PAGES * getpagesize() - 1;
+
+     /* associate a buffer with the file */
+     perf->mpage = mmap(NULL, (NUM_PAGES + 1) * getpagesize(),
+                     PROT_READ | PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
+     if (perf->mpage == MAP_FAILED)
+             return -1;
+     return 0;
+}

BTW, I found that the above holds the conversions we need for the local clock!

        printf("time_shift=%d\n", perf->mpage->time_shift);
        printf("time_mult=%d\n", perf->mpage->time_mult);
        printf("time_offset=%lld\n", perf->mpage->time_offset);
Quoted 7 lines

Which gives me:

time_shift=31
time_mult=633046315
time_offset=-115773323084683

[ one for each CPU ]

This will give us time shift/mult/offset for each host CPU, right ? Is the local trace clock
different for each CPU ? Currently, the time offset is calculated per VCPU, assuming
that the host CPU on which this VCPU runs has no impact on the timestamp synchronization.
If the local clock depends on the CPU, then we should calculate the time offset of each guest
event individually, depending on host CPU and VCPU the event happened
- as the host task which runs
the VCPU can migrate between CPUs at any time. So, we need to:
1. Add timesync information for each host CPU in the trace.dat file.
2. Track the migration between CPUs of each task that runs VCPU and
save that information
in the trace.dat file.
2. When calculating the new timestamp of each guest event
(individually) - somehow find out on
which host CPU that guest event happened ?

Points 1 and 2 are doable, but will break the current trace.dat file option that holds the timesync information.
Point 3 is not clear to me, how we can get such information before the host and guest events are synchronised ?

Quoted 87 lines

The ftrace local clock is defined by:

u64 notrace trace_clock_local(void)

{
        u64 clock;
        preempt_disable_notrace();
        clock = sched_clock();
        preempt_enable_notrace();
        return clock;
}

Where

u64 sched_clock(void)

{
        if (static_branch_likely(&__use_tsc)) { // true
                u64 tsc_now = rdtsc();

                /* return the value in ns */
                return cycles_2_ns(tsc_now);
        }

and

static __always_inline unsigned long long cycles_2_ns(unsigned long long cyc)

{
        struct cyc2ns_data data;
        unsigned long long ns;

        cyc2ns_read_begin(&data); // <- this is where the data comes from

        ns = data.cyc2ns_offset;
        ns += mul_u64_u32_shr(cyc, data.cyc2ns_mul, data.cyc2ns_shift);

        cyc2ns_read_end();

        return ns;
}

__always_inline void cyc2ns_read_begin(struct cyc2ns_data *data)

{
        int seq, idx;

        preempt_disable_notrace();

        do {
                seq = this_cpu_read(cyc2ns.seq.seqcount.sequence);
                idx = seq & 1;

                data->cyc2ns_offset = this_cpu_read(cyc2ns.data[idx].cyc2ns_offset);
                data->cyc2ns_mul    = this_cpu_read(cyc2ns.data[idx].cyc2ns_mul);
                data->cyc2ns_shift  = this_cpu_read(cyc2ns.data[idx].cyc2ns_shift);

        } while (unlikely(seq != this_cpu_read(cyc2ns.seq.seqcount.sequence)));
}

The offset, multiplier and shift are from the cyc2ns.data[idx] (per cpu) is what determines the conversion from x86 cycles to nanoseconds.

Does user space have access to that? Yes! Via perf!

void arch_perf_update_userpage(struct perf_event *event,
struct perf_event_mmap_page *userpg, u64 now)
{
[..]

        cyc2ns_read_begin(&data);

        offset = data.cyc2ns_offset + __sched_clock_offset;

        /*
         * Internal timekeeping for enabled/running/stopped times
         * is always in the local_clock domain.
         */
        userpg->cap_user_time = 1;
        userpg->time_mult = data.cyc2ns_mul;
        userpg->time_shift = data.cyc2ns_shift;
        userpg->time_offset = offset - now;

Those above values are the ones I printed at the beginning of this email.

Hence, we can use x86-tsc as the clock for both the host and guest, and then using perf find out how to convert that to what the 'local' clock would produce. At least the multiplier and the shfit.

-- Steve

Signature · 2 lines
Tzvetomir (Ceco) Stoyanov
VMware Open Source Technology Center
#10 lore raw

Re: [PATCH 5/5] [WIP] trace-cmd: Add new subcomand "trace-cmd perf"

Quoted 32 lines · On Fri, 19 Feb 2021 09:16:26 +0200 Tzvetomir Stoyanov <[email protected]>…

Hi Steven,

Quoted 29 lines · Steven Rostedt

tracecmd/trace-perf.c line 360

Quoted 11 lines · On Thu, 3 Dec 2020 08:02:26 +0200 "Tzvetomir Stoyanov (VMware)"…
tracecmd/trace-perf.c new file +11 -0
+static int perf_mmap(struct perf_cpu *perf)
+{
+     mmap_mask = NUM_PAGES * getpagesize() - 1;
+
+     /* associate a buffer with the file */
+     perf->mpage = mmap(NULL, (NUM_PAGES + 1) * getpagesize(),
+                     PROT_READ | PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
+     if (perf->mpage == MAP_FAILED)
+             return -1;
+     return 0;
+}  

BTW, I found that the above holds the conversions we need for the local clock!

        printf("time_shift=%d\n", perf->mpage->time_shift);
        printf("time_mult=%d\n", perf->mpage->time_mult);
        printf("time_offset=%lld\n", perf->mpage->time_offset);

Which gives me:

time_shift=31
time_mult=633046315
time_offset=-115773323084683

Quoted 5 lines
Quoted 1 line

[ one for each CPU ]

This will give us time shift/mult/offset for each host CPU, right ? Is the local trace clock
different for each CPU ?

It can be. Note, the above offset is basically useless. That injects the current time into the value and we can't rely on it. But the shift and mult is needed.

But, usually, the shift and offset are identical on most systems across CPUs, but there's no guarantee that it will always be the case.

Quoted 5 lines

Currently, the time offset is calculated per
VCPU, assuming
that the host CPU on which this VCPU runs has no impact on the timestamp synchronization.
If the local clock depends on the CPU, then we should calculate the

Quoted 8 lines

time offset of each guest
event individually, depending on host CPU and VCPU the event happened
- as the host task which runs
the VCPU can migrate between CPUs at any time. So, we need to:
1. Add timesync information for each host CPU in the trace.dat file.
2. Track the migration between CPUs of each task that runs VCPU and
save that information
in the trace.dat file.

I was thinking about this too. And perhaps we can hold off until we find systems that have different values for mult and shift.

That said, we can easily add this information by recording the sched_switch events in a separate buffer. And I've been thinking about doing this by default anyway. More below.

Quoted 6 lines

2. When calculating the new timestamp of each guest event
(individually) - somehow find out on
which host CPU that guest event happened ?

Points 1 and 2 are doable, but will break the current trace.dat file option that holds the timesync information.

I don't think we need to have it in the timesync option. I think we can create another option to hold guest event data.

Quoted 3 lines

Point 3 is not clear to me, how we can get such information before the host and guest events are synchronised ?

My thoughts about this is. When we enable tracing of a guest (-A), we then create an instance on the host that records only kvm enter / exit events as well as sched switch events. Basically, enable all the events that we need to synchronize and show entering and exiting of the guest.

The synchronization logic already shows us what host thread controls each guest VCPU. If we record the kvm enter/exit and sched_switch events in a separate buffer, we can see when a host thread that runs a guest VCPU migrates to another CPU. Since the timestamps of those events are recorded in the meta events themselves (sched_switch), we know exactly where we need to use the new mult and shift values for the guest events.

Make sense?

-- Steve

#11 lore raw

Re: [PATCH 5/5] [WIP] trace-cmd: Add new subcomand "trace-cmd perf"

Quoted 90 lines · Steven Rostedt
Quoted 32 lines · On Fri, 19 Feb 2021 09:16:26 +0200 Tzvetomir Stoyanov <[email protected]>…

Hi Steven,

Quoted 29 lines · Steven Rostedt

tracecmd/trace-perf.c line 360

Quoted 11 lines · On Thu, 3 Dec 2020 08:02:26 +0200 "Tzvetomir Stoyanov (VMware)"…
tracecmd/trace-perf.c new file +11 -0
+static int perf_mmap(struct perf_cpu *perf)
+{
+     mmap_mask = NUM_PAGES * getpagesize() - 1;
+
+     /* associate a buffer with the file */
+     perf->mpage = mmap(NULL, (NUM_PAGES + 1) * getpagesize(),
+                     PROT_READ | PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
+     if (perf->mpage == MAP_FAILED)
+             return -1;
+     return 0;
+}

BTW, I found that the above holds the conversions we need for the local clock!

        printf("time_shift=%d\n", perf->mpage->time_shift);
        printf("time_mult=%d\n", perf->mpage->time_mult);
        printf("time_offset=%lld\n", perf->mpage->time_offset);

Which gives me:

time_shift=31
time_mult=633046315
time_offset=-115773323084683

Quoted 5 lines
Quoted 1 line

[ one for each CPU ]

This will give us time shift/mult/offset for each host CPU, right ? Is the local trace clock
different for each CPU ?

It can be. Note, the above offset is basically useless. That injects the current time into the value and we can't rely on it. But the shift and mult is needed.

But, usually, the shift and offset are identical on most systems across CPUs, but there's no guarantee that it will always be the case.

Quoted 5 lines

Currently, the time offset is calculated per
VCPU, assuming
that the host CPU on which this VCPU runs has no impact on the timestamp synchronization.
If the local clock depends on the CPU, then we should calculate the

Quoted 8 lines

time offset of each guest
event individually, depending on host CPU and VCPU the event happened
- as the host task which runs
the VCPU can migrate between CPUs at any time. So, we need to:
1. Add timesync information for each host CPU in the trace.dat file.
2. Track the migration between CPUs of each task that runs VCPU and
save that information
in the trace.dat file.

I was thinking about this too. And perhaps we can hold off until we find systems that have different values for mult and shift.

That said, we can easily add this information by recording the sched_switch events in a separate buffer. And I've been thinking about doing this by default anyway. More below.

Quoted 6 lines

2. When calculating the new timestamp of each guest event
(individually) - somehow find out on
which host CPU that guest event happened ?

Points 1 and 2 are doable, but will break the current trace.dat file option that holds the timesync information.

I don't think we need to have it in the timesync option. I think we can create another option to hold guest event data.

Quoted 3 lines

Point 3 is not clear to me, how we can get such information before the host and guest events are synchronised ?

My thoughts about this is. When we enable tracing of a guest (-A), we then create an instance on the host that records only kvm enter / exit events as well as sched switch events. Basically, enable all the events that we need to synchronize and show entering and exiting of the guest.

Quoted 8 lines

The synchronization logic already shows us what host thread controls each guest VCPU. If we record the kvm enter/exit and sched_switch events in a separate buffer, we can see when a host thread that runs a guest VCPU migrates to another CPU. Since the timestamps of those events are recorded in the meta events themselves (sched_switch), we know exactly where we need to use the new mult and shift values for the guest events.

Make sense?

Yes, but I have two concerns:
1. Recording kvm enter / exit events will make this implementation
KVM specific,
how about other hypervisors ?
2. The problem with finding guest event -> host CPU relation. We now only the timestamp of the guest event, not yet synchronized with the host
time. How will
find on what host CPU that guest event happened, as the host
task CPU migration
mapping is recorded with host time ?

Quoted 2 lines

-- Steve

Signature · 2 lines
Tzvetomir (Ceco) Stoyanov
VMware Open Source Technology Center
#12 lore raw

Re: [PATCH 5/5] [WIP] trace-cmd: Add new subcomand "trace-cmd perf"

Quoted 5 lines · On Fri, 19 Feb 2021 19:56:59 +0200 Tzvetomir Stoyanov <[email protected]>…
Quoted 1 line

Make sense?

Yes, but I have two concerns:
1. Recording kvm enter / exit events will make this implementation
KVM specific,
how about other hypervisors ?

I think this should all be part of the protocol. The option can be TRACECMD_OPTION_GUEST_METADATA, where that has a field for "enter/exit" events with CPU, vCPU, timestamp, and the also a note of sched switch events.

That is, the implementation will enable kvm events, but other trace-cmd plugins can implement other events. But what gets recorded into the trace.dat file can be post processed into a generic format.

Quoted 6 lines

2. The problem with finding guest event -> host CPU relation. We now only the timestamp of the guest event, not yet synchronized with the host
time. How will
find on what host CPU that guest event happened, as the host
task CPU migration
mapping is recorded with host time ?

It would be done all post processed. Here's the workflow I envision:

1. Run pre synchronization protocol between host/guest (ie. kvm, ptp)

2. Start the meta data events.
Start tracing guest enter/exit events along with scheduling. We may be able to even filter specifically if we know the threads a head of time, but that's just an optimization.
These events will be recorded raw into a file (with host threads saving the events to disk like it does for the tracing data). All this is in a separate instance.

3. Run tracing
Recorded events on the guest are sent to the host and stored in raw format on the host.
Optionally, events on the host is also recorded.

4. At the end of tracing
Stop the recording of tracing.
Stop the recording of meta data.
Run post synchronization protocol between host and guest.

5. Read the meta data events and convert them into a form of timestamp, enter/exit events, migration events. Yes, the timestamp will be that of the host.

A couple of things to understand with step 5, and assumptions we can make.

The scale factor between the host and guest for each VCPU should not change, even if the VCPU migrates. If it does, then there had to have been a kernel event where the kernel knew about this change, and we need to find a way to extract that. For now, we shouldn't worry about it, as I'm guessing that could be rather complex to manage even on the kernel end, and it would also be expensive for migrations.

I'm making a big assumption here, that either the different VCPUS have different scaling factors but the host scaling between physical CPUS are the same, or the physical CPUS have different scaling factors, but the VCPUS do not. So far I ran this on 4 different machines (including my laptop) and all had the same mult and shift on the host. Perhaps we just state that we do not support machines that do not have this.

Anyway, when all is done, the meta data events will map to the host. Using this mapping and the synchronization between the host and guest, we can map these migrations and such to the guest itself. And if the vCPUS are different (and we assume the host is the same for all), and we know when VCPU scheduled away from a physical CPU (from the host time), we can then figure out how to find the guest time when that happened.

Or did I miss something?

-- Steve