Skip to contentSkip to conversation

Timestamp synchronization of host - guest tracing session

PATCH Superseded Tzvetomir Stoyanov (VMware) 1 participant 8 messages Feb 25, 2021

v30 of 34 Superseded Latest is v34 →

lore
Share & tools
lore
#0 lore raw

v30 cover Timestamp synchronization of host - guest tracing session

Basic infrastructure for host - guest timestamp synchronization and a PoC implementation of PTP-like and KVM algorithms.

The KVM plugin is with higher weight than PTP, it is preferred in case both are active. KVM is used only if x86-tsc clock is selected for the current trace, PTP is used for all other cases.

v30 changes:
- Moved all time sync logic in the trace-cmd library.
- Separate the logig for pthread barrier time sync threads synhonization in its own patch.
v29 changes:
- Included <linux/types.h> in trace-timesync-kvm.c for __s64 type.
- Added pthread barrier to host time sync pthread, to ensure times are synchronized before starting the trace.
- Removed already merged patches from the set.
v28 changes:
- Fix bugs, introduced by previous trace-cmd commits, related to tracefs library usage.
- Removed unused type defines for trace packets.
v27 changes:
- Fixed broken compilation due to usage of old libtracefs APIs.
- Rewrote complex macros to follow the Linux kernel requirements for macros.
- Removed pathces from the set, that were already merged upstream.
v26 changes:
- Rebased on top of latest master.
- Abstracted Time sync protocol names in a structure, to avoid using triple char pointers.
- Removed a patch from the set, as it is already merged:
"trace-cmd: Add new libtrasefs API to get the current trace clock".
- Minor coding style changes, for better code readability.
v25 changes:
- Addressed Steven's comments.
- Reorded the patches in the plugin - put the PTP and KVM PoC patches last and all other fixes and improvements before them.
- Implemented a new libtrasefs API to get the current trace clock.
- Replaced IDs of trace timestamps synchronization protocols with strings.
- Implemented an "accuracy" parameter for timestamps synchronization protocols.
- Added "scaling ratio" correction, calculated by the timestamp synchronization protocols.
- Added flags, declared by the timestamps synchronization protocols, and stored in the trace.dat file, together with the calculated time offsets.
- Implemented timestamp offset calculation per virtual CPU.
v24 changes:
- trace-cmd internal refactoring, needed for KVM timestamp synchronization plugin.
- Added KVM timestamp synchronization plugin.

v23 changes:
- Added flags to PTP start message to control the behaviour of the algorithm. This is for development purposes mostly, to compare and evaluate how these changes affect the accuracy.
PTP_FLAG_FASTEST_RESPONSE: Consider only the probe with fastest
response time, otherwise make a histogram from all probes.
PTP_FLAG_USE_MARKER: Use trace marker to get the clock,
otherwise use directly the system clock

v22 changes, addressed Steven's comments:
- Fixed error flow in read_qemu_guests_pids(), free allocated resources in case of an error.
- Fixed initialisation of reallocated memmory in set_vcpu_pid_mapping().
- Fixed bitmask logic in tracecmd_tsync_proto_select().
- Fixed usage of wrong structure in make_trace_resp().

v21 changes:
- Rebased on top of latest master.
- Remove these two patches from the set, as they are already merged:
trace-cmd: Add new library API for local CPU count
trace-cmd: Add support for negative time offsets in trace.dat file
- Added more descriptive warning message when fails to extract Time Shift information from the trace.dat file.
- Added a warning message when fails to obtain vcpu - pid mappings.
- Handle the case with sparse VCPU numbers in VCPU - PID mapping array.
- Fixed broken recording over FIFOs.
v20 changes:
- Rebased on top of latest master.
- Removed the VCPUS_MAX hardcoded limit, reimplemented the cpu_pid[] array to be dynamically allocated.
- Added a warning when reading of TRACECMD_OPTION_TIME_SHIFT option fails, due to unexpected option's size.
- Improved loading of TRACECMD_OPTION_GUEST option data, as Steven suggested.
v19 changes:
- Rebased on top of latest master. The librtacefs is already merged, this allows to drop few patches from the set and use librtacefs APIs instead.
- Reimplemented all new trace.dat options to be in binary format, instead of text. Leverage the new "trace-cmd dump" sub command to track what is written in the file.
- Addressed Steven's comments.

v18 changes: addressed Steven Rostdet comments:
- Replaced semaphores with pthread mutexes.
- Made bitmask with time sync protocols unlimited, so we can support more than 32 protocols. That required to redesign the trace request packet format.
- A lot of small fixes.

v17 changes:
- Implemented new PTP logic for calculating the clocks offset, using histogram of all PTP samples. It gives better results than the logic with the fastest response time, so set the new one as default in the POC patch.

v16 changes:
- Fixed compilation in case no VSOCK is available (Thanks to Slavomir Kaslev)
- Fixed a typo in trace-cmd-record.1.txt (Thanks to Slavomir Kaslev)
- Added forgotten file in the patch "trace-cmd: Add new library APIs for ftrace instances." - trace-instance.c
- Fixed few compilation warnings related to TSYNC_DEBUG code.
- Removed a blank line at the end of "tsync_readme" file.

