1 /*
2  * Copyright (c) 2020 Linaro Ltd
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef ZEPHYR_DRIVERS_ETHERNET_ETH_H_
8 #define ZEPHYR_DRIVERS_ETHERNET_ETH_H_
9 
10 #include <zephyr/types.h>
11 #include <zephyr/random/random.h>
12 
13 /* helper macro to return mac address octet from local_mac_address prop */
14 #define NODE_MAC_ADDR_OCTET(node, n) DT_PROP_BY_IDX(node, local_mac_address, n)
15 
16 /* Determine if a mac address is all 0's */
17 #define NODE_MAC_ADDR_NULL(node) \
18 	((NODE_MAC_ADDR_OCTET(node, 0) == 0) && \
19 	 (NODE_MAC_ADDR_OCTET(node, 1) == 0) && \
20 	 (NODE_MAC_ADDR_OCTET(node, 2) == 0) && \
21 	 (NODE_MAC_ADDR_OCTET(node, 3) == 0) && \
22 	 (NODE_MAC_ADDR_OCTET(node, 4) == 0) && \
23 	 (NODE_MAC_ADDR_OCTET(node, 5) == 0))
24 
25 /* Given a device tree node for an ethernet controller will
26  * returns false if there is no local-mac-address property or
27  * the property is all zero's.  Otherwise will return True
28  */
29 #define NODE_HAS_VALID_MAC_ADDR(node) \
30 	UTIL_AND(DT_NODE_HAS_PROP(node, local_mac_address),\
31 			(!NODE_MAC_ADDR_NULL(node)))
32 
gen_random_mac(uint8_t * mac_addr,uint8_t b0,uint8_t b1,uint8_t b2)33 static inline void gen_random_mac(uint8_t *mac_addr, uint8_t b0, uint8_t b1, uint8_t b2)
34 {
35 	uint32_t entropy;
36 
37 	entropy = sys_rand32_get();
38 
39 	mac_addr[0] = b0;
40 	mac_addr[1] = b1;
41 	mac_addr[2] = b2;
42 
43 	/* Set MAC address locally administered, unicast (LAA) */
44 	mac_addr[0] |= 0x02;
45 
46 	mac_addr[3] = (entropy >> 16) & 0xff;
47 	mac_addr[4] = (entropy >>  8) & 0xff;
48 	mac_addr[5] = (entropy >>  0) & 0xff;
49 }
50 
51 #endif /* ZEPHYR_DRIVERS_ETHERNET_ETH_H_ */
52