From: Ahmad Fatoum <a.fatoum@pengutronix.de>
Date: Mon, 21 Mar 2022 15:28:39 +0100
Subject: [PATCH] common: add optional systemd.hostname generation

To maintain unique hostnames, having barebox fix up its own hostname
appended by "-${global.serial_number} is a sane default. Add a Kconfig
option to enable this.

Signed-off-by: Ahmad Fatoum <a.fatoum@pengutronix.de>
Upstream-Status: Submitted [https://lore.kernel.org/all/20250411074045.2019372-1-a.fatoum@pengutronix.de/]
---
 common/Kconfig |  8 ++++++++
 common/misc.c  | 16 ++++++++++++++++
 2 files changed, 24 insertions(+)

diff --git a/common/Kconfig b/common/Kconfig
index e505032e14d1..dcc88707bad9 100644
--- a/common/Kconfig
+++ b/common/Kconfig
@@ -1169,6 +1169,14 @@ config MACHINE_ID
 	  Note: if no hashable information is available no machine id will be passed
 	  to the kernel.
 
+config SERIAL_NUMBER_FIXUP_SYSTEMD_HOSTNAME
+	bool "fix up board serial number into hostname"
+	depends on FLEXIBLE_BOOTARGS
+	help
+	  add a systemd.hostname= kernel command line argument consisting
+	  of ${global.hostname}-${global.serial_number}. If either is not
+	  available, no hostname will be fixed up.
+
 config SYSTEMD_OF_WATCHDOG
 	bool "inform devicetree-enabled kernel of used watchdog"
 	depends on WATCHDOG && OFTREE && FLEXIBLE_BOOTARGS
diff --git a/common/misc.c b/common/misc.c
index 7e19797c2f99..1154ae9e21cd 100644
--- a/common/misc.c
+++ b/common/misc.c
@@ -210,6 +210,18 @@ bool barebox_hostname_is_valid(const char *s)
 	return true;
 }
 
+static void linux_bootargs_set_hostname(void)
+{
+	char *buf;
+	if (!IS_ENABLED(CONFIG_SERIAL_NUMBER_FIXUP_SYSTEMD_HOSTNAME) ||
+	    !serial_number || !hostname)
+		return;
+
+	buf = basprintf("systemd.hostname=%s-%s", hostname, serial_number);
+	globalvar_add_simple("linux.bootargs.hostname", buf);
+	free(buf);
+}
+
 /*
  * The hostname is supposed to be the shortname of a board. It should
  * contain only lowercase letters, numbers, '-', '_'. No whitespaces
@@ -225,6 +237,8 @@ void barebox_set_hostname(const char *__hostname)
 		pr_warn("Hostname is not valid, please fix it\n");
 
 	hostname = xstrdup(__hostname);
+
+	linux_bootargs_set_hostname();
 }
 
 const char *barebox_get_hostname(void)
@@ -249,6 +263,8 @@ void barebox_set_serial_number(const char *__serial_number)
 
 	free(serial_number);
 	serial_number = xstrdup(__serial_number);
+
+	linux_bootargs_set_hostname();
 }
 
 const char *barebox_get_serial_number(void)