v15 changes:
- Removed the patch for "--proc-map" from the series, as it should not be part of it.

v14 changes:
- Bring back the PTP-like algorithm and removed the ftrace event based logic.
- Reimplemented the PTP-like algorithm to use raw ftrace markers, instead of clock_gettime() API.
- Refactored the logic to be algorithm independent and plugin friendly.
- Implemented continuous timestamps synchronization, while the trace is running.
- Moved logic from trace-cmd application to libtracecmd, as new library APIs.
- Implemented new trace id functionality.
- Implemented new guest section in host trace.dat file.

v13 changes:
- Remove few patches from the set, as they were merged.
- Rebased to the latest master, Slavomirs patchest "Add VM kernel tracing over vsockets and FIFOs" got merged!

v12 changes:
- Rebased on top of Slavomir's v13 "Add VM kernel tracing over vsockets and FIFOs"

v11 changes:
- Rebased on top of Slavomir's v10 "Add VM kernel tracing over vsockets and FIFOs"
- Addressed Slavomir's commnents from version 10 of the patch series.

v10 changes:
- Fixed broken compilation, call to timestamp_correction_calc() in timestamp_correct was smashed.
- Replaced deprecated tep_data_event_from_type() API with tep_find_event().
- Fixed a warning on assignment const to non const.

v9 changes:
- Fixed implementation of binary search algorithm in timestamp_correct()

v8 changes:
- Added rmdir() call in tracecmd_remove_instance(), to completely remove the instance. However, there is an issue with deleting the instances using rmdir(), which is investigated.
- Few changes in read_qemu_guests_pids(), timestamp_correct(), tsync_offset_load()
tracecmd_clock_context_new() and find_raw_events() suggested by Slavomir.

v7 changes:
- Added warning messages in case time synchronization cannot be negotiated or fails.
- Few optimizations and checks in read_qemu_guests_pids(), tsync_offset_load(), and find_raw_events(), suggested by Slavomir Kaslev.
- Reworked timestamp_correct() to not use static variables.
- Check TRACECMD_OPTION_TIME_SHIFT before reading time sync samples from the trace.dat file

v6 changes:
- Refactored tracecmd_msg_snd_time_sync() and tracecmd_msg_rcv_time_sync() functions:
removed any time sync calculations logic as separate functions in trace-timesync.c file
- Defined TSYNC_PROBE, TSYNC_REQ and TSYNC_RESP messages, in order to make the time sync protocol comprehensible.
- Addressed Steven Rostedt comments.
- Addressed Slavomir Kaslev commnets.

v5 changes:
- Rebased to Slavomir's v8 "Add VM kernel tracing over vsockets and FIFOs" patch series.
- Implemented an algorithm for time drift correction.
- Addressed Slavomir's commnets.
- Refactored the code: moved all time sync specific implementation in trace-timesync.c
- Isolated all hardcoded event specific stuff in a structure, so it could be easily moved to external plugins.
- Added a check for VSOCK support: do not perform vsock dependent time synchronisation in case there is no VSOCK support.

v4 changes:
- Removed the implementation of PTP-like algorithm. The current logic relies on matching time stamps of kvm_exit/virtio_transport_recv_pkt events on host to virtio_transport_alloc_pkt/vp_notify events on guest.
- Rebased to Slavomir's v7 "Add VM kernel tracing over vsockets and FIFOs" patch series.
- Decreased the time synch probes from 5000 to 300.
- Addressed Steven Rostedt comments.
- Code cleanup.

v3 changes:
- Removed any magic constants, used in the PTP-like algorithm, as Slavomir Kaslev suggested.
- Implemented new algorithm, based on mapping kvm_exit events in host context to vsock_send events in guest context, suggested by Steven Rostedt.

