[PATCH 2/2] console: allocate only once instead of twice per log message

Ahmad Fatoum a.fatoum at pengutronix.de
Fri Aug 4 01:11:47 PDT 2023


We do two allocations for each log message, one for the log message
string itself and another for the struct log_entry referencing it.

We could just make the log message directly follow the log entry and
save the space for the pointer and the time to do a second allocation.

No functional change.

Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
 common/console_common.c | 14 +++++++-------
 include/linux/printk.h  |  2 +-
 2 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/common/console_common.c b/common/console_common.c
index 866a7cbf65dc..c78581299248 100644
--- a/common/console_common.c
+++ b/common/console_common.c
@@ -10,6 +10,7 @@
 #include <errno.h>
 #include <console.h>
 #include <init.h>
+#include <string.h>
 #include <environment.h>
 #include <globalvar.h>
 #include <magicvar.h>
@@ -19,6 +20,7 @@
 #include <malloc.h>
 #include <linux/pstore.h>
 #include <linux/math64.h>
+#include <linux/overflow.h>
 
 #ifndef CONFIG_CONSOLE_NONE
 
@@ -39,7 +41,6 @@ static int barebox_log_max_messages = 1000;
 
 static void log_del(struct log_entry *log)
 {
-	free(log->msg);
 	list_del(&log->list);
 	free(log);
 	barebox_logbuf_num_messages--;
@@ -89,15 +90,14 @@ static void pr_puts(int level, const char *str)
 			log_clean(barebox_log_max_messages - 1);
 
 		if (barebox_log_max_messages >= 0) {
-			log = malloc(sizeof(*log));
+			int msglen;
+
+			msglen = strlen(str);
+			log = malloc(struct_size(log, msg, msglen + 1));
 			if (!log)
 				goto nolog;
 
-			log->msg = strdup(str);
-			if (!log->msg) {
-				free(log);
-				goto nolog;
-			}
+			memcpy(log->msg, str, msglen + 1);
 
 			log->timestamp = get_time_ns();
 			log->level = level;
diff --git a/include/linux/printk.h b/include/linux/printk.h
index 76cdb15d5b4c..cd4c3cb68edb 100644
--- a/include/linux/printk.h
+++ b/include/linux/printk.h
@@ -148,9 +148,9 @@ int __pr_memory_display(int level, const void *addr, loff_t offs, unsigned nbyte
 
 struct log_entry {
 	struct list_head list;
-	char *msg;
 	uint64_t timestamp;
 	int level;
+	char msg[];
 };
 
 extern struct list_head barebox_logbuf;
-- 
2.39.2




More information about the barebox mailing list