Skip to contentSkip to conversation

trace: Update the trace feature to work with trace-cmd

PATCH In review Simon Glass 3 participants 27 messages Jan 15, 2023 – Feb 12, 2023 Library code

lore
Share & tools
lore
#0 lore raw

cover trace: Update the trace feature to work with trace-cmd

Since U-Boot's tracing feature was originally written, quite a few changes have taken place in this domain. The original text format used by tracing is still emitted by Linux, but a new trace-cmd tool has invented a binary format which is now used by new tools, such as kernelshark.

With recent distributions and the move to Python 3, the old pybootchart tool does not build or run. Unfortunately there is no 1:1 replacement for the features that were provided by pybootchart, or at least it is not obvious. Still, it makes sense to keep with the times.

This series updates proftool to use the new binary format, adding support for function and funcgraph tracing, so that U-Boot's trace records can be examined by trace-cmd and kernelshark.

This series also adds support for a flamegraph, which provides a visual way to see which functions are called a lot, as well as which ones consume the most time.

Some minor updates to the trace implementation within U-Boot are included, to provide a little more information and to fix a few problems.

No unit tests are provided by proftool, but a functional test ensures that sandbox can emit traces which can be processed by proftool, then parsed by trace-cmd and that the timing of the various formats looks consistent.

Simon Glass (24):
.gitignore: Ignore the moveconfig database
sandbox: Expand the space for sandbox_vpl
sandbox: Bring back setting mon_len in global_data
dm: Allow serial output during the relocation process
timer: Tidy up use of notrace
time: Tidy up some unnecessary #ifdefs
trace: Reduce the default for TRACE_EARLY_CALL_DEPTH_LIMIT
abuf: Support use from tools
trace: Update the file header
trace: Reduce the number of function sites
trace: Track the minimum stack depth
trace: Show a few more stats about tracing
trace: Correct the relocation handover with buffer overflow
trace: Detect an infinite loop
trace: Rename prof to trace and improve comments
trace: Update proftool to use new binary format
trace: Drop use of objsection
trace: Use text_base from the trace header
trace: Support output of funcgraph records
trace: Support output of a flamegraph
trace: Provide a flamegraph that uses timing
Docker: Support trace-cmd
trace: Add a test
trace: Update documentation

 .azure-pipelines.yml                   |    8 +
 .gitattributes                         |    1 +
 .gitignore                             |    3 +
 .gitlab-ci.yml                         |   12 +
 arch/sandbox/dts/sandbox_vpl.dtsi      |    4 +-
 common/board_f.c                       |    3 +
 common/board_r.c                       |    9 +
 doc/develop/pics/flamegraph.png        |  Bin 0 -> 48224 bytes
 doc/develop/pics/flamegraph_timing.png |  Bin 0 -> 31305 bytes
 doc/develop/pics/flamegraph_zoom.png   |  Bin 0 -> 25465 bytes
 doc/develop/pics/kernelshark.png       |  Bin 0 -> 29617 bytes
 doc/develop/pics/kernelshark_fg.png    |  Bin 0 -> 28899 bytes
 doc/develop/trace.rst                  |  281 ++++-
 doc/usage/cmd/trace.rst                |  163 +++
 doc/usage/index.rst                    |    1 +
 drivers/core/device.c                  |    3 +-
 drivers/timer/timer-uclass.c           |    2 +-
 include/timer.h                        |   13 +-
 include/trace.h                        |   18 +-
 lib/Kconfig                            |    2 +-
 lib/abuf.c                             |   21 +-
 lib/time.c                             |   14 +-
 lib/trace.c                            |   93 +-
 test/py/tests/test_trace.py            |  304 +++++
 tools/Makefile                         |    3 +
 tools/docker/Dockerfile                |   16 +
 tools/proftool.c                       | 1598 ++++++++++++++++++++++--
 27 files changed, 2345 insertions(+), 227 deletions(-)
 create mode 100644 doc/develop/pics/flamegraph.png
 create mode 100644 doc/develop/pics/flamegraph_timing.png
 create mode 100644 doc/develop/pics/flamegraph_zoom.png
 create mode 100644 doc/develop/pics/kernelshark.png
 create mode 100644 doc/develop/pics/kernelshark_fg.png
 create mode 100644 doc/usage/cmd/trace.rst
 create mode 100644 test/py/tests/test_trace.py
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#1 lore raw

PATCH 1/24 .gitignore: Ignore the moveconfig database

This file is produced by the moveconfig.py tool. It should never be added to the repo, so add it to the .gitignore file.

---

 .gitignore | 3 +++
 1 file changed, 3 insertions(+)
.gitignore +3 -0
index eb769f144c3..357bcfe9917 100644
@@ -104,3 +104,6 @@ __pycache__
 # pylint files
 /pylint.cur
 /pylint.out/
+
+# moveconfig database
+/moveconfig.db
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#2 lore raw

PATCH 2/24 sandbox: Expand the space for sandbox_vpl

In reply to Simon Glass

This is quite near the limit so add a little more space.

---

 arch/sandbox/dts/sandbox_vpl.dtsi | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/sandbox/dts/sandbox_vpl.dtsi +2 -2
index 1fba537f135..6966eeff7b3 100644
@@ -17,8 +17,8 @@
 		 * provide plenty of space for ELF files with debug info so that
 		 * gdb can be used
 		 */