v2 changes:
- Addressed Steven Rostedt comments.
- Modified PTP-like timestamps sync algorithm to gain more accuracy, with the help of Yordan Karadzhov and Slavomir Kaslev.
Tzvetomir Stoyanov (VMware) (7):
trace-cmd: Add timestamp synchronization per vCPU
trace-cmd: Add dummy function to initialize timestamp sync logic
trace-cmd: Move time sync logic in the trace-cmd library
trace-cmd: Wait for first time sync before the trace
trace-cmd: [POC] PTP-like algorithm for host - guest timestamp
synchronization
trace-cmd: Debug scripts for PTP-like algorithm for host - guest
timestamp synchronization
trace-cmd [POC]: Add KVM timestamp synchronization plugin

 lib/trace-cmd/Makefile                        |   4 +-
 .../include/private/trace-cmd-private.h       |  35 +-
 lib/trace-cmd/include/trace-tsync-local.h     |  37 +-
 lib/trace-cmd/trace-input.c                   | 188 +++--
 lib/trace-cmd/trace-timesync-kvm.c            | 460 +++++++++++
 lib/trace-cmd/trace-timesync-ptp.c            | 715 ++++++++++++++++
 lib/trace-cmd/trace-timesync.c                | 761 ++++++++++++++++--
 scripts/debug/tsync_hist.py                   |  57 ++
 scripts/debug/tsync_readme                    |  12 +
 scripts/debug/tsync_res.py                    |  46 ++
 tracecmd/Makefile                             |   3 -
 tracecmd/include/trace-local.h                |   5 +-
 tracecmd/trace-agent.c                        |  22 +-
 tracecmd/trace-dump.c                         |  52 +-
 tracecmd/trace-record.c                       |  93 ++-
 tracecmd/trace-tsync.c                        | 294 -------
 16 files changed, 2248 insertions(+), 536 deletions(-)
 create mode 100644 lib/trace-cmd/trace-timesync-kvm.c
 create mode 100644 lib/trace-cmd/trace-timesync-ptp.c
 create mode 100644 scripts/debug/tsync_hist.py
 create mode 100644 scripts/debug/tsync_readme
 create mode 100644 scripts/debug/tsync_res.py
 delete mode 100644 tracecmd/trace-tsync.c
Signature · 1 line
2.29.2
#1 lore raw

PATCH v30 1/7 trace-cmd: Add timestamp synchronization per vCPU

Timestamp synchronization logic is changed to work per virtual CPU. Some hypervisors maintain time offset and scaling per vCPU. The host-guest communication protocol is changed to request time stamp offset calculation for particular vCPU. The guest thread, responsible for running that logic is pinned to the requested CPU. The time sync medata data, saved in the trace.dat file is changed to an array of vCPUs. When an event time stamp is corrected, the CPU on that the event happened is used to get the correct offset.

---
 .../include/private/trace-cmd-private.h       |   2 +-
 lib/trace-cmd/include/trace-tsync-local.h     |  22 +-
 lib/trace-cmd/trace-input.c                   | 188 ++++++++++------
 lib/trace-cmd/trace-timesync.c                | 213 +++++++++++++-----
 tracecmd/trace-dump.c                         |  52 +++--
 tracecmd/trace-tsync.c                        |  67 ++++--
 6 files changed, 372 insertions(+), 172 deletions(-)
