From 61b0555d3b8e962f3cac5cf17ab149f4fb318ca3 Mon Sep 17 00:00:00 2001
From: Jonas Karlman <jonas@kwiboo.se>
Date: Mon, 20 Aug 2018 22:55:34 +0200
Subject: [PATCH] rockchip: board: use efuse cpuid to set ethaddr

---
 arch/arm/mach-rockchip/board.c | 51 ++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)

diff --git a/arch/arm/mach-rockchip/board.c b/arch/arm/mach-rockchip/board.c
index b56edebf13..155871f5bf 100644
--- a/arch/arm/mach-rockchip/board.c
+++ b/arch/arm/mach-rockchip/board.c
@@ -31,6 +31,8 @@
 #include <mmc.h>
 #include <of_live.h>
 #include <dm/root.h>
+#include <hash.h>
+#include <u-boot/sha256.h>
 
 DECLARE_GLOBAL_DATA_PTR;
 /* define serialno max length, the max length is 512 Bytes
@@ -44,6 +46,7 @@ DECLARE_GLOBAL_DATA_PTR;
 static int rockchip_set_serialno(void)
 {
 	char serialno_str[VENDOR_SN_MAX];
+	char cpuid_str[CPUID_LEN * 2 + 1];
 	int ret = 0, i;
 	u8 cpuid[CPUID_LEN] = {0};
 	u8 low[CPUID_LEN / 2], high[CPUID_LEN / 2];
@@ -73,6 +76,13 @@ static int rockchip_set_serialno(void)
 			printf("%s: reading cpuid from the efuses failed\n", __func__);
 			return ret;
 		}
+
+		memset(cpuid_str, 0, sizeof(cpuid_str));
+		for (i = 0; i < CPUID_LEN; i++) {
+			sprintf(&cpuid_str[i * 2], "%02x", cpuid[i]);
+		}
+
+		env_set("cpuid#", cpuid_str);
 #else
 		/* generate random cpuid */
 		for (i = 0; i < CPUID_LEN; i++) {
@@ -95,6 +105,45 @@ static int rockchip_set_serialno(void)
 	return ret;
 }
 
+static void rockchip_set_ethaddr(void)
+{
+#if CONFIG_IS_ENABLED(CMD_NET)
+	int ret;
+	const char *cpuid = env_get("cpuid#");
+	u8 hash[SHA256_SUM_LEN];
+	int size = sizeof(hash);
+	u8 mac_addr[6];
+
+	/* Only generate a MAC address, if none is set in the environment */
+	if (env_get("ethaddr"))
+		return;
+
+	if (!cpuid) {
+		debug("%s: could not retrieve 'cpuid#'\n", __func__);
+		return;
+	}
+
+	ret = hash_block("sha256", (void *)cpuid, strlen(cpuid), hash, &size);
+	if (ret) {
+		debug("%s: failed to calculate SHA256\n", __func__);
+		return;
+	}
+
+	/* Copy 6 bytes of the hash to base the MAC address on */
+	memcpy(mac_addr, hash, 6);
+
+	/* Make this a valid MAC address and set it */
+	mac_addr[0] &= 0xfe;  /* clear multicast bit */
+	mac_addr[0] |= 0x02;  /* set local assignment bit (IEEE802) */
+	eth_env_set_enetaddr("ethaddr", mac_addr);
+
+	/* Make a valid MAC address for eth1 */
+	mac_addr[5] += 0x20;
+	mac_addr[5] &= 0xff;
+	eth_env_set_enetaddr("eth1addr", mac_addr);
+#endif
+}
+
 #if defined(CONFIG_USB_FUNCTION_FASTBOOT)
 int fb_set_reboot_flag(void)
 {
@@ -162,6 +211,8 @@ int board_late_init(void)
 #endif
 	rockchip_set_serialno();
 
+	rockchip_set_ethaddr();
+
 	soc_clk_dump();
 
 	return rk_board_late_init();