-		offset = <0x400000>;
-		size = <0xdffc00>;
+		offset = <0x500000>;
+		size = <0xcffc00>;
 
 		fit {
 			fit,external-offset = <0>;
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#3 lore raw

PATCH 3/24 sandbox: Bring back setting mon_len in global_data

In reply to Simon Glass

This change was made for the benefit of RISC-V but broke other architectures also. In particular, tracing cannot work without this value. Add it back for architectures which support it.

Fixes 3c9fc23c443 ("sandbox: don't refer to symbol _init")

---

 common/board_f.c | 3 +++
 1 file changed, 3 insertions(+)
common/board_f.c +3 -0
index 2b4edf30c93..f3c1ab53b1c 100644
@@ -290,7 +290,10 @@ static int setup_mon_len(void)
 {
 #if defined(__ARM__) || defined(__MICROBLAZE__)
 	gd->mon_len = (ulong)&__bss_end - (ulong)_start;
+#elif defined(CONFIG_SANDBOX) && !defined(__riscv)
+	gd->mon_len = (ulong)&_end - (ulong)_init;
 #elif defined(CONFIG_SANDBOX)
+	/* gcc does not provide _init in crti.o on RISC-V */
 	gd->mon_len = 0;
 #elif defined(CONFIG_EFI_APP)
 	gd->mon_len = (ulong)&_end - (ulong)_init;
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#4 lore raw

PATCH 4/24 dm: Allow serial output during the relocation process

In reply to Simon Glass

Reset the serial flags so that the debug UART can be used (if enabled) in the small window where there is no serial device. This can avoid a hang in some cases.

---

 common/board_r.c | 9 +++++++++
 1 file changed, 9 insertions(+)
common/board_r.c +9 -0
index 3618acad437..5f3c3db476d 100644
@@ -796,6 +796,15 @@ static init_fnc_t init_sequence_r[] = {
 
 void board_init_r(gd_t *new_gd, ulong dest_addr)
 {
+	/*
+	 * The pre-relocation drivers may be using memory that has now gone
+	 * away. Mark serial as unavailable - this will fall back to the debug
+	 * UART if available.
+	 *
+	 * Do the same with log drivers since the memory may not be available.
+	 */
+	gd->flags &= ~(GD_FLG_SERIAL_READY | GD_FLG_LOG_READY);
+
 	/*
 	 * Set up the new global data pointer. So far only x86 does this
 	 * here.
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#5 lore raw

PATCH 5/24 timer: Tidy up use of notrace

In reply to Simon Glass

Tracing is typically enabled by the time driver model starts up, so there is no point in adding a 'notrace' to the timer-init function. However, once the driver model timer is enabled, we do need to be able to access the timer's private data when reading the timer, so add it to the core function needed for that.

Update the function's documentation while we are here.

---

 drivers/core/device.c        |  3 ++-
 drivers/timer/timer-uclass.c |  2 +-
 include/timer.h              | 13 +++++++++----
 3 files changed, 12 insertions(+), 6 deletions(-)
drivers/core/device.c +2 -1
index d9ce546c0c4..6e26b64fb81 100644
@@ -654,7 +654,8 @@ void *dev_get_priv(const struct udevice *dev)
 	return dm_priv_to_rw(dev->priv_);
 }
 
-void *dev_get_uclass_priv(const struct udevice *dev)
+/* notrace is needed as this is called by timer_get_rate() */
+notrace void *dev_get_uclass_priv(const struct udevice *dev)
 {
 	if (!dev) {
 		dm_warn("%s: null device\n", __func__);
drivers/timer/timer-uclass.c +1 -1
index bb719792135..f4b871ac23a 100644
@@ -136,7 +136,7 @@ u64 timer_conv_64(u32 count)
 	return ((u64)gd->timebase_h << 32) | gd->timebase_l;
 }
 
-int notrace dm_timer_init(void)
+int dm_timer_init(void)
 {
 	struct udevice *dev = NULL;
 	__maybe_unused ofnode node;
include/timer.h +9 -4
index d33a26e28fe..311ce6b2c3a 100644
@@ -9,11 +9,16 @@
 #define timer_get_ops(dev)	((struct timer_ops *)(dev)->driver->ops)
 
 /**
- * dm_timer_init() - initialize a timer for time keeping. On success
- * initializes gd->timer so that lib/timer can use it for future
- * referrence.
+ * dm_timer_init() - set up a timer for time keeping
  *
- * Return: 0 on success or error number
+ * Sets up gd->timer if the device is not already bound, making sure it is
+ * probed and ready for use
+ *
+ * On success, inits gd->timer so that lib/timer can use it for future reference
+ *
+ * Returns: 0 on success, -EAGAIN if driver model is not ready yet, -ENODEV if
+ * no timer could be found, other error if the timer could not be bound or
+ * probed
  */
 int dm_timer_init(void);
 
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#6 lore raw

PATCH 6/24 time: Tidy up some unnecessary #ifdefs

In reply to Simon Glass

Avoid using the preprocessor with TIMER_EARLY.

---

 lib/time.c | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)
lib/time.c +6 -8
index 0c95d12f614..1ef58f92cd1 100644
@@ -70,15 +70,14 @@ extern unsigned long timer_read_counter(void);
 ulong notrace get_tbclk(void)
 {
 	if (!gd->timer) {
-#ifdef CONFIG_TIMER_EARLY
-		return timer_early_get_rate();
-#else
 		int ret;
 
+		if (IS_ENABLED(CONFIG_TIMER_EARLY))
+			return timer_early_get_rate();
+
 		ret = dm_timer_init();
 		if (ret)
 			return ret;
-#endif
 	}
 
 	return timer_get_rate(gd->timer);
@@ -90,15 +89,14 @@ uint64_t notrace get_ticks(void)
 	int ret;
 
 	if (!gd->timer) {
-#ifdef CONFIG_TIMER_EARLY
-		return timer_early_get_count();
-#else
 		int ret;
 
+		if (IS_ENABLED(CONFIG_TIMER_EARLY))
+			return timer_early_get_count();
+
 		ret = dm_timer_init();
 		if (ret)
 			panic("Could not initialize timer (err %d)\n", ret);
-#endif
 	}
 
 	ret = timer_get_count(gd->timer, &count);
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#7 lore raw

PATCH 7/24 trace: Reduce the default for TRACE_EARLY_CALL_DEPTH_LIMIT

In reply to Simon Glass

This is a silly value at present, since U-Boot's call depth never reaches
200. Fix it.

---

 lib/Kconfig | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/Kconfig +1 -1
index a83f32d82a5..11968a0c531 100644
@@ -368,7 +368,7 @@ config TRACE_EARLY_SIZE
 config TRACE_EARLY_CALL_DEPTH_LIMIT
 	int "Early trace call depth limit"
 	depends on TRACE_EARLY
-	default 200
+	default 15
 	help
 	  Sets the maximum call depth up to which function calls are recorded
 	  during early tracing.
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#8 lore raw

Re: [PATCH 07/24] trace: Reduce the default for TRACE_EARLY_CALL_DEPTH_LIMIT

Am 15. Januar 2023 22:15:44 MEZ schrieb Simon Glass <[email protected]>:

Quoted 17 lines

This is a silly value at present, since U-Boot's call depth never reaches
200. Fix it.

---

lib/Kconfig | 2 +-

1 file changed, 1 insertion(+), 1 deletion(-)
lib/Kconfig +0 -0
index a83f32d82a5..11968a0c531 100644
@@ -368,7 +368,7 @@ config TRACE_EARLY_SIZE

config TRACE_EARLY_CALL_DEPTH_LIMIT
int "Early trace call depth limit"
depends on TRACE_EARLY

lib/Kconfig config TRACE_EARLY_SIZE · line 371

Quoted 1 line
lib/Kconfig +0 -1
-	default 200

The call depth when running the EFI SCT by far exceeds 15.

Is the suggested change relevant after reaching the cli?

Did you measure the actual call depth?

Best regards

Heinrich

Quoted 4 lines
lib/Kconfig +1 -0
+	default 15

help
Sets the maximum call depth up to which function calls are recorded during early tracing.

#9 lore raw

PATCH 8/24 abuf: Support use from tools

In reply to Simon Glass

Update the code slightly so that abuf can be used in U-Boot tools. It will soon be needed for proftool.

---

 lib/abuf.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
lib/abuf.c +20 -1
index 1635d58682c..bd270467dd4 100644
@@ -6,11 +6,14 @@
  * Written by Simon Glass <[email protected]>
  */
 
+#ifndef USE_HOSTCC
 #include <common.h>
-#include <abuf.h>
 #include <malloc.h>
 #include <mapmem.h>
 #include <string.h>
+#endif
+
+#include <abuf.h>
 
 void abuf_set(struct abuf *abuf, void *data, size_t size)
 {
@@ -19,10 +22,26 @@ void abuf_set(struct abuf *abuf, void *data, size_t size)
 	abuf->size = size;
 }
 
+#ifndef USE_HOSTCC
 void abuf_map_sysmem(struct abuf *abuf, ulong addr, size_t size)
 {
 	abuf_set(abuf, map_sysmem(addr, size), size);
 }
+#else
+/* copied from lib/string.c for convenience */
+static char *memdup(const void *src, size_t len)
+{
+	char *p;
+
+	p = malloc(len);
+	if (!p)
+		return NULL;
+
+	memcpy(p, src, len);
+
+	return p;
+}
+#endif
 
 bool abuf_realloc(struct abuf *abuf, size_t new_size)
 {
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#10 lore raw

PATCH 9/24 trace: Update the file header

In reply to Simon Glass

It seems better to put the TEXT_BASE value in the file header rather than in an entry record. While it is true that there is a separate base for pre-relocation, this can be handled by using offsets in the file.

It is useful to have a version number in case we need to change the trace format again.

Update the header to make these changes.

---

 include/trace.h | 12 ++++++++++--
 lib/trace.c     | 19 ++++---------------
 2 files changed, 14 insertions(+), 17 deletions(-)
include/trace.h +10 -2
index e7aee024f03..2be8d81b515 100644
@@ -6,6 +6,8 @@
 #ifndef __TRACE_H
 #define __TRACE_H
 
+/* this file is included from a tool so uses uint32_t instead of u32, etc. */
+
 enum {
 	/*
 	 * This affects the granularity of our trace. We can bin function
@@ -23,6 +25,8 @@ enum {
 	 * this value.
 	 */
 	FUNC_SITE_SIZE	= 4,	/* distance between function sites */
+
+	TRACE_VERSION	= 1,
 };
 
 enum trace_chunk_type {
@@ -39,7 +43,11 @@ struct trace_output_func {
 /* A header at the start of the trace output buffer */
 struct trace_output_hdr {
 	enum trace_chunk_type type;	/* Record type */
-	size_t rec_count;		/* Number of records */
+	uint32_t version;		/* Version (TRACE_VERSION) */
+	uint32_t rec_count;		/* Number of records */
+	uint32_t spare;			/* 0 */
+	uint64_t text_base;		/* Value of CONFIG_TEXT_BASE */
+	uint64_t spare2;		/* 0 */
 };
 
 /* Print statistics about traced function calls */
@@ -63,7 +71,7 @@ int trace_list_functions(void *buff, size_t buff_size, size_t *needed);
 enum ftrace_flags {
 	FUNCF_EXIT		= 0UL << 30,
 	FUNCF_ENTRY		= 1UL << 30,
-	FUNCF_TEXTBASE		= 2UL << 30,
+	/* two more values are available */
 
 	FUNCF_TIMESTAMP_MASK	= 0x3fffffff,
 };
lib/trace.c +4 -15
index b9dc6d2e4b5..2e2c1bed54f 100644
@@ -118,18 +118,6 @@ static void notrace add_ftrace(void *func_ptr, void *caller, ulong flags)
 	hdr->ftrace_count++;
 }
 
-static void notrace add_textbase(void)
-{
-	if (hdr->ftrace_count < hdr->ftrace_size) {
-		struct trace_call *rec = &hdr->ftrace[hdr->ftrace_count];
-
-		rec->func = CONFIG_TEXT_BASE;
-		rec->caller = 0;
-		rec->flags = FUNCF_TEXTBASE;
-	}
-	hdr->ftrace_count++;
-}
-
 /**
  * __cyg_profile_func_enter() - record function entry
  *
@@ -278,8 +266,11 @@ int trace_list_calls(void *buff, size_t buff_size, size_t *needed)
 
 	/* Update the header */
 	if (output_hdr) {
+		memset(output_hdr, '\0', sizeof(*output_hdr));
 		output_hdr->rec_count = upto;
 		output_hdr->type = TRACE_CHUNK_CALLS;
+		output_hdr->version = TRACE_VERSION;
+		output_hdr->text_base = CONFIG_TEXT_BASE;
 	}
 
 	/* Work out how must of the buffer we used */
@@ -385,10 +376,9 @@ int notrace trace_init(void *buff, size_t buff_size)
 	/* Use any remaining space for the timed function trace */
 	hdr->ftrace = (struct trace_call *)(buff + needed);
 	hdr->ftrace_size = (buff_size - needed) / sizeof(*hdr->ftrace);
-	add_textbase();
+	hdr->depth_limit = CONFIG_TRACE_CALL_DEPTH_LIMIT;
 
 	puts("trace: enabled\n");
-	hdr->depth_limit = CONFIG_TRACE_CALL_DEPTH_LIMIT;
 	trace_enabled = 1;
 	trace_inited = 1;
 
@@ -426,7 +416,6 @@ int notrace trace_early_init(void)
 	/* Use any remaining space for the timed function trace */
 	hdr->ftrace = (struct trace_call *)((char *)hdr + needed);
 	hdr->ftrace_size = (buff_size - needed) / sizeof(*hdr->ftrace);
-	add_textbase();
 	hdr->depth_limit = CONFIG_TRACE_EARLY_CALL_DEPTH_LIMIT;
 	printf("trace: early enable at %08x\n", CONFIG_TRACE_EARLY_ADDR);
 
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#11 lore raw

PATCH 10/24 trace: Reduce the number of function sites

In reply to Simon Glass

Given that the compiler adds two function calls into each function, the current spacing is overkill. Drop it down to 16 bytes per function, which is still plenty. This saves some space in the trace buffer.

Also move the calculation into a function, so it is common code. Add a check for gd->mon_len being unset, which breaks tracing.

---

 include/trace.h |  6 ++++--
 lib/trace.c     | 19 +++++++++++++++++--
 2 files changed, 21 insertions(+), 4 deletions(-)
include/trace.h +4 -2
index 2be8d81b515..763d6d1255a 100644
@@ -17,14 +17,16 @@ enum {
 	 *
 	 * The value here assumes a minimum instruction size of 4 bytes,
 	 * or that instructions are 2 bytes but there are at least 2 of
-	 * them in every function.
+	 * them in every function. Given that each function needs a call to
+	 * __cyg_profile_func_enter() and __cyg_profile_func_exit() as well,
+	 * we cannot have functions smaller that 16 bytes.
 	 *
 	 * Increasing this value reduces the number of functions we can
 	 * resolve, but reduces the size of the uintptr_t array used for
 	 * our function list, which is the length of the code divided by
 	 * this value.
 	 */
-	FUNC_SITE_SIZE	= 4,	/* distance between function sites */
+	FUNC_SITE_SIZE	= 16,	/* distance between function sites */
 
 	TRACE_VERSION	= 1,
 };
lib/trace.c +17 -2
index 2e2c1bed54f..12dae2089a4 100644
@@ -321,6 +321,17 @@ void notrace trace_set_enabled(int enabled)
 	trace_enabled = enabled != 0;
 }
 
+static int get_func_count(void)
+{
+	/* Detect no support for mon_len since this means tracing cannot work */
+	if (IS_ENABLED(CONFIG_SANDBOX) && !gd->mon_len) {
+		puts("Tracing is not supported on this board\n");
+		return -ENOTSUPP;
+	}
+
+	return gd->mon_len / FUNC_SITE_SIZE;
+}
+
 /**
  * trace_init() - initialize the tracing system and enable it
  *
@@ -330,10 +341,12 @@ void notrace trace_set_enabled(int enabled)
  */
 int notrace trace_init(void *buff, size_t buff_size)
 {
-	ulong func_count = gd->mon_len / FUNC_SITE_SIZE;
+	int func_count = get_func_count();
 	size_t needed;
 	int was_disabled = !trace_enabled;
 
+	if (func_count < 0)
+		return func_count;
 	trace_save_gd();
 
 	if (!was_disabled) {
@@ -393,10 +406,12 @@ int notrace trace_init(void *buff, size_t buff_size)
  */
 int notrace trace_early_init(void)
 {
-	ulong func_count = gd->mon_len / FUNC_SITE_SIZE;
+	int func_count = get_func_count();
 	size_t buff_size = CONFIG_TRACE_EARLY_SIZE;
 	size_t needed;
 
+	if (func_count < 0)
+		return func_count;
 	/* We can ignore additional calls to this function */
 	if (trace_enabled)
 		return 0;
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#12 lore raw

PATCH 11/24 trace: Track the minimum stack depth

In reply to Simon Glass

The trace does not necessarily start at the top level, so we can see it go negative. Track this so that we can show an accurate value for the stack depth.

---

 lib/trace.c | 24 ++++++++++++++++--------
 1 file changed, 16 insertions(+), 8 deletions(-)
lib/trace.c +16 -8
index 12dae2089a4..3551ef3a23c 100644
@@ -35,9 +35,10 @@ struct trace_hdr {
 	ulong ftrace_count;	/* Num. of ftrace records written */
 	ulong ftrace_too_deep_count;	/* Functions that were too deep */
 
-	int depth;
-	int depth_limit;
-	int max_depth;
+	int depth;		/* Depth of function calls */
+	int depth_limit;	/* Depth limit to trace to */
+	int max_depth;		/* Maximum depth seen so far */
+	int min_depth;		/* Minimum depth seen so far */
 };
 
 /* Pointer to start of trace buffer */
@@ -142,7 +143,7 @@ void notrace __cyg_profile_func_enter(void *func_ptr, void *caller)
 			hdr->untracked_count++;
 		}
 		hdr->depth++;
-		if (hdr->depth > hdr->depth_limit)
+		if (hdr->depth > hdr->max_depth)
 			hdr->max_depth = hdr->depth;
 		trace_swap_gd();
 	}
@@ -158,8 +159,10 @@ void notrace __cyg_profile_func_exit(void *func_ptr, void *caller)
 {
 	if (trace_enabled) {
 		trace_swap_gd();
-		add_ftrace(func_ptr, caller, FUNCF_EXIT);
 		hdr->depth--;
+		add_ftrace(func_ptr, caller, FUNCF_EXIT);
+		if (hdr->depth < hdr->min_depth)
+			hdr->min_depth = hdr->depth;
 		trace_swap_gd();
 	}
 }
@@ -309,8 +312,10 @@ void trace_print_stats(void)
 		printf(" (%lu dropped due to overflow)",
 		       hdr->ftrace_count - hdr->ftrace_size);
 	}
-	puts("\n");
-	printf("%15d maximum observed call depth\n", hdr->max_depth);
+
+	/* Add in minimum depth since the trace did not start at top level */
+	printf("\n%15d maximum observed call depth\n",
+	       hdr->max_depth - hdr->min_depth);
 	printf("%15d call depth limit\n", hdr->depth_limit);
 	print_grouped_ull(hdr->ftrace_too_deep_count, 10);
 	puts(" calls not traced due to depth\n");
@@ -381,8 +386,10 @@ int notrace trace_init(void *buff, size_t buff_size)
 		return -ENOSPC;
 	}
 
-	if (was_disabled)
+	if (was_disabled) {
 		memset(hdr, '\0', needed);
+		hdr->min_depth = INT_MAX;
+	}
 	hdr->func_count = func_count;
 	hdr->call_accum = (uintptr_t *)(hdr + 1);
 
@@ -427,6 +434,7 @@ int notrace trace_early_init(void)
 	memset(hdr, '\0', needed);
 	hdr->call_accum = (uintptr_t *)(hdr + 1);
 	hdr->func_count = func_count;
+	hdr->min_depth = INT_MAX;
 
 	/* Use any remaining space for the timed function trace */
 	hdr->ftrace = (struct trace_call *)((char *)hdr + needed);
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#13 lore raw

PATCH 12/24 trace: Show a few more stats about tracing

In reply to Simon Glass

Add a few more useful items into the output. Update the buffers to use hex consistently.

---

 lib/trace.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
lib/trace.c +6 -2
index 3551ef3a23c..c3354a256fb 100644
@@ -319,6 +319,10 @@ void trace_print_stats(void)
 	printf("%15d call depth limit\n", hdr->depth_limit);
 	print_grouped_ull(hdr->ftrace_too_deep_count, 10);
 	puts(" calls not traced due to depth\n");
+	print_grouped_ull(hdr->ftrace_size, 10);
+	puts(" max function calls\n");
+	printf("\ntrace buffer %lx call records %lx\n",
+	       (ulong)map_to_sysmem(hdr), (ulong)map_to_sysmem(hdr->ftrace));
 }
 
 void notrace trace_set_enabled(int enabled)
@@ -381,7 +385,7 @@ int notrace trace_init(void *buff, size_t buff_size)
 	hdr = (struct trace_hdr *)buff;
 	needed = sizeof(*hdr) + func_count * sizeof(uintptr_t);
 	if (needed > buff_size) {
-		printf("trace: buffer size %zd bytes: at least %zd needed\n",
+		printf("trace: buffer size %zx bytes: at least %zx needed\n",
 		       buff_size, needed);
 		return -ENOSPC;
 	}
@@ -426,7 +430,7 @@ int notrace trace_early_init(void)
 	hdr = map_sysmem(CONFIG_TRACE_EARLY_ADDR, CONFIG_TRACE_EARLY_SIZE);
 	needed = sizeof(*hdr) + func_count * sizeof(uintptr_t);
 	if (needed > buff_size) {
-		printf("trace: buffer size is %zd bytes, at least %zd needed\n",
+		printf("trace: buffer size is %zx bytes, at least %zx needed\n",
 		       buff_size, needed);
 		return -ENOSPC;
 	}
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#14 lore raw

PATCH 13/24 trace: Correct the relocation handover with buffer overflow

In reply to Simon Glass

When the early trace buffer overflows it leaves a gap in the trace buffer between where the actual data finished and where it would have finished if there were enough buffer space. This results in corrupted output.

Adjust the logic to resolve this and add a message when the buffer overflows.

---

 lib/trace.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
lib/trace.c +10 -3
index c3354a256fb..bbc316af295 100644
@@ -360,8 +360,8 @@ int notrace trace_init(void *buff, size_t buff_size)
 
 	if (!was_disabled) {
 #ifdef CONFIG_TRACE_EARLY
+		ulong used, count;
 		char *end;
-		ulong used;
 
 		/*
 		 * Copy over the early trace data if we have it. Disable
@@ -370,12 +370,19 @@ int notrace trace_init(void *buff, size_t buff_size)
 		trace_enabled = 0;
 		hdr = map_sysmem(CONFIG_TRACE_EARLY_ADDR,
 				 CONFIG_TRACE_EARLY_SIZE);
-		end = (char *)&hdr->ftrace[min(hdr->ftrace_count,
-					       hdr->ftrace_size)];
+		count = min(hdr->ftrace_count, hdr->ftrace_size);
+		end = (char *)&hdr->ftrace[count];
 		used = end - (char *)hdr;
 		printf("trace: copying %08lx bytes of early data from %x to %08lx\n",
 		       used, CONFIG_TRACE_EARLY_ADDR,
 		       (ulong)map_to_sysmem(buff));
+		printf("%lu traced function calls", count);
+		if (hdr->ftrace_count > hdr->ftrace_size) {
+			printf(" (%lu dropped due to overflow)",
+			       hdr->ftrace_count - hdr->ftrace_size);
+			hdr->ftrace_count = hdr->ftrace_size;
+		}
+		puts("\n");
 		memcpy(buff, hdr, used);
 #else
 		puts("trace: already enabled\n");
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#15 lore raw

PATCH 14/24 trace: Detect an infinite loop

In reply to Simon Glass

If something is wrong with a board's timer function such that it calls functions not marked with notrace, U-Boot will hang.

Detect this, print a message and disable the trace.

---

 lib/trace.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
lib/trace.c +10 -0
index bbc316af295..1091a5793a1 100644
@@ -39,6 +39,7 @@ struct trace_hdr {
 	int depth_limit;	/* Depth limit to trace to */
 	int max_depth;		/* Maximum depth seen so far */
 	int min_depth;		/* Minimum depth seen so far */
+	bool trace_locked;	/* Used to detect recursive tracing */
 };
 
 /* Pointer to start of trace buffer */
@@ -133,6 +134,14 @@ void notrace __cyg_profile_func_enter(void *func_ptr, void *caller)
 	if (trace_enabled) {
 		int func;
 
+		if (hdr->trace_locked) {
+			trace_enabled = 0;
+			puts("trace: recursion detected, disabling\n");
+			hdr->trace_locked = false;
+			return;
+		}
+
+		hdr->trace_locked = true;
 		trace_swap_gd();
 		add_ftrace(func_ptr, caller, FUNCF_ENTRY);
 		func = func_ptr_to_num(func_ptr);
@@ -146,6 +155,7 @@ void notrace __cyg_profile_func_enter(void *func_ptr, void *caller)
 		if (hdr->depth > hdr->max_depth)
 			hdr->max_depth = hdr->depth;
 		trace_swap_gd();
+		hdr->trace_locked = false;
 	}
 }
 
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#16 lore raw

PATCH 15/24 trace: Rename prof to trace and improve comments

In reply to Simon Glass

The current use of 'profile' in some places is confusing. Update the code to use the word 'trace' consistently. Change the flags to better match their meaning and add some more comments.

---

 tools/proftool.c | 196 +++++++++++++++++++++++++++++++++++++----------
 1 file changed, 157 insertions(+), 39 deletions(-)
tools/proftool.c +157 -39
index b66ea556486..6aa157c8b59 100644
@@ -26,38 +26,62 @@ enum {
 	FUNCF_TRACE	= 1 << 0,	/* Include this function in trace */
 };
 
+/**
+ * struct func_info - information recorded for each function
+ *
+ * @offset: Function offset in the image, measured from the text_base
+ * @name: Function name
+ * @code_size: Total code size of the function
+ * @flags: Either 0 or FUNCF_TRACE
+ * @objsection: the section this function is in
+ */
 struct func_info {
 	unsigned long offset;
 	const char *name;
 	unsigned long code_size;
-	unsigned long call_count;
 	unsigned flags;
-	/* the section this function is in */
 	struct objsection_info *objsection;
 };
 
+/**
+ * enum trace_line_type - whether to include or exclude a function
+ *
+ * @TRACE_LINE_INCLUDE: Include the function
+ * @TRACE_LINE_EXCLUDE: Exclude the function
+ */
 enum trace_line_type {
 	TRACE_LINE_INCLUDE,
 	TRACE_LINE_EXCLUDE,
 };
 
+/**
+ * struct trace_configline_info - information about a config-file line
+ *
+ * @next: Next line
+ * @type: Line type
+ * @name: identifier name / wildcard
+ * @regex: Regex to use if name starts with '/'
+ */
 struct trace_configline_info {
 	struct trace_configline_info *next;
 	enum trace_line_type type;
-	const char *name;	/* identifier name / wildcard */
-	regex_t regex;		/* Regex to use if name starts with / */
+	const char *name;
+	regex_t regex;
 };
 
 /* The contents of the trace config file */
 struct trace_configline_info *trace_config_head;
 
+/* list of all functions in System.map file, sorted by offset in the image */
 struct func_info *func_list;
-int func_count;
-struct trace_call *call_list;
-int call_count;
+
+int func_count;			/* number of functions */
+struct trace_call *call_list;	/* list of all calls in the input trace file */
+int call_count;			/* number of calls */
 int verbose;	/* Verbosity level 0=none, 1=warn, 2=notice, 3=info, 4=debug */
-unsigned long text_offset;		/* text address of first function */
+ulong text_offset;		/* text address of first function */
 
+/* debugging helpers */
 static void outf(int level, const char *fmt, ...)
 		__attribute__ ((format (__printf__, 2, 3)));
 #define error(fmt, b...) outf(0, fmt, ##b)
@@ -66,7 +90,6 @@ static void outf(int level, const char *fmt, ...)
 #define info(fmt, b...) outf(3, fmt, ##b)
 #define debug(fmt, b...) outf(4, fmt, ##b)
 
-
 static void outf(int level, const char *fmt, ...)
 {
 	if (verbose >= level) {
@@ -84,16 +107,24 @@ static void usage(void)
 		"Usage: proftool [-cmtv] <cmd> <profdata>\n"
 		"\n"
 		"Commands\n"
-		"   dump-ftrace\t\tDump out textual data in ftrace format\n"
+		"   dump-ftrace\t\tDump out records in ftrace format for use by trace-cmd\n"
 		"\n"
 		"Options:\n"
-		"   -c <cfg>\tSpecific config file\n"
+		"   -c <cfg>\tSpecify config file\n"
 		"   -m <map>\tSpecify Systen.map file\n"
+		"   -o <fname>\tSpecify output file\n"
 		"   -t <fname>\tSpecify trace data file (from U-Boot 'trace calls')\n"
 		"   -v <0-4>\tSpecify verbosity\n");
 	exit(EXIT_FAILURE);
 }
 
+/**
+ * h_cmp_offset - bsearch() function to compare two functions bny their offset
+ *
+ * @v1: Pointer to first function (struct func_info)
+ * @v2: Pointer to second function (struct func_info)
+ * Returns: < 0 if v1 offset < v2 offset, 0 if equal, > 0 otherwise
+ */
 static int h_cmp_offset(const void *v1, const void *v2)
 {
 	const struct func_info *f1 = v1, *f2 = v2;
@@ -101,6 +132,15 @@ static int h_cmp_offset(const void *v1, const void *v2)
 	return (f1->offset / FUNC_SITE_SIZE) - (f2->offset / FUNC_SITE_SIZE);
 }
 
+/**
+ * read_system_map() - read the System.map file to create a list of functions
+ *
+ * This also reads the text_offset value, since we assume that the first text
+ * symbol is at that address
+ *
+ * @fin: File to read
+ * Returns: 0 if OK, non-zero on error
+ */
 static int read_system_map(FILE *fin)
 {
 	unsigned long offset, start = 0;
@@ -152,6 +192,7 @@ static int read_system_map(FILE *fin)
 	}
 	notice("%d functions found in map file\n", func_count);
 	text_offset = start;
+
 	return 0;
 }
 
@@ -163,13 +204,22 @@ static int read_data(FILE *fin, void *buff, int size)
 	if (!err)
 		return 1;
 	if (err != size) {
-		error("Cannot read profile file at pos %lx\n", ftell(fin));
+		error("Cannot read trace file at pos %lx\n", ftell(fin));
 		return -1;
 	}
 	return 0;
 }
 
-static struct func_info *find_func_by_offset(uint32_t offset)
+/**
+ * find_func_by_offset() - Look up a function by its offset
+ *
+ * @offset: Offset to search for, from text_base
+ * Returns: function, if found, else NULL
+ *
+ * This does a fast search for a function given its offset from text_base
+ *
+ */
+static struct func_info *find_func_by_offset(uint offset)
 {
 	struct func_info key, *found;
 
@@ -180,8 +230,17 @@ static struct func_info *find_func_by_offset(uint32_t offset)
 	return found;
 }
 
-/* This finds the function which contains the given offset */
-static struct func_info *find_caller_by_offset(uint32_t offset)
+/**
+ * find_caller_by_offset() - finds the function which contains the given offset
+ *
+ * @offset: Offset to search for, from text_base
+ * Returns: function, if found, else NULL
+ *
+ * If the offset falls between two functions, then it is assumed to belong to
+ * the first function (with the lowest offset). This is a way of figuring out
+ * which function owns code at a particular offset
+ */
+static struct func_info *find_caller_by_offset(uint offset)
 {
 	int low;	/* least function that could be a match */
 	int high;	/* greated function that could be a match */
@@ -206,6 +265,15 @@ static struct func_info *find_caller_by_offset(uint32_t offset)
 	return low >= 0 ? &func_list[low] : NULL;
 }
 
+/**
+ * read_calls() - Read the list of calls from the trace data
+ *
+ * The calls are stored consecutively in the trace output produced by U-Boot
+ *
+ * @fin: File to read from
+ * @count: Number of calls to read
+ * Returns: 0 if OK, -1 on error
+ */
 static int read_calls(FILE *fin, size_t count)
 {
 	struct trace_call *call_data;
@@ -222,16 +290,24 @@ static int read_calls(FILE *fin, size_t count)
 	call_data = call_list;
 	for (i = 0; i < count; i++, call_data++) {
 		if (read_data(fin, call_data, sizeof(*call_data)))
-			return 1;
+			return -1;
 	}
 	return 0;
 }
 
-static int read_profile(FILE *fin, int *not_found)
+/**
+ * read_trace() - Read the U-Boot trace file
+ *
+ * Read in the calls from the trace file. The function list is ignored at
+ * present
+ *
+ * @fin: File to read
+ * Returns 0 if OK, non-zero on error
+ */
+static int read_trace(FILE *fin)
 {
 	struct trace_output_hdr hdr;
 
-	*not_found = 0;
 	while (!feof(fin)) {
 		int err;
 
@@ -255,6 +331,14 @@ static int read_profile(FILE *fin, int *not_found)
 	return 0;
 }
 
+/**
+ * read_map_file() - Read the System.map file
+ *
+ * This reads the file into the func_list array
+ *
+ * @fname: Filename to read
+ * Returns 0 if OK, non-zero on error
+ */
 static int read_map_file(const char *fname)
 {
 	FILE *fmap;
@@ -272,28 +356,30 @@ static int read_map_file(const char *fname)
 	return err;
 }
 
-static int read_profile_file(const char *fname)
+/**
+ * read_trace_file() - Open and read the U-Boot trace file
+ *
+ * Read in the calls from the trace file. The function list is ignored at
+ * present
+ *
+ * @fin: File to read
+ * Returns 0 if OK, non-zero on error
+ */
+static int read_trace_file(const char *fname)
 {
-	int not_found = INT_MAX;
 	FILE *fprof;
 	int err;
 
 	fprof = fopen(fname, "rb");
 	if (!fprof) {
-		error("Cannot open profile data file '%s'\n",
+		error("Cannot open trace data file '%s'\n",
 		      fname);
 		return 1;
 	} else {
-		err = read_profile(fprof, &not_found);
+		err = read_trace(fprof);
 		fclose(fprof);
 		if (err)
 			return err;
-
-		if (not_found) {
-			warn("%d profile functions could not be found in the map file - are you sure that your profile data and map file correspond?\n",
-			     not_found);
-			return 1;
-		}
 	}
 	return 0;
 }
@@ -344,6 +430,7 @@ static void check_trace_config_line(struct trace_configline_info *item)
 	}
 }
 
+/** check_trace_config() - Check trace-config file, reporting any problems */
 static void check_trace_config(void)
 {
 	struct trace_configline_info *line;
@@ -377,6 +464,21 @@ static void check_functions(void)
 	     not_found, removed_code_size);
 }
 
+/**
+ * read_trace_config() - read the trace-config file
+ *
+ * This file consists of lines like:
+ *
+ * include-func <regex>
+ * exclude-func <regex>
+ *
+ * where <regex> is a regular expression matched against function names. It
+ * allows some functions to be dropped from the trace when producing ftrace
+ * records
+ *
+ * @fin: File to process
+ * Returns: 0 if OK, -1 on error
+ */
 static int read_trace_config(FILE *fin)
 {
 	char buff[200];
@@ -400,8 +502,7 @@ static int read_trace_config(FILE *fin)
 		if (!*s || *s == '#')
 			continue;
 
-		line = (struct trace_configline_info *)calloc(1,
-							      sizeof(*line));
+		line = (struct trace_configline_info *)calloc(1, sizeof(*line));
 		if (!line) {
 			error("Cannot allocate config line\n");
 			return -1;
@@ -540,15 +641,25 @@ static int make_ftrace(void)
 	return 0;
 }
 
+/**
+ * prof_tool() - Performs requested action
+ *
+ * @argc: Number of arguments (used to obtain the command
+ * @argv: List of arguments
+ * @trace_fname: Filename of input file (trace data from U-Boot)
+ * @map_fname: Filename of map file (System.map from U-Boot)
+ * @trace_config_fname: Trace-configuration file, or NULL if none
+ * @out_fname: Output filename
+ */
 static int prof_tool(int argc, char *const argv[],
-		     const char *prof_fname, const char *map_fname,
-		     const char *trace_config_fname)
+		     const char *trace_fname, const char *map_fname,
+		     const char *trace_config_fname, const char *out_fname)
 {
 	int err = 0;
 
 	if (read_map_file(map_fname))
 		return -1;
-	if (prof_fname && read_profile_file(prof_fname))
+	if (trace_fname && read_trace_file(trace_fname))
 		return -1;
 	if (trace_config_fname && read_trace_config_file(trace_config_fname))
 		return -1;
@@ -572,27 +683,27 @@ int main(int argc, char *argv[])
 	const char *map_fname = "System.map";
 	const char *trace_fname = NULL;
 	const char *config_fname = NULL;
+	const char *out_fname = NULL;
 	int opt;
 
 	verbose = 2;
-	while ((opt = getopt(argc, argv, "c:m:t:v:")) != -1) {
+	while ((opt = getopt(argc, argv, "c:m:o:t:v:")) != -1) {
 		switch (opt) {
 		case 'c':
 			config_fname = optarg;
 			break;
-
 		case 'm':
 			map_fname = optarg;
 			break;
-
+		case 'o':
+			out_fname = optarg;
+			break;
 		case 't':
 			trace_fname = optarg;
 			break;
-
 		case 'v':
 			verbose = atoi(optarg);
 			break;
-
 		default:
 			usage();
 		}
@@ -601,6 +712,13 @@ int main(int argc, char *argv[])
 	if (argc < 1)
 		usage();
 
+	if (!out_fname || !map_fname || !trace_fname) {
+		fprintf(stderr,
+			"Must provide trace data, System.map file and output file\n");
+		usage();
+	}
+
 	debug("Debug enabled\n");
-	return prof_tool(argc, argv, trace_fname, map_fname, config_fname);
+	return prof_tool(argc, argv, trace_fname, map_fname, config_fname,
+			 out_fname);
 }
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#17 lore raw

PATCH 16/24 trace: Update proftool to use new binary format

In reply to Simon Glass

The old text format is not much used anymore. Instead a new trace-cmd tool has introduced a binary format for trace records.

Add support for generating this format. This involves removing the old text format, adding various helpers for the new format and adjusting the code to use an output file instead of stdout.

---

 tools/Makefile   |   3 +
 tools/proftool.c | 896 ++++++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 854 insertions(+), 45 deletions(-)
tools/Makefile +3 -0
index edfa40903d9..269bedd206e 100644
@@ -225,7 +225,10 @@ HOSTCFLAGS_ubsha1.o := -pedantic
 
 hostprogs-$(CONFIG_ARCH_KIRKWOOD) += kwboot
 hostprogs-$(CONFIG_ARCH_MVEBU) += kwboot
+
 hostprogs-y += proftool
+proftool-objs = proftool.o lib/abuf.o
+
 hostprogs-$(CONFIG_STATIC_RELA) += relocate-rela
 hostprogs-$(CONFIG_RISCV) += prelink-riscv
 
tools/proftool.c +851 -45

955 lines not on this page · raw message

Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#18 lore raw

PATCH 17/24 trace: Drop use of objsection

In reply to Simon Glass

This feature was only partly implemented and serves no current purpose. Drop it.

---

 tools/proftool.c | 29 +----------------------------
 1 file changed, 1 insertion(+), 28 deletions(-)
tools/proftool.c +1 -28
index feeef55c1b9..0d74e1169a9 100644
@@ -95,14 +95,12 @@ enum trace_type {
  * @name: Function name
  * @code_size: Total code size of the function
  * @flags: Either 0 or FUNCF_TRACE
- * @objsection: the section this function is in
  */
 struct func_info {
 	unsigned long offset;
 	const char *name;
 	unsigned long code_size;
 	unsigned flags;
-	struct objsection_info *objsection;
 };
 
 /**
@@ -540,31 +538,6 @@ static void check_trace_config(void)
 		check_trace_config_line(line);
 }
 
-/**
- * Check the functions to see if they each have an objsection. If not, then
- * the linker must have eliminated them.
- */
-static void check_functions(void)
-{
-	struct func_info *func, *end;
-	unsigned long removed_code_size = 0;
-	int not_found = 0;
-
-	/* Look for missing functions */
-	for (func = func_list, end = func + func_count; func < end; func++) {
-		if (!func->objsection) {
-			removed_code_size += func->code_size;
-			not_found++;
-		}
-	}
-
-	/* Figure out what functions we want to trace */
-	check_trace_config();
-
-	warn("%d functions removed by linker, %ld code size\n",
-	     not_found, removed_code_size);
-}
-
 /**
  * read_trace_config() - read the trace-config file
  *
@@ -1460,7 +1433,7 @@ static int prof_tool(int argc, char *const argv[],
 	if (trace_config_fname && read_trace_config_file(trace_config_fname))
 		return -1;
 
-	check_functions();
+	check_trace_config();
 
 	for (; argc; argc--, argv++) {
 		const char *cmd = *argv;
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#19 lore raw

PATCH 18/24 trace: Use text_base from the trace header

In reply to Simon Glass

Use the information in the trace header instead of reading it from the trace records. Add debugging to check that System.map and the trace header agree on this value.

---

 tools/proftool.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
tools/proftool.c +6 -1
index 0d74e1169a9..b5b8a9f7938 100644
@@ -179,6 +179,7 @@ struct trace_call *call_list;	/* list of all calls in the input trace file */
 int call_count;			/* number of calls */
 int verbose;	/* Verbosity level 0=none, 1=warn, 2=notice, 3=info, 4=debug */
 ulong text_offset;		/* text address of first function */
+ulong text_base;		/* CONFIG_TEXT_BASE from trace file */
 
 /* debugging helpers */
 static void outf(int level, const char *fmt, ...)
@@ -289,7 +290,8 @@ static int read_system_map(FILE *fin)
 		if (func_count > 1)
 			func[-1].code_size = func->offset - func[-1].offset;
 	}
-	notice("%d functions found in map file\n", func_count);
+	notice("%d functions found in map file, start addr %lx\n", func_count,
+	       start);
 	text_offset = start;
 
 	return 0;
@@ -415,6 +417,7 @@ static int read_trace(FILE *fin)
 			break; /* EOF */
 		else if (err)
 			return 1;
+		text_base = hdr.text_base;
 
 		switch (hdr.type) {
 		case TRACE_CHUNK_FUNCS:
@@ -1342,6 +1345,8 @@ static int write_flyrecord(struct twriter *tw, int *missing_countp,
 	tw->ptr += tputq(fout, len);
 	tw->ptr += tputs(fout, str);
 
+	debug("trace text base %lx, map file %lx\n", text_base, text_offset);
+
 	ret = write_pages(tw, missing_countp, skip_countp);
 	if (ret < 0) {
 		fprintf(stderr, "Cannot output pages\n");
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#20 lore raw

PATCH 19/24 trace: Support output of funcgraph records

In reply to Simon Glass

Add support for writing ftrace records in the 'funcgraph' format, which shows function entry and exit points as well as the time taken by each function.

---

 tools/proftool.c | 182 ++++++++++++++++++++++++++++++++++++++---------
 1 file changed, 150 insertions(+), 32 deletions(-)
tools/proftool.c +150 -32
index b5b8a9f7938..588ae48a0c8 100644
@@ -47,6 +47,19 @@ enum {
 	MAX_LINE_LEN	= 500,		/* Max characters per line */
 };
 
+/**
+ * enum out_format_t - supported output formats
+ *
+ * @OUT_FMT_DEFAULT: Use the default for the output file
+ * @OUT_FMT_FUNCTION: Write ftrace 'function' records
+ * @OUT_FMT_FUNCGRAPH: Write ftrace funcgraph_entry and funcgraph_exit records
+ */
+enum out_format_t {
+	OUT_FMT_DEFAULT,
+	OUT_FMT_FUNCTION,
+	OUT_FMT_FUNCGRAPH,
+};
+
 /* Section types for v7 format (trace-cmd format) */
 enum {
 	SECTION_OPTIONS,
@@ -211,10 +224,15 @@ static void usage(void)
 		"\n"
 		"Options:\n"
 		"   -c <cfg>\tSpecify config file\n"
+		"   -f <subtype>\tSpecify output subtype\n"
 		"   -m <map>\tSpecify Systen.map file\n"
 		"   -o <fname>\tSpecify output file\n"
 		"   -t <fname>\tSpecify trace data file (from U-Boot 'trace calls')\n"
-		"   -v <0-4>\tSpecify verbosity\n");
+		"   -v <0-4>\tSpecify verbosity\n"
+		"\n"
+		"Subtypes for dump-ftrace:\n"
+		"   function - write function-call records (caller/callee)\n"
+		"   funcgraph - write function entry/exit records (graph)\n");
 	exit(EXIT_FAILURE);
 }
 
@@ -1165,6 +1183,43 @@ static int write_options(struct twriter *tw)
 	return 0;
 }
 
+/**
+ * calc_min_depth() - Calculate the minimum call depth from the call list
+ *
+ * Starting with a depth of 0, this works through the call list, adding 1 for
+ * each function call and subtracting 1 for each function return. Most likely
+ * the value ends up being negative, since the trace does not start at the
+ * very top of the call stack, e.g. main(), but some function called by that.
+ *
+ * This value can be used to calculate the depth value for the first call,
+ * such that it never goes negative for subsequent returns.
+ *
+ * Returns: minimum call depth (e.g. -2)
+ */
+static int calc_min_depth(void)
+{
+	struct trace_call *call;
+	int depth, min_depth, i;
+
+	/* Calculate minimum depth */
+	depth = 0;
+	min_depth = 0;
+	for (i = 0, call = call_list; i < call_count; i++, call++) {
+		switch (TRACE_CALL_TYPE(call)) {
+		case FUNCF_ENTRY:
+			depth++;
+			break;
+		case FUNCF_EXIT:
+			depth--;
+			if (depth < min_depth)
+				min_depth = depth;
+			break;
+		}
+	}
+
+	return min_depth;
+}
+
 /**
  * write_pages() - Write the pages of trace data
  *
@@ -1172,17 +1227,19 @@ static int write_options(struct twriter *tw)
  * needed.
  *
  * @tw: Writer context
+ * @out_format: Output format to use
  * @missing_countp: Returns number of missing functions (not found in function
  * list)
  * @skip_countp: Returns number of skipped functions (excluded from trace)
  *
  * Returns: 0 on success, -ve on error
  */
-static int write_pages(struct twriter *tw, int *missing_countp,
-		       int *skip_countp)
+static int write_pages(struct twriter *tw, enum out_format_t out_format,
+		       int *missing_countp, int *skip_countp)
 {
+	ulong func_stack[MAX_STACK_DEPTH];
 	int stack_ptr;	/* next free position in stack */
-	int upto, page_upto, i;
+	int upto, depth, page_upto, i;
 	int missing_count = 0, skip_count = 0;
 	struct trace_call *call;
 	ulong last_timestamp;
@@ -1200,8 +1257,13 @@ static int write_pages(struct twriter *tw, int *missing_countp,
 	/* maintain a stack of start times for calling functions */
 	stack_ptr = 0;
 
+	/*
+	 * The first thing in the trace may not be the top-level function, so
+	 * set the initial depth so that no function goes below depth 0
+	 */
+	depth = -calc_min_depth();
 	for (i = 0, call = call_list; i < call_count; i++, call++) {
-		struct func_info *caller_func;
+		bool entry = TRACE_CALL_TYPE(call) == FUNCF_ENTRY;
 		struct func_info *func;
 		ulong timestamp;
 		uint rec_words;
@@ -1227,7 +1289,10 @@ static int write_pages(struct twriter *tw, int *missing_countp,
 			continue;
 		}
 
-		rec_words = 6;
+		if (out_format == OUT_FMT_FUNCTION)
+			rec_words = 6;
+		else /* 2 header words and then 3 or 8 others */
+			rec_words = 2 + (entry ? 3 : 8);
 
 		/* convert timestamp from us to ns */
 		timestamp = call->flags & FUNCF_TIMESTAMP_MASK;
@@ -1273,24 +1338,59 @@ static int write_pages(struct twriter *tw, int *missing_countp,
 			return -1;
 		}
 
-		if (_DEBUG) {
-			fprintf(stderr, "%d: delta=%d, stamp=%ld\n",
-				upto, delta, timestamp);
-			fprintf(stderr,
-				"   last_delta %x to %x: last_timestamp=%lx, timestamp=%lx, call->flags=%x, upto=%d\n",
-				last_delta, delta, last_timestamp, timestamp, call->flags, upto);
-		}
+		if (out_format == OUT_FMT_FUNCTION) {
+			struct func_info *caller_func;
 
-		/* type_len is 6, meaning 4 * 6 = 24 bytes */
-		tw->ptr += tputl(fout, rec_words | (uint)delta << 5);
-		tw->ptr += tputh(fout, TRACE_FN);
-		tw->ptr += tputh(fout, 0);	/* flags */
-		tw->ptr += tputl(fout, TRACE_PID);	/* PID */
-		/* function */
-		tw->ptr += tputq(fout, text_offset + func->offset);
-		caller_func = find_caller_by_offset(call->caller);
-		/* caller */
-		tw->ptr += tputq(fout, text_offset + caller_func->offset);
+			if (_DEBUG) {
+				fprintf(stderr, "%d: delta=%d, stamp=%ld\n",
+					upto, delta, timestamp);
+				fprintf(stderr,
+					"   last_delta %x to %x: last_timestamp=%lx, "
+					"timestamp=%lx, call->flags=%x, upto=%d\n",
+					last_delta, delta, last_timestamp,
+					timestamp, call->flags, upto);
+			}
+
+			/* type_len is 6, meaning 4 * 6 = 24 bytes */
+			tw->ptr += tputl(fout, rec_words | (uint)delta << 5);
+			tw->ptr += tputh(fout, TRACE_FN);
+			tw->ptr += tputh(fout, 0);	/* flags */
+			tw->ptr += tputl(fout, TRACE_PID);	/* PID */
+			/* function */
+			tw->ptr += tputq(fout, text_offset + func->offset);
+			caller_func = find_caller_by_offset(call->caller);
+			/* caller */
+			tw->ptr += tputq(fout,
+					 text_offset + caller_func->offset);
+		} else {
+			tw->ptr += tputl(fout, rec_words | delta << 5);
+			tw->ptr += tputh(fout, entry ? TRACE_GRAPH_ENT
+						: TRACE_GRAPH_RET);
+			tw->ptr += tputh(fout, 0);	/* flags */
+			tw->ptr += tputl(fout, TRACE_PID); /* PID */
+			/* function */
+			tw->ptr += tputq(fout, text_offset + func->offset);
+			tw->ptr += tputl(fout, depth); /* depth */
+			if (entry) {
+				depth++;
+				if (stack_ptr < MAX_STACK_DEPTH)
+					func_stack[stack_ptr] = timestamp;
+				stack_ptr++;
+			} else {
+				ulong func_duration = 0;
+
+				depth--;
+				if (stack_ptr && stack_ptr <= MAX_STACK_DEPTH) {
+					ulong start = func_stack[--stack_ptr];
+
+					func_duration = timestamp - start;
+				}
+				tw->ptr += tputl(fout, 0);	/* overrun */
+				tw->ptr += tputq(fout, 0);	/* calltime */
+				/* rettime */
+				tw->ptr += tputq(fout, func_duration);
+			}
+		}
 
 		last_delta = delta;
 		last_timestamp = timestamp;
@@ -1314,14 +1414,15 @@ static int write_pages(struct twriter *tw, int *missing_countp,
  * writes out the counter-type info, selecting "[local]"
  *
  * @tw: Writer context
+ * @out_format: Output format to use
  * @missing_countp: Returns number of missing functions (not found in function
  * list)
  * @skip_countp: Returns number of skipped functions (excluded from trace)
  *
  * Returns: 0 on success, -ve on error
  */
-static int write_flyrecord(struct twriter *tw, int *missing_countp,
-			   int *skip_countp)
+static int write_flyrecord(struct twriter *tw, enum out_format_t out_format,
+			   int *missing_countp, int *skip_countp)
 {
 	int start, ret, len;
 	FILE *fout = tw->fout;
@@ -1347,7 +1448,7 @@ static int write_flyrecord(struct twriter *tw, int *missing_countp,
 
 	debug("trace text base %lx, map file %lx\n", text_base, text_offset);
 
-	ret = write_pages(tw, missing_countp, skip_countp);
+	ret = write_pages(tw, out_format, missing_countp, skip_countp);
 	if (ret < 0) {
 		fprintf(stderr, "Cannot output pages\n");
 		return -1;
@@ -1370,9 +1471,10 @@ static int write_flyrecord(struct twriter *tw, int *missing_countp,
  * https://github.com/rostedt/trace-cmd/blob/master/Documentation/trace-cmd/trace-cmd.dat.v7.5.txt
  *
  * @fout: Output file
+ * @out_format: Output format to use
  * Returns: 0 on success, -ve on error
  */
-static int make_ftrace(FILE *fout)
+static int make_ftrace(FILE *fout, enum out_format_t out_format)
 {
 	int missing_count, skip_count;
 	struct twriter tws, *tw = &tws;
@@ -1403,7 +1505,7 @@ static int make_ftrace(FILE *fout)
 		return -1;
 	}
 
-	ret = write_flyrecord(tw, &missing_count, &skip_count);
+	ret = write_flyrecord(tw, out_format, &missing_count, &skip_count);
 	if (ret < 0) {
 		fprintf(stderr, "Cannot write flyrecord\n");
 		return -1;
@@ -1427,7 +1529,8 @@ static int make_ftrace(FILE *fout)
  */
 static int prof_tool(int argc, char *const argv[],
 		     const char *trace_fname, const char *map_fname,
-		     const char *trace_config_fname, const char *out_fname)
+		     const char *trace_config_fname, const char *out_fname,
+		     enum out_format_t out_format)
 {
 	int err = 0;
 
@@ -1446,13 +1549,16 @@ static int prof_tool(int argc, char *const argv[],
 		if (!strcmp(cmd, "dump-ftrace")) {
 			FILE *fout;
 
+			if (out_format != OUT_FMT_FUNCTION &&
+			    out_format != OUT_FMT_FUNCGRAPH)
+				out_format = OUT_FMT_FUNCTION;
 			fout = fopen(out_fname, "w");
 			if (!fout) {
 				fprintf(stderr, "Cannot write file '%s'\n",
 					out_fname);
 				return -1;
 			}
-			err = make_ftrace(fout);
+			err = make_ftrace(fout, out_format);
 			fclose(fout);
 		} else {
 			warn("Unknown command '%s'\n", cmd);
@@ -1464,6 +1570,7 @@ static int prof_tool(int argc, char *const argv[],
 
 int main(int argc, char *argv[])
 {
+	enum out_format_t out_format = OUT_FMT_DEFAULT;
 	const char *map_fname = "System.map";
 	const char *trace_fname = NULL;
 	const char *config_fname = NULL;
@@ -1471,11 +1578,22 @@ int main(int argc, char *argv[])
 	int opt;
 
 	verbose = 2;
-	while ((opt = getopt(argc, argv, "c:m:o:t:v:")) != -1) {
+	while ((opt = getopt(argc, argv, "c:f:m:o:t:v:")) != -1) {
 		switch (opt) {
 		case 'c':
 			config_fname = optarg;
 			break;
+		case 'f':
+			if (!strcmp("function", optarg)) {
+				out_format = OUT_FMT_FUNCTION;
+			} else if (!strcmp("funcgraph", optarg)) {
+				out_format = OUT_FMT_FUNCGRAPH;
+			} else {
+				fprintf(stderr,
+					"Invalid format: use function, funcgraph, calls, timing\n");
+				exit(1);
+			}
+			break;
 		case 'm':
 			map_fname = optarg;
 			break;
@@ -1504,5 +1622,5 @@ int main(int argc, char *argv[])
 
 	debug("Debug enabled\n");
 	return prof_tool(argc, argv, trace_fname, map_fname, config_fname,
-			 out_fname);
+			 out_fname, out_format);
 }
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#21 lore raw

PATCH 20/24 trace: Support output of a flamegraph

In reply to Simon Glass

It is useful to see how many times each function is called, particularly in the context of its callers. A flamegraph is a way of showing this.

Support output in this format which can be used by the flamegraph.pl script, to generate an SVG image for browsing.

---

 tools/proftool.c | 272 ++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 271 insertions(+), 1 deletion(-)
tools/proftool.c +271 -1
index 588ae48a0c8..844ff3d0d06 100644
@@ -6,7 +6,7 @@
 
 /*
  * Decode and dump U-Boot trace information into formats that can be used
- * by trace-cmd or kernelshark
+ * by trace-cmd, kernelshark or flamegraph.pl
  *
  * See doc/develop/trace.rst for more information
  */
@@ -27,6 +27,8 @@
 #include <trace.h>
 #include <abuf.h>
 
+#include <linux/list.h>
+
 /* Set to 1 to emit version 7 file (currently this doesn't work) */
 #define VERSION7	0
 
@@ -37,6 +39,18 @@
 #define __ALIGN_MASK(x, mask)	(((x) + (mask)) & ~(mask))
 #define ALIGN(x, a)		__ALIGN_MASK((x), (typeof(x))(a) - 1)
 
+/**
+ * container_of - cast a member of a structure out to the containing structure
+ * @ptr:	the pointer to the member.
+ * @type:	the type of the container struct this is embedded in.
+ * @member:	the name of the member within the struct.
+ *
+ * (this is needed by list.h)
+ */
+#define container_of(ptr, type, member) ({			\
+	const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
+	(type *)( (char *)__mptr - offsetof(type,member) );})
+
 enum {
 	FUNCF_TRACE	= 1 << 0,	/* Include this function in trace */
 	TRACE_PAGE_SIZE	= 4096,		/* Assumed page size for trace */
@@ -101,6 +115,38 @@ enum trace_type {
 	TRACE_GRAPH_ENT,
 };
 
+/**
+ * struct flame_node - a node in the call-stack tree
+ *
+ * Each stack frame detected in the trace is given a node corresponding to a
+ * function call in the call stack. Functions can appear multiple times when
+ * they are called by a different set of parent functions.
+ *
+ * @parent: Parent node (the call stack for the function that called this one)
+ * @child_head: List of children of this node (functions called from here)
+ * @sibling: Next node in the list of children
+ * @func: Function this node refers to (NULL for root node)
+ * @count: Number of times this call-stack occurred
+ */
+struct flame_node {
+	struct flame_node *parent;
+	struct list_head child_head;
+	struct list_head sibling_node;
+	struct func_info *func;
+	int count;
+};
+
+/**
+ * struct flame_state - state information for building the flame graph
+ *
+ * @node: Current node being processed (corresponds to a function call)
+ * @nodes: Number of nodes created (running count)
+ */
+struct flame_state {
+	struct flame_node *node;
+	int nodes;
+};
+
 /**
  * struct func_info - information recorded for each function
  *
@@ -221,6 +267,7 @@ static void usage(void)
 		"\n"
 		"Commands\n"
 		"   dump-ftrace\t\tDump out records in ftrace format for use by trace-cmd\n"
+		"   dump-flamegraph\tWrite a file for use with flamegraph.pl\n"
 		"\n"
 		"Options:\n"
 		"   -c <cfg>\tSpecify config file\n"
@@ -1517,6 +1564,218 @@ static int make_ftrace(FILE *fout, enum out_format_t out_format)
 	return 0;
 }
 
+/**
+ * create_node() - Create a new node in the flamegraph tree
+ *
+ * @msg: Message to use for debugging if something goes wrong
+ * Returns: Pointer to newly created node, or NULL on error
+ */
+static struct flame_node *create_node(const char *msg)
+{
+	struct flame_node *node;
+
+	node = calloc(1, sizeof(*node));
+	if (!node) {
+		fprintf(stderr, "Out of memory for %s\n", msg);
+		return NULL;
+	}
+	INIT_LIST_HEAD(&node->child_head);
+
+	return node;
+}
+
+/**
+ * process_call(): Add a call to the flamegraph info
+ *
+ * For function calls, if this call stack has been seen before, this increments
+ * the call count, creating a new node if needed.
+ *
+ * For function returns, it adds up the time spent in this call stack,
+ * subtracting the time spent by child functions.
+ *
+ * @state: Current flamegraph state
+ * @entry: true if this is a function entry, false if a function exit
+ * @timestamp: Timestamp from the trace file (in microseconds)
+ * @func: Function that was called/returned from
+ *
+ * Returns: 0 on success, -ve on error
+ */
+static int process_call(struct flame_state *state, bool entry, ulong timestamp,
+			struct func_info *func)
+{
+	struct flame_node *node = state->node;
+
+	if (entry) {
+		struct flame_node *child, *chd;
+
+		/* see if we have this as a child node already */
+		child = NULL;
+		list_for_each_entry(chd, &node->child_head, sibling_node) {
+			if (chd->func == func) {
+				child = chd;
+				break;
+			}
+		}
+		if (!child) {
+			/* create a new node */
+			child = create_node("child");
+			if (!child)
+				return -1;
+			list_add_tail(&child->sibling_node, &node->child_head);
+			child->func = func;
+			child->parent = node;
+			state->nodes++;
+		}
+		debug("entry %s: move from %s to %s\n", func->name,
+		      node->func ? node->func->name : "(root)",
+		      child->func->name);
+		child->count++;
+		node = child;
+	} else if (node->parent) {
+		debug("exit  %s: move from %s to %s\n", func->name,
+		      node->func->name, node->parent->func ?
+		      node->parent->func->name : "(root)");
+		node = node->parent;
+	}
+
+	state->node = node;
+
+	return 0;
+}
+
+/**
+ * make_flame_tree() - Create a tree of stack traces
+ *
+ * Set up a tree, with the root node having the top-level functions as children
+ * and the leaf nodes being leaf functions. Each node has a count of how many
+ * times this function appears in the trace
+ *
+ * @treep: Returns the resulting flamegraph tree
+ * Returns: 0 on success, -ve on error
+ */
+static int make_flame_tree(struct flame_node **treep)
+{
+	struct flame_state state;
+	struct flame_node *tree;
+	struct trace_call *call;
+	int missing_count = 0;
+	int i, depth;
+
+	/*
+	 * The first thing in the trace may not be the top-level function, so
+	 * set the initial depth so that no function goes below depth 0
+	 */
+	depth = -calc_min_depth();
+
+	tree = create_node("tree");
+	if (!tree)
+		return -1;
+	state.node = tree;
+	state.nodes = 0;
+
+	for (i = 0, call = call_list; i < call_count; i++, call++) {
+		bool entry = TRACE_CALL_TYPE(call) == FUNCF_ENTRY;
+		ulong timestamp = call->flags & FUNCF_TIMESTAMP_MASK;
+		struct func_info *func;
+
+		if (entry)
+			depth++;
+		else
+			depth--;
+
+		func = find_func_by_offset(call->func);
+		if (!func) {
+			warn("Cannot find function at %lx\n",
+			     text_offset + call->func);
+			missing_count++;
+			continue;
+		}
+
+		if (process_call(&state, entry, timestamp, func))
+			return -1;
+	}
+	fprintf(stderr, "%d nodes\n", state.nodes);
+	*treep = tree;
+
+	return 0;
+}
+
+/**
+ * output_tree() - Output a flamegraph tree
+ *
+ * Writes the tree out to a file in a format suitable for flamegraph.pl
+ *
+ * This works by maintaining a string shared across all recursive calls. The
+ * function name for this node is added to the existing string, to make up the
+ * full call-stack description. For example, on entry, @str might contain:
+ *
+ *    "initf_bootstage;bootstage_mark_name"
+ *                                        ^ @base
+ *
+ * with @base pointing to the \0 at the end of the string. This function adds
+ * a ';' following by the name of the current function, e.g. "timer_get_boot_us"
+ * as well as the output value, to get the full line:
+ *
+ * initf_bootstage;bootstage_mark_name;timer_get_boot_us 123
+ *
+ * @fout: Output file
+ * @node: Node to output (pass the whole tree at first)
+ * @str: String to use to build the output line (e.g. 500 charas long)
+ * @maxlen: Maximum length of string
+ * @base: Current base position in the string
+ * @treep: Returns the resulting flamegraph tree
+ * Returns 0 if OK, -1 on error
+ */
+static int output_tree(FILE *fout, const struct flame_node *node,
+		       char *str, int maxlen, int base)
+{
+	const struct flame_node *child;
+	int pos;
+
+	if (node->count)
+		fprintf(fout, "%s %d\n", str, node->count);
+
+	pos = base;
+	if (pos)
+		str[pos++] = ';';
+	list_for_each_entry(child, &node->child_head, sibling_node) {
+		int len;
+
+		len = strlen(child->func->name);
+		if (pos + len + 1 >= maxlen) {
+			fprintf(stderr, "String too short (%d chars)\n",
+				maxlen);
+			return -1;
+		}
+		strcpy(str + pos, child->func->name);
+		if (output_tree(fout, child, str, maxlen, pos + len))
+			return -1;
+	}
+
+	return 0;
+}
+
+/**
+ * make_flamegraph() - Write out a flame graph
+ *
+ * @fout: Output file
+ * Returns 0 if OK, -1 on error
+ */
+static int make_flamegraph(FILE *fout)
+{
+	struct flame_node *tree;
+	char str[500];
+
+	if (make_flame_tree(&tree))
+		return -1;
+
+	*str = '\0';
+	if (output_tree(fout, tree, str, sizeof(str), 0))
+		return -1;
+
+	return 0;
+}
+
 /**
  * prof_tool() - Performs requested action
  *
@@ -1560,6 +1819,17 @@ static int prof_tool(int argc, char *const argv[],
 			}
 			err = make_ftrace(fout, out_format);
 			fclose(fout);
+		} else if (!strcmp(cmd, "dump-flamegraph")) {
+			FILE *fout;
+
+			fout = fopen(out_fname, "w");
+			if (!fout) {
+				fprintf(stderr, "Cannot write file '%s'\n",
+					out_fname);
+				return -1;
+			}
+			err = make_flamegraph(fout);
+			fclose(fout);
 		} else {
 			warn("Unknown command '%s'\n", cmd);
 		}
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#22 lore raw

PATCH 21/24 trace: Provide a flamegraph that uses timing

In reply to Simon Glass

Add a second variant of the flame graph that shows records in terms of the number of microseconds used by each call stack. This is a useful way of seeing where time is going within the execution of U-Boot.

This requires a call stack that records the start time of each function, as well as a way of subtracting all time consumed by child functions, so that this time is not counted twice by the flamegraph. The time values in the output are just for the function itself, not for its children.

---

 tools/proftool.c | 108 ++++++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 97 insertions(+), 11 deletions(-)
tools/proftool.c +97 -11
index 844ff3d0d06..089360428c2 100644
@@ -67,11 +67,16 @@ enum {
  * @OUT_FMT_DEFAULT: Use the default for the output file
  * @OUT_FMT_FUNCTION: Write ftrace 'function' records
  * @OUT_FMT_FUNCGRAPH: Write ftrace funcgraph_entry and funcgraph_exit records
+ * @OUT_FMT_FLAMEGRAPH_CALLS: Write a file suitable for flamegraph.pl
+ * @OUT_FMT_FLAMEGRAPH_TIMING: Write a file suitable for flamegraph.pl with the
+ * counts set to the number of microseconds used by each function
  */
 enum out_format_t {
 	OUT_FMT_DEFAULT,
 	OUT_FMT_FUNCTION,
 	OUT_FMT_FUNCGRAPH,
+	OUT_FMT_FLAMEGRAPH_CALLS,
+	OUT_FMT_FLAMEGRAPH_TIMING,
 };
 
 /* Section types for v7 format (trace-cmd format) */
@@ -127,6 +132,8 @@ enum trace_type {
  * @sibling: Next node in the list of children
  * @func: Function this node refers to (NULL for root node)
  * @count: Number of times this call-stack occurred
+ * @duration: Number of microseconds taken to run this function, excluding all
+ * of the functions it calls
  */
 struct flame_node {
 	struct flame_node *parent;
@@ -134,16 +141,27 @@ struct flame_node {
 	struct list_head sibling_node;
 	struct func_info *func;
 	int count;
+	ulong duration;
 };
 
 /**
  * struct flame_state - state information for building the flame graph
  *
  * @node: Current node being processed (corresponds to a function call)
+ * @stack: Stack of call-start time for this function as well as the
+ * accumulated total time of all child calls (so we can subtract them from the
+ * function's call time. This is an 'empty' stack, meaning that @stack_ptr
+ * points to the next available stack position
+ * @stack_ptr: points to first empty position in the stack
  * @nodes: Number of nodes created (running count)
  */
 struct flame_state {
 	struct flame_node *node;
+	struct stack_info {
+		ulong timestamp;
+		ulong child_total;
+	} stack[MAX_STACK_DEPTH];
+	int stack_ptr;
 	int nodes;
 };
 
@@ -279,7 +297,11 @@ static void usage(void)
 		"\n"
 		"Subtypes for dump-ftrace:\n"
 		"   function - write function-call records (caller/callee)\n"
-		"   funcgraph - write function entry/exit records (graph)\n");
+		"   funcgraph - write function entry/exit records (graph)\n"
+		"\n"
+		"Subtypes for dump-flamegraph\n"
+		"   calls - create a flamegraph of stack frames\n"
+		"   timing - create a flamegraph of microseconds for each stack frame\n");
 	exit(EXIT_FAILURE);
 }
 
@@ -1604,6 +1626,7 @@ static int process_call(struct flame_state *state, bool entry, ulong timestamp,
 			struct func_info *func)
 {
 	struct flame_node *node = state->node;
+	int stack_ptr = state->stack_ptr;
 
 	if (entry) {
 		struct flame_node *child, *chd;
@@ -1630,14 +1653,44 @@ static int process_call(struct flame_state *state, bool entry, ulong timestamp,
 		      node->func ? node->func->name : "(root)",
 		      child->func->name);
 		child->count++;
+		if (stack_ptr < MAX_STACK_DEPTH) {
+			state->stack[stack_ptr].timestamp = timestamp;
+			state->stack[stack_ptr].child_total = 0;
+		}
+		debug("%d: %20s: entry at %ld\n", stack_ptr, func->name,
+		      timestamp);
+		stack_ptr++;
 		node = child;
 	} else if (node->parent) {
+		ulong total_duration = 0, child_duration = 0;
+		struct stack_info *stk;
+
 		debug("exit  %s: move from %s to %s\n", func->name,
 		      node->func->name, node->parent->func ?
 		      node->parent->func->name : "(root)");
+		if (stack_ptr && stack_ptr <= MAX_STACK_DEPTH) {
+			stk = &state->stack[--stack_ptr];
+
+			/*
+			 * get total duration of the function which just
+			 * exited
+			 */
+			total_duration = timestamp - stk->timestamp;
+			child_duration = stk->child_total;
+
+			if (stack_ptr)
+				state->stack[stack_ptr - 1].child_total += total_duration;
+
+			debug("%d: %20s: exit at %ld, total %ld, child %ld, child_total=%ld\n",
+			      stack_ptr, func->name, timestamp,
+			      total_duration, child_duration,
+			      stk->child_total);
+		}
+		node->duration += total_duration - child_duration;
 		node = node->parent;
 	}
 
+	state->stack_ptr = stack_ptr;
 	state->node = node;
 
 	return 0;
@@ -1650,10 +1703,12 @@ static int process_call(struct flame_state *state, bool entry, ulong timestamp,
  * and the leaf nodes being leaf functions. Each node has a count of how many
  * times this function appears in the trace
  *
+ * @out_format: Output format to use
  * @treep: Returns the resulting flamegraph tree
  * Returns: 0 on success, -ve on error
  */
-static int make_flame_tree(struct flame_node **treep)
+static int make_flame_tree(enum out_format_t out_format,
+			   struct flame_node **treep)
 {
 	struct flame_state state;
 	struct flame_node *tree;
@@ -1661,6 +1716,9 @@ static int make_flame_tree(struct flame_node **treep)
 	int missing_count = 0;
 	int i, depth;
 
+	/* maintain a stack of start times, etc. for 'calling' functions */
+	state.stack_ptr = 0;
+
 	/*
 	 * The first thing in the trace may not be the top-level function, so
 	 * set the initial depth so that no function goes below depth 0
@@ -1719,6 +1777,7 @@ static int make_flame_tree(struct flame_node **treep)
  * initf_bootstage;bootstage_mark_name;timer_get_boot_us 123
  *
  * @fout: Output file
+ * @out_format: Output format to use
  * @node: Node to output (pass the whole tree at first)
  * @str: String to use to build the output line (e.g. 500 charas long)
  * @maxlen: Maximum length of string
@@ -1726,14 +1785,32 @@ static int make_flame_tree(struct flame_node **treep)
  * @treep: Returns the resulting flamegraph tree
  * Returns 0 if OK, -1 on error
  */
-static int output_tree(FILE *fout, const struct flame_node *node,
-		       char *str, int maxlen, int base)
+static int output_tree(FILE *fout, enum out_format_t out_format,
+		       const struct flame_node *node, char *str, int maxlen,
+		       int base)
 {
 	const struct flame_node *child;
 	int pos;
 
-	if (node->count)
-		fprintf(fout, "%s %d\n", str, node->count);
+	if (node->count) {
+		if (out_format == OUT_FMT_FLAMEGRAPH_CALLS) {
+			fprintf(fout, "%s %d\n", str, node->count);
+		} else {
+			/*
+			 * Write out the number of microseconds used by this
+			 * call stack. Since the time taken by child calls is
+			 * subtracted from this total, it can reach 0, meaning
+			 * that this function took no time beyond what its
+			 * children used. For this case, write 1 rather than 0,
+			 * so that this call stack appears in the flamegraph.
+			 * This has the effect of inflating the timing slightly,
+			 * but only by at most 1 microsecond per function,
+			 * assuming that is the timestamp resolution
+			 */
+			fprintf(fout, "%s %ld\n", str,
+				node->duration ? node->duration : 1);
+		}
+	}
 
 	pos = base;
 	if (pos)
@@ -1748,7 +1825,8 @@ static int output_tree(FILE *fout, const struct flame_node *node,
 			return -1;
 		}
 		strcpy(str + pos, child->func->name);
-		if (output_tree(fout, child, str, maxlen, pos + len))
+		if (output_tree(fout, out_format, child, str, maxlen,
+				pos + len))
 			return -1;
 	}
 
@@ -1759,18 +1837,19 @@ static int output_tree(FILE *fout, const struct flame_node *node,
  * make_flamegraph() - Write out a flame graph
  *
  * @fout: Output file
+ * @out_format: Output format to use, e.g. function counts or timing
  * Returns 0 if OK, -1 on error
  */
-static int make_flamegraph(FILE *fout)
+static int make_flamegraph(FILE *fout, enum out_format_t out_format)
 {
 	struct flame_node *tree;
 	char str[500];
 
-	if (make_flame_tree(&tree))
+	if (make_flame_tree(out_format, &tree))
 		return -1;
 
 	*str = '\0';
-	if (output_tree(fout, tree, str, sizeof(str), 0))
+	if (output_tree(fout, out_format, tree, str, sizeof(str), 0))
 		return -1;
 
 	return 0;
@@ -1822,13 +1901,16 @@ static int prof_tool(int argc, char *const argv[],
 		} else if (!strcmp(cmd, "dump-flamegraph")) {
 			FILE *fout;
 
+			if (out_format != OUT_FMT_FLAMEGRAPH_CALLS &&
+			    out_format != OUT_FMT_FLAMEGRAPH_TIMING)
+				out_format = OUT_FMT_FLAMEGRAPH_CALLS;
 			fout = fopen(out_fname, "w");
 			if (!fout) {
 				fprintf(stderr, "Cannot write file '%s'\n",
 					out_fname);
 				return -1;
 			}
-			err = make_flamegraph(fout);
+			err = make_flamegraph(fout, out_format);
 			fclose(fout);
 		} else {
 			warn("Unknown command '%s'\n", cmd);
@@ -1858,6 +1940,10 @@ int main(int argc, char *argv[])
 				out_format = OUT_FMT_FUNCTION;
 			} else if (!strcmp("funcgraph", optarg)) {
 				out_format = OUT_FMT_FUNCGRAPH;
+			} else if (!strcmp("calls", optarg)) {
+				out_format = OUT_FMT_FLAMEGRAPH_CALLS;
+			} else if (!strcmp("timing", optarg)) {
+				out_format = OUT_FMT_FLAMEGRAPH_TIMING;
 			} else {
 				fprintf(stderr,
 					"Invalid format: use function, funcgraph, calls, timing\n");
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#23 lore raw

PATCH 22/24 Docker: Support trace-cmd

In reply to Simon Glass

Build trace-cmd as part of the docker image, so that trace tests can be used. Unfortunately the version provided by distributions is a little old and has bugs. It also does not support specifying the time base for the trace, which is required to convert microseconds to nanaseconds.

---

 tools/docker/Dockerfile | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
tools/docker/Dockerfile +16 -0
index 202a8145af7..6e0cdd48dd5 100644
@@ -213,6 +213,22 @@ RUN git clone https://github.com/stefanberger/swtpm /tmp/swtpm && \
 	make install && \
 	rm -rf /tmp/swtpm
 
+# Build trace-cmd
+RUN mkdir /tmp/trace && \
+    git clone https://git.kernel.org/pub/scm/libs/libtrace/libtraceevent.git /tmp/trace/libtraceevent && \
+    cd /tmp/trace/libtraceevent && \
+    make -j$(nproc) && \
+    sudo make install && \
+    git clone https://git.kernel.org/pub/scm/libs/libtrace/libtracefs.git /tmp/trace/libtracefs && \
+    cd /tmp/trace/libtracefs && \
+    make -j$(nproc) && \
+    sudo make install && \
+    git clone https://github.com/rostedt/trace-cmd.git /tmp/trace/trace-cmd && \
+    cd /tmp/trace/trace-cmd && \
+    make -j$(nproc) && \
+    sudo make install && \
+    rm -rf /tmp/trace
+
 # Create our user/group
 RUN echo uboot ALL=NOPASSWD: ALL > /etc/sudoers.d/uboot
 RUN useradd -m -U uboot
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#24 lore raw

PATCH 23/24 trace: Add a test

In reply to Simon Glass

Add a test which runs sandbox, collects a trace and makes sure it can be processed by trace-cmd. This should ensure that this feature continues to work as U-Boot and trace-cmd evolve.

---

 .azure-pipelines.yml        |   8 +
 .gitlab-ci.yml              |  12 ++
 test/py/tests/test_trace.py | 304 ++++++++++++++++++++++++++++++++++++
 3 files changed, 324 insertions(+)
 create mode 100644 test/py/tests/test_trace.py
.azure-pipelines.yml +8 -0
index 49fc34fbf23..8f5c8e05dc5 100644
@@ -239,6 +239,11 @@ stages:
           TEST_PY_TEST_SPEC: "test_ofplatdata or test_handoff or test_spl"
         sandbox_flattree:
           TEST_PY_BD: "sandbox_flattree"
+        sandbox_trace:
+          TEST_PY_BD: "sandbox"
+          BUILD_ENV: "FTRACE=1 NO_LTO=1"
+          TEST_PY_TEST_SPEC: "trace"
+          OVERRIDE: "-a CONFIG_TRACE=y -a CONFIG_TRACE_EARLY=y -a CONFIG_TRACE_EARLY_SIZE=0x01000000"
         coreboot:
           TEST_PY_BD: "coreboot"
           TEST_PY_ID: "--id qemu"
@@ -361,6 +366,9 @@ stages:
           # the below corresponds to .gitlab-ci.yml "script"
           cd ${WORK_DIR}
           export UBOOT_TRAVIS_BUILD_DIR=/tmp/${TEST_PY_BD};
+          if [ -n "${BUILD_ENV}" ]; then
+              export ${BUILD_ENV};
+          fi
           tools/buildman/buildman -o ${UBOOT_TRAVIS_BUILD_DIR} -w -E -W -e --board ${TEST_PY_BD} ${OVERRIDE}
           cp ~/grub_x86.efi ${UBOOT_TRAVIS_BUILD_DIR}/
           cp ~/grub_x64.efi ${UBOOT_TRAVIS_BUILD_DIR}/
.gitlab-ci.yml +12 -0
index 398fa2b45e2..87288a666df 100644
@@ -35,6 +35,9 @@ stages:
     # If we've been asked to use clang only do one configuration.
     - export UBOOT_TRAVIS_BUILD_DIR=/tmp/${TEST_PY_BD}
     - echo BUILD_ENV ${BUILD_ENV}
+    - if [ -n "${BUILD_ENV}" ]; then
+        export ${BUILD_ENV};
+      fi
     - tools/buildman/buildman -o ${UBOOT_TRAVIS_BUILD_DIR} -w -E -W -e
         --board ${TEST_PY_BD} ${OVERRIDE}
     - cp ~/grub_x86.efi $UBOOT_TRAVIS_BUILD_DIR/
@@ -267,6 +270,15 @@ sandbox_vpl test.py:
     TEST_PY_TEST_SPEC: "test_vpl_help or test_spl"
   <<: *buildman_and_testpy_dfn
 
+# Enable tracing and disable LTO, to ensure functions are not elided
+sandbox trace_test.py:
+  variables:
+    TEST_PY_BD: "sandbox"
+    BUILD_ENV: "FTRACE=1 NO_LTO=1"
+    TEST_PY_TEST_SPEC: "trace"
+    OVERRIDE: "-a CONFIG_TRACE=y -a CONFIG_TRACE_EARLY=y -a CONFIG_TRACE_EARLY_SIZE=0x01000000"
+  <<: *buildman_and_testpy_dfn
+
 evb-ast2500 test.py:
   variables:
     TEST_PY_BD: "evb-ast2500"
test/py/tests/test_trace.py new file +304 -0

304 lines not on this page · raw message

Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#25 lore raw

PATCH 24/24 trace: Update documentation

In reply to Simon Glass

Revamp the documentation for the new features, including a description of the new features and documentation for the trace command.

---

 .gitattributes                         |   1 +
 doc/develop/pics/flamegraph.png        | Bin 0 -> 48224 bytes
 doc/develop/pics/flamegraph_timing.png | Bin 0 -> 31305 bytes
 doc/develop/pics/flamegraph_zoom.png   | Bin 0 -> 25465 bytes
 doc/develop/pics/kernelshark.png       | Bin 0 -> 29617 bytes
 doc/develop/pics/kernelshark_fg.png    | Bin 0 -> 28899 bytes
 doc/develop/trace.rst                  | 281 +++++++++++++++++++------
 doc/usage/cmd/trace.rst                | 163 ++++++++++++++
 doc/usage/index.rst                    |   1 +
 9 files changed, 382 insertions(+), 64 deletions(-)
 create mode 100644 doc/develop/pics/flamegraph.png
 create mode 100644 doc/develop/pics/flamegraph_timing.png
 create mode 100644 doc/develop/pics/flamegraph_zoom.png
 create mode 100644 doc/develop/pics/kernelshark.png
 create mode 100644 doc/develop/pics/kernelshark_fg.png
 create mode 100644 doc/usage/cmd/trace.rst
.gitattributes +1 -0
index 1879a2dfb3c..d5931f03e7c 100644
@@ -4,3 +4,4 @@
 *.bmp binary
 *.ttf binary
 *.gz binary
+*.png binary
doc/develop/pics/flamegraph.png new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..dbdd27e6d872668dcf6f27174382371a75751e9e
GIT binary patch
doc/develop/pics/flamegraph_timing.png new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..b388b8b9881f26a3fc8eab4676caccd22779149c
GIT binary patch
doc/develop/pics/flamegraph_zoom.png new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..38b68444b7ba5cfaa34d9efe6773d697efa5ff13
GIT binary patch
doc/develop/pics/kernelshark.png new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..3450c6b5fd37c849f5b3f5b1d6793b1883d94bc4
GIT binary patch
doc/develop/pics/kernelshark_fg.png new file binary +0 -0
new file mode 100644
index 0000000000000000000000000000000000000000..a54efd1c4cf8d6d6f2f3dc5085fba167d01ebefe
GIT binary patch
doc/develop/trace.rst +217 -64

391 lines not on this page · raw message

doc/usage/cmd/trace.rst new file +163 -0

163 lines not on this page · raw message

doc/usage/index.rst +1 -0
index bbd40a6e189..d6d53151489 100644
@@ -76,6 +76,7 @@ Shell commands
    cmd/sound
    cmd/temperature
    cmd/tftpput
+   cmd/trace
    cmd/true
    cmd/ums
    cmd/ut
Signature · 1 line
2.39.0.314.g84b9a713c41-goog
#26 lore raw
In reply to Simon Glass
Quoted 11 lines · Simon Glass

Since U-Boot's tracing feature was originally written, quite a few changes have taken place in this domain. The original text format used by tracing is still emitted by Linux, but a new trace-cmd tool has invented a binary format which is now used by new tools, such as kernelshark.

With recent distributions and the move to Python 3, the old pybootchart tool does not build or run. Unfortunately there is no 1:1 replacement for the features that were provided by pybootchart, or at least it is not obvious. Still, it makes sense to keep with the times.

[...]

After talking with Simon and dropping the sandbox_vpl change, as it breaks CI and Simon notes it's only needed with LTO off, the series is now applied to u-boot/master, thanks!

Signature · 1 line
Tom