lib/trace-cmd/include/private/trace-cmd-private.h +1 -1
index eddfd9eb..9369a9d3 100644
@@ -440,7 +440,7 @@ const char *tracecmd_tsync_proto_select(struct tracecmd_tsync_protos *protos, ch
 bool tsync_proto_is_supported(const char *proto_name);
 void tracecmd_tsync_with_host(struct tracecmd_time_sync *tsync);
 void tracecmd_tsync_with_guest(struct tracecmd_time_sync *tsync);
-int tracecmd_tsync_get_offsets(struct tracecmd_time_sync *tsync,
+int tracecmd_tsync_get_offsets(struct tracecmd_time_sync *tsync, int cpu,
 				int *count, long long **ts,
 				long long **offsets, long long **scalings);
 int tracecmd_tsync_get_proto_flags(struct tracecmd_time_sync *tsync,
lib/trace-cmd/include/trace-tsync-local.h +15 -7
index 83d1721a..d4281469 100644
@@ -8,12 +8,7 @@
 
 #include <stdbool.h>
 
-struct clock_sync_context {
-	void				*proto_data;	/* time sync protocol specific data */
-	bool				is_server;	/* server side time sync role */
-	bool				is_guest;	/* guest or host time sync role */
-	struct tracefs_instance		*instance;	/* ftrace buffer, used for time sync events */
-
+struct clock_sync_offsets {
 	/* Arrays with calculated time offsets at given time */
 	int				sync_size;	/* Allocated size of sync_ts,
 							 * sync_offsets and sync_scalings
@@ -24,6 +19,18 @@ struct clock_sync_context {
 	long long			*sync_ts;
 	long long			*sync_offsets;
 	long long			*sync_scalings;
+};
+
+struct clock_sync_context {
+	void				*proto_data;	/* time sync protocol specific data */
+	bool				is_server;	/* server side time sync role */
+	bool				is_guest;	/* guest or host time sync role */
+	struct tracefs_instance		*instance;	/* ftrace buffer, used for time sync events */
+
+	int				cpu_count;
+	struct clock_sync_offsets	*offsets;	/* Array of size cpu_count
+							 * calculated offsets per CPU
+							 */
 
 	/* Identifiers of local and remote time sync peers: cid and port */
 	unsigned int			local_cid;
@@ -37,7 +44,8 @@ int tracecmd_tsync_proto_register(const char *proto_name, int accuracy, int role
 				  int (*init)(struct tracecmd_time_sync *),
 				  int (*free)(struct tracecmd_time_sync *),
 				  int (*calc)(struct tracecmd_time_sync *,
-					      long long *, long long *, long long *));
+					      long long *, long long *,
+					      long long *, unsigned int));
 int tracecmd_tsync_proto_unregister(char *proto_name);
 
 int ptp_clock_sync_register(void);
lib/trace-cmd/trace-input.c +123 -65

297 lines not on this page · raw message

lib/trace-cmd/trace-timesync.c +158 -55

351 lines not on this page · raw message

tracecmd/trace-dump.c +29 -23

65 lines not on this page · raw message

tracecmd/trace-tsync.c +46 -21

103 lines not on this page · raw message

Signature · 1 line
2.29.2
#2 lore raw

PATCH v30 2/7 trace-cmd: Add dummy function to initialize timestamp sync logic

In reply to Tzvetomir Stoyanov (VMware)

A dummy empty function is added, will be used to initialize timestamp synchronization logic:
tracecmd_tsync_init()
When this code is implemented as real plugins, this function will be removed. Then the initializion will be triggered at plugin load time.

---
 lib/trace-cmd/trace-timesync.c |  8 ++++++++
 tracecmd/trace-agent.c         |  2 ++
 tracecmd/trace-record.c        | 23 +++++++++++++++--------
 3 files changed, 25 insertions(+), 8 deletions(-)
lib/trace-cmd/trace-timesync.c +8 -0
index 7c11ee1b..f49eafdd 100644
@@ -57,6 +57,14 @@ static struct tsync_proto *tsync_proto_find(const char *proto_name)
 	return NULL;
 }
 
+/**
+ * tracecmd_tsync_init - Initialize the global, per task, time sync data.
+ */
+void tracecmd_tsync_init(void)
+{
+
+}
+
 int tracecmd_tsync_proto_register(const char *proto_name, int accuracy, int roles,
 				  int supported_clocks, unsigned int flags,
 				  int (*init)(struct tracecmd_time_sync *),
tracecmd/trace-agent.c +2 -0
index ff4a4e11..36444d32 100644
@@ -248,6 +248,8 @@ static void agent_serve(unsigned int port)
 	if (sd < 0)
 		die("Failed to open vsocket");
 
+	tracecmd_tsync_init();
+
 	if (!get_local_cid(&cid))
 		printf("listening on @%u:%u\n", cid, port);
 
tracecmd/trace-record.c +15 -8
index efd96d27..cc870124 100644
@@ -6218,10 +6218,6 @@ static bool has_local_instances(void)
 	return false;
 }
 
-/*
- * This function contains common code for the following commands:
- * record, start, stream, profile.
- */
 static void record_trace(int argc, char **argv,
 			 struct common_record_context *ctx)
 {
@@ -6379,12 +6375,23 @@ static void record_trace(int argc, char **argv,
 	finalize_record_trace(ctx);
 }
 
+/*
+ * This function contains common code for the following commands:
+ * record, start, stream, profile.
+ */
+static void record_trace_command(int argc, char **argv,
+				 struct common_record_context *ctx)
+{
+	tracecmd_tsync_init();
+	record_trace(argc, argv, ctx);
+}
+
 void trace_start(int argc, char **argv)
 {
 	struct common_record_context ctx;
 
 	parse_record_options(argc, argv, CMD_start, &ctx);
-	record_trace(argc, argv, &ctx);
+	record_trace_command(argc, argv, &ctx);
 	exit(0);
 }
 
@@ -6476,7 +6483,7 @@ void trace_stream(int argc, char **argv)
 	struct common_record_context ctx;
 
 	parse_record_options(argc, argv, CMD_stream, &ctx);
-	record_trace(argc, argv, &ctx);
+	record_trace_command(argc, argv, &ctx);
 	exit(0);
 }
 
@@ -6495,7 +6502,7 @@ void trace_profile(int argc, char **argv)
 	if (!buffer_instances)
 		top_instance.flags |= BUFFER_FL_PROFILE;
 
-	record_trace(argc, argv, &ctx);
+	record_trace_command(argc, argv, &ctx);
 	do_trace_profile();
 	exit(0);
 }
@@ -6505,7 +6512,7 @@ void trace_record(int argc, char **argv)
 	struct common_record_context ctx;
 
 	parse_record_options(argc, argv, CMD_record, &ctx);
-	record_trace(argc, argv, &ctx);
+	record_trace_command(argc, argv, &ctx);
 	exit(0);
 }
 
Signature · 1 line
2.29.2
#3 lore raw

PATCH v30 3/7 trace-cmd: Move time sync logic in the trace-cmd library

In reply to Tzvetomir Stoyanov (VMware)

The whole timestamp synchronization logic is moved in the trace-cmd library. The logic is abstracted, the application receives a time sync context which represents the synchronization session. These library APIs can be used to control the synchronization session:

---
 lib/trace-cmd/Makefile                        |   2 -
 .../include/private/trace-cmd-private.h       |  33 +-
 lib/trace-cmd/include/trace-tsync-local.h     |  16 +
 lib/trace-cmd/trace-timesync.c                | 528 ++++++++++++++++--
 tracecmd/Makefile                             |   3 -
 tracecmd/include/trace-local.h                |   5 +-
 tracecmd/trace-agent.c                        |  20 +-
 tracecmd/trace-record.c                       |  70 ++-
 tracecmd/trace-tsync.c                        | 319 -----------
 9 files changed, 590 insertions(+), 406 deletions(-)
 delete mode 100644 tracecmd/trace-tsync.c
