[U-Boot] [PATCH v7 3/4] net: add helper to generate random mac address

Michael Walle michael at walle.cc
Thu May 31 20:12:44 CEST 2012


Add new function eth_random_enetaddr() to generate a locally administered
ethernet address.

Signed-off-by: Michael Walle <michael at walle.cc>
Acked-by: Joe Hershberger <joe.hershberger at gmail.com>
---
 include/net.h |   17 +++++++++++++++++
 net/eth.c     |   22 ++++++++++++++++++++++
 2 files changed, 39 insertions(+), 0 deletions(-)

diff --git a/include/net.h b/include/net.h
index a092f29..6d2d6cd 100644
--- a/include/net.h
+++ b/include/net.h
@@ -122,6 +122,23 @@ extern int eth_setenv_enetaddr(char *name, const uchar *enetaddr);
 extern int eth_getenv_enetaddr_by_index(const char *base_name, int index,
 					uchar *enetaddr);
 
+#ifdef CONFIG_RANDOM_MACADDR
+/*
+ * The u-boot policy does not allow hardcoded ethernet addresses. Under the
+ * following circumstances a random generated address is allowed:
+ *  - in emergency cases, where you need a working network connection to set
+ *    the ethernet address.
+ *    Eg. you want a rescue boot and don't have a serial port to access the
+ *    CLI to set environment variables.
+ *
+ * In these cases, we generate a random locally administered ethernet address.
+ *
+ * Args:
+ *  enetaddr - returns 6 byte hardware address
+ */
+extern void eth_random_enetaddr(uchar *enetaddr);
+#endif
+
 extern int usb_eth_initialize(bd_t *bi);
 extern int eth_init(bd_t *bis);			/* Initialize the device */
 extern int eth_send(void *packet, int length);	   /* Send a packet */
diff --git a/net/eth.c b/net/eth.c
index d9a6430..d526264 100644
--- a/net/eth.c
+++ b/net/eth.c
@@ -70,6 +70,28 @@ static int eth_mac_skip(int index)
 	return ((skip_state = getenv(enetvar)) != NULL);
 }
 
+#ifdef CONFIG_RANDOM_MACADDR
+void eth_random_enetaddr(uchar *enetaddr)
+{
+	uint32_t rval;
+
+	srand(get_timer(0));
+
+	rval = rand();
+	enetaddr[0] = rval & 0xff;
+	enetaddr[1] = (rval >> 8) & 0xff;
+	enetaddr[2] = (rval >> 16) & 0xff;
+
+	rval = rand();
+	enetaddr[3] = rval & 0xff;
+	enetaddr[4] = (rval >> 8) & 0xff;
+	enetaddr[5] = (rval >> 16) & 0xff;
+
+	/* make sure it's local and unicast */
+	enetaddr[0] = (enetaddr[0] | 0x02) & ~0x01;
+}
+#endif
+
 /*
  * CPU and board-specific Ethernet initializations.  Aliased function
  * signals caller to move on
-- 
1.7.2.5



More information about the U-Boot mailing list