lib/trace-cmd/Makefile +0 -2
index 841c84f1..2f553ed5 100644
@@ -17,9 +17,7 @@ OBJS += trace-util.o
 OBJS += trace-filter-hash.o
 OBJS += trace-msg.o
 OBJS += trace-plugin.o
-ifeq ($(VSOCK_DEFINED), 1)
 OBJS += trace-timesync.o
-endif
 
 # Additional util objects
 OBJS += trace-blk-hack.o
lib/trace-cmd/include/private/trace-cmd-private.h +15 -18
index 9369a9d3..9f3cc539 100644
@@ -405,6 +405,7 @@ const char *tracecmd_clock_id2str(enum tracecmd_clocks clock);
 
 /* --- Timestamp synchronization --- */
 
+struct tracecmd_time_sync;
 #define TRACECMD_TSYNC_PNAME_LENGTH	16
 #define TRACECMD_TSYNC_PROTO_NONE	"none"
 
@@ -418,34 +419,30 @@ enum tracecmd_time_sync_role {
 	TRACECMD_TIME_SYNC_ROLE_GUEST	= (1 << 1),
 };
 
-struct tracecmd_time_sync {
-	const char			*proto_name;
-	int				loop_interval;
-	pthread_mutex_t			lock;
-	pthread_cond_t			cond;
-	char				*clock_str;
-	struct tracecmd_msg_handle	*msg_handle;
-	void				*context;
-	int				guest_pid;
-	int				vcpu_count;
-};
-
 /* Timestamp synchronization flags */
 #define TRACECMD_TSYNC_FLAG_INTERPOLATE	0x1
 
 void tracecmd_tsync_init(void);
 int tracecmd_tsync_proto_getall(struct tracecmd_tsync_protos **protos, const char *clock, int role);
-const char *tracecmd_tsync_proto_select(struct tracecmd_tsync_protos *protos, char *clock,
-					enum tracecmd_time_sync_role role);
 bool tsync_proto_is_supported(const char *proto_name);
-void tracecmd_tsync_with_host(struct tracecmd_time_sync *tsync);
-void tracecmd_tsync_with_guest(struct tracecmd_time_sync *tsync);
+struct tracecmd_time_sync *
+tracecmd_tsync_with_host(struct tracecmd_tsync_protos *tsync_protos,
+			 const char *clock);
+int tracecmd_tsync_with_host_stop(struct tracecmd_time_sync *tsync);
+struct tracecmd_time_sync *
+tracecmd_tsync_with_guest(unsigned long long trace_id, int loop_interval,
+			  unsigned int cid, unsigned int port, int guest_pid,
+			  int guest_cpus, const char *proto_name, const char *clock);
+int tracecmd_tsync_with_guest_stop(struct tracecmd_time_sync *tsync);
 int tracecmd_tsync_get_offsets(struct tracecmd_time_sync *tsync, int cpu,
 				int *count, long long **ts,
 				long long **offsets, long long **scalings);
-int tracecmd_tsync_get_proto_flags(struct tracecmd_time_sync *tsync,
-				   unsigned int *flags);
+int tracecmd_tsync_get_session_params(struct tracecmd_time_sync *tsync,
+				      char **selected_proto,
+				      unsigned int *tsync_port);
 void tracecmd_tsync_free(struct tracecmd_time_sync *tsync);
+int tracecmd_write_guest_time_shift(struct tracecmd_output *handle,
+				    struct tracecmd_time_sync *tsync);
 
 /* --- Plugin handling --- */
 extern struct tep_plugin_option trace_ftrace_options[];
lib/trace-cmd/include/trace-tsync-local.h +16 -0
index d4281469..b3a3bdfc 100644
@@ -8,6 +8,22 @@
 
 #include <stdbool.h>
 
+struct tracecmd_time_sync {
+	pthread_t			thread;
+	bool				thread_running;
+	unsigned long long		trace_id;
+	char				*proto_name;
+	int				loop_interval;
+	pthread_mutex_t			lock;
+	pthread_cond_t			cond;
+	pthread_barrier_t		first_sync;
+	char				*clock_str;
+	struct tracecmd_msg_handle	*msg_handle;
+	void				*context;
+	int				guest_pid;
+	int				vcpu_count;
+};
+
 struct clock_sync_offsets {
 	/* Arrays with calculated time offsets at given time */
 	int				sync_size;	/* Allocated size of sync_ts,
lib/trace-cmd/trace-timesync.c +496 -32

617 lines not on this page · raw message

tracecmd/Makefile +0 -3
index 2b14284b..80c69bbb 100644
@@ -36,9 +36,6 @@ TRACE_CMD_OBJS += trace-usage.o
 TRACE_CMD_OBJS += trace-dump.o
 TRACE_CMD_OBJS += trace-clear.o
 TRACE_CMD_OBJS += trace-vm.o
-ifeq ($(VSOCK_DEFINED), 1)
-TRACE_CMD_OBJS += trace-tsync.o
-endif
 
 ifeq ($(VSOCK_DEFINED), 1)
 TRACE_CMD_OBJS += trace-agent.o
tracecmd/include/trace-local.h +2 -3
index 77271712..6e39d27d 100644
@@ -262,9 +262,8 @@ struct buffer_instance {
 	int			*fds;
 	bool			use_fifos;
 
-	pthread_t		tsync_thread;
-	bool			tsync_thread_running;
-	struct tracecmd_time_sync tsync;
+	int			tsync_loop_interval;
+	struct tracecmd_time_sync *tsync;
 };
 
 void init_top_instance(void);
tracecmd/trace-agent.c +11 -9
index 36444d32..0edfa60f 100644
@@ -143,12 +143,12 @@ static char *get_clock(int argc, char **argv)
 static void agent_handle(int sd, int nr_cpus, int page_size)
 {
 	struct tracecmd_tsync_protos *tsync_protos = NULL;
+	struct tracecmd_time_sync *tsync = NULL;
 	struct tracecmd_msg_handle *msg_handle;
-	const char *tsync_proto = NULL;
+	char *tsync_proto = NULL;
 	unsigned long long trace_id;
 	unsigned int tsync_port = 0;
 	unsigned int *ports;
-	pthread_t sync_thr;
 	char **argv = NULL;
 	int argc = 0;
 	bool use_fifos;
@@ -176,10 +176,11 @@ static void agent_handle(int sd, int nr_cpus, int page_size)
 	if (!use_fifos)
 		make_vsocks(nr_cpus, fds, ports);
 	if (tsync_protos && tsync_protos->names) {
-		tsync_proto = tracecmd_guest_tsync(tsync_protos,
-						   get_clock(argc, argv),
-						   &tsync_port, &sync_thr);
-		if (!tsync_proto)
+		tsync = tracecmd_tsync_with_host(tsync_protos,
+						 get_clock(argc, argv));
+		if (tsync)
+			tracecmd_tsync_get_session_params(tsync, &tsync_proto, &tsync_port);
+		else
 			warning("Failed to negotiate timestamps synchronization with the host");
 	}
 	trace_id = tracecmd_generate_traceid();
@@ -192,9 +193,10 @@ static void agent_handle(int sd, int nr_cpus, int page_size)
 	trace_record_agent(msg_handle, nr_cpus, fds, argc, argv,
 			   use_fifos, trace_id);
 
-	if (tsync_proto)
-		pthread_join(sync_thr, NULL);
-
+	if (tsync) {
+		tracecmd_tsync_with_host_stop(tsync);
+		tracecmd_tsync_free(tsync);
+	}
 	if (tsync_protos) {
 		free(tsync_protos->names);
 		free(tsync_protos);
tracecmd/trace-record.c +50 -20

126 lines not on this page · raw message

tracecmd/trace-tsync.c deleted +0 -319

319 lines not on this page · raw message

Signature · 1 line
2.29.2
#4 lore raw

PATCH v30 4/7 trace-cmd: Wait for first time sync before the trace

In reply to Tzvetomir Stoyanov (VMware)

Added a barrier in time synchronization threads to ensure the first time synchronization passed before to start the trace.

---
 lib/trace-cmd/trace-timesync.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
lib/trace-cmd/trace-timesync.c +14 -1
index d38ee975..1e8ba509 100644
@@ -571,6 +571,7 @@ void tracecmd_tsync_free(struct tracecmd_time_sync *tsync)
 	}
 	pthread_mutex_destroy(&tsync->lock);
 	pthread_cond_destroy(&tsync->cond);
+	pthread_barrier_destroy(&tsync->first_sync);
 	free(tsync->clock_str);
 	free(tsync->proto_name);
 	free(tsync);
@@ -753,6 +754,7 @@ static int tsync_with_guest(struct tracecmd_time_sync *tsync)
 	int ts_array_size = CLOCK_TS_ARRAY;
 	struct tsync_proto *proto;
 	struct timespec timeout;
+	bool first = true;
 	bool end = false;
 	int ret;
 	int i;
@@ -777,6 +779,10 @@ static int tsync_with_guest(struct tracecmd_time_sync *tsync)
 			if (ret)
 				break;
 		}
+		if (first) {
+			first = false;
+			pthread_barrier_wait(&tsync->first_sync);
+		}
 		if (end || i < tsync->vcpu_count)
 			break;
 		if (tsync->loop_interval > 0) {
@@ -804,12 +810,17 @@ static int tsync_with_guest(struct tracecmd_time_sync *tsync)
 static void *tsync_host_thread(void *data)
 {
 	struct tracecmd_time_sync *tsync = NULL;
+	int ret;
 
 	tsync = (struct tracecmd_time_sync *)data;
-	tsync_with_guest(tsync);
+	ret = tsync_with_guest(tsync);
 	tracecmd_msg_handle_close(tsync->msg_handle);
 	tsync->msg_handle = NULL;
 
+	/* tsync with guest failed, release the barrier */
+	if (ret)
+		pthread_barrier_wait(&tsync->first_sync);
+
 	pthread_exit(0);
 }
 
@@ -868,6 +879,7 @@ tracecmd_tsync_with_guest(unsigned long long trace_id, int loop_interval,
 		tsync->clock_str = strdup(clock);
 	pthread_mutex_init(&tsync->lock, NULL);
 	pthread_cond_init(&tsync->cond, NULL);
+	pthread_barrier_init(&tsync->first_sync, NULL, 2);
 	pthread_attr_init(&attrib);
 	pthread_attr_setdetachstate(&attrib, PTHREAD_CREATE_JOINABLE);
 
@@ -878,6 +890,7 @@ tracecmd_tsync_with_guest(unsigned long long trace_id, int loop_interval,
 
 	if (!get_first_cpu(&pin_mask, &mask_size))
 		pthread_setaffinity_np(tsync->thread, mask_size, pin_mask);
+	pthread_barrier_wait(&tsync->first_sync);
 
 	if (pin_mask)
 		CPU_FREE(pin_mask);
Signature · 1 line
2.29.2
#5 lore raw

PATCH v30 5/7 trace-cmd: [POC] PTP-like algorithm for host - guest timestamp synchronization

In reply to Tzvetomir Stoyanov (VMware)

PTP protocol is designed for synchronizing clocks of machines in a local network. The same approach can be used for host - guest timestamp synchronization. This implementation uses ftrace raw markers to track trace timestamps of PTP events. The patch is a POC, two different algorithms for PTP calculations are proposed:
- Choosing the sample with the fastest response time for calculating the clocks offset.
- Calculating the clocks offset using the average of all PTP samples.

The implementation can be tuned using those parameters:
- #define FASTEST_RESPONSE - is defined, the sample with the fastest response time is used for calculating the clocks offset. Otherwise the histogram of all samples is used.
- #define PTP_SYNC_LOOP 340 - defines the number of samples, used for one calculation.
- --tsync-interval - a trace-cmd argument, choose the intervals between offset calculations, performed continuously during the trace.
- #define TSYNC_DEBUG - if defined, a debug information is collected and stored in files, in the guest machine:
s-cid*.txt - For each offset calculation: host and guest clocks and calculated offset. res-cid*.txt - For each tracing session: all calculated clock offsets.

---
 lib/trace-cmd/Makefile             |   3 +
 lib/trace-cmd/trace-timesync-ptp.c | 715 +++++++++++++++++++++++++++++
 lib/trace-cmd/trace-timesync.c     |   4 +-
 3 files changed, 721 insertions(+), 1 deletion(-)
 create mode 100644 lib/trace-cmd/trace-timesync-ptp.c
lib/trace-cmd/Makefile +3 -0
index 2f553ed5..e66c7b5f 100644
@@ -18,6 +18,9 @@ OBJS += trace-filter-hash.o
 OBJS += trace-msg.o
 OBJS += trace-plugin.o
 OBJS += trace-timesync.o
+ifeq ($(VSOCK_DEFINED), 1)
+OBJS += trace-timesync-ptp.o
+endif
 
 # Additional util objects
 OBJS += trace-blk-hack.o
lib/trace-cmd/trace-timesync-ptp.c new file +715 -0

715 lines not on this page · raw message

lib/trace-cmd/trace-timesync.c +3 -1
index 1e8ba509..f939d34b 100644
@@ -64,7 +64,9 @@ static struct tsync_proto *tsync_proto_find(const char *proto_name)
  */
 void tracecmd_tsync_init(void)
 {
-
+#ifdef VSOCK
+	ptp_clock_sync_register();
+#endif
 }
 
 int tracecmd_tsync_proto_register(const char *proto_name, int accuracy, int roles,
Signature · 1 line
2.29.2
#6 lore raw

PATCH v30 6/7 trace-cmd: Debug scripts for PTP-like algorithm for host - guest timestamp synchronization

In reply to Tzvetomir Stoyanov (VMware)

These scripts can be used to visualise debug files, written when the PTP-like algorithm is compiled with TSYNC_DEBUG defined. The files are located in the guest machine:
s-cid*.txt - For each offset calculation: host and guest clocks and calculated offset. res-cid*.txt - For each tracing session: all calculated clock offsets.

tsync_hist.py plots a histogram, using data from a s-cid*.txt file:

	"python tsync_hist.py s-cid2_1.txt"

tsync_res.py plots a line, using data from res-cid*.txt file:
"python tsync_res.py res-cid2.txt"

---
 scripts/debug/tsync_hist.py | 57 +++++++++++++++++++++++++++++++++++++
 scripts/debug/tsync_readme  | 12 ++++++++
 scripts/debug/tsync_res.py  | 46 ++++++++++++++++++++++++++++++
 3 files changed, 115 insertions(+)
 create mode 100644 scripts/debug/tsync_hist.py
 create mode 100644 scripts/debug/tsync_readme
 create mode 100644 scripts/debug/tsync_res.py
scripts/debug/tsync_hist.py new file +57 -0
new file mode 100644
index 00000000..819d1e8f
@@ -0,0 +1,57 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Copyright (C) 2019, VMware Inc, Tzvetomir Stoyanov <[email protected]>
+# Copyright (C) 2019, VMware Inc, Yordan Karadzhov <[email protected]>
+
+
+import matplotlib.pyplot as plt
+import matplotlib.lines as mlines
+import numpy as np
+import sys
+
+def newline(p1, p2):
+    ax = plt.gca()
+    xmin, xmax = ax.get_xbound()
+
+    if(p2[0] == p1[0]):
+        xmin = xmax = p1[0]
+        ymin, ymax = ax.get_ybound()
+    else:
+        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
+        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])
+
+    l = mlines.Line2D([xmin,xmax], [ymin,ymax], color='red')
+    ax.add_line(l)
+    return l
+
+
+data = np.loadtxt(fname = sys.argv[1])
+selected_ts  = data[-1, 1]
+selected_ofs = data[-1, 0]
+data = data[:-1,:]
+
+x = data[:, 1] - data[:, 0]
+
+mean = x.mean()
+std = x.std()
+
+num_bins = 500
+min = x.min() #+ .4 * (x.max() - x.min())
+max = x.max() #- .4 * (x.max() - x.min())
+bins = np.linspace(min, max, num_bins, endpoint = False, dtype=int)
+
+fig, ax = plt.subplots()
+
+# the histogram of the data
+n, bins, patches = ax.hist(x, bins, histtype=u'step');
+
+ax.set_xlabel('clock offset [$\mu$s]')
+ax.set_ylabel('entries')
+ax.set_title("$\sigma$=%i" % std)
+
+x1, y1 = [selected_ofs, min], [selected_ofs, max]
+newline(x1, y1)
+
+# Tweak spacing to prevent clipping of ylabel
+fig.tight_layout()
+plt.show()
scripts/debug/tsync_readme new file +12 -0
new file mode 100644
index 00000000..f3ebb25d
@@ -0,0 +1,12 @@
+PTP-like algorithm debug
+========================
+
+tsync_*.py scripts can be used to visualise debug files, written when the PTP-like algorithm
+is compiled with TSYNC_DEBUG defined. The files are located in the guest machine:
+    s-cid*.txt - For each offset calculation: host and guest clocks and calculated offset.
+    res-cid*.txt - For each tracing session: all calculated clock offsets.
+
+tsync_hist.py plots a histogram, using data from a s-cid*.txt file:
+	"python tsync_hist.py s-cid2_1.txt"
+tsync_res.py plots a line, using data from res-cid*.txt file:
+	"python tsync_res.py res-cid2.txt"
scripts/debug/tsync_res.py new file +46 -0

46 lines not on this page · raw message

Signature · 1 line
2.29.2
#7 lore raw

PATCH v30 7/7 trace-cmd [POC]: Add KVM timestamp synchronization plugin

In reply to Tzvetomir Stoyanov (VMware)

Added new timestamp synchronization plugin for KVM hosts. It reads the clock offsets directly from the KVM debug filesystem, if available. The plugin works only with x86-tsc ftrace clock.

---
 lib/trace-cmd/Makefile                    |   1 +
 lib/trace-cmd/include/trace-tsync-local.h |   1 +
 lib/trace-cmd/trace-timesync-kvm.c        | 460 ++++++++++++++++++++++
 lib/trace-cmd/trace-timesync.c            |   1 +
 4 files changed, 463 insertions(+)
 create mode 100644 lib/trace-cmd/trace-timesync-kvm.c
lib/trace-cmd/Makefile +1 -0
index e66c7b5f..b1a07a04 100644
@@ -20,6 +20,7 @@ OBJS += trace-plugin.o
 OBJS += trace-timesync.o
 ifeq ($(VSOCK_DEFINED), 1)
 OBJS += trace-timesync-ptp.o
+OBJS += trace-timesync-kvm.o
 endif
 
 # Additional util objects
lib/trace-cmd/include/trace-tsync-local.h +1 -0
index b3a3bdfc..7e56d187 100644
@@ -65,5 +65,6 @@ int tracecmd_tsync_proto_register(const char *proto_name, int accuracy, int role
 int tracecmd_tsync_proto_unregister(char *proto_name);
 
 int ptp_clock_sync_register(void);
+int kvm_clock_sync_register(void);
 
 #endif /* _TRACE_TSYNC_LOCAL_H */
lib/trace-cmd/trace-timesync-kvm.c new file +460 -0

460 lines not on this page · raw message

lib/trace-cmd/trace-timesync.c +1 -0
index f939d34b..7514766a 100644
@@ -66,6 +66,7 @@ void tracecmd_tsync_init(void)
 {
 #ifdef VSOCK
 	ptp_clock_sync_register();
+	kvm_clock_sync_register();
 #endif
 }
 
Signature · 1 line
2.29.2