1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * Copyright (c) 2019 Western Digital Corporation or its affiliates.
4 *
5 * Authors:
6 * Anup Patel <anup.patel@wdc.com>
7 */
8
9 #include <cpu_func.h>
10 #include <dm.h>
11 #include <env.h>
12 #include <init.h>
13 #include <log.h>
14 #include <linux/bitops.h>
15 #include <linux/bug.h>
16 #include <linux/delay.h>
17 #include <misc.h>
18 #include <spl.h>
19 #include <asm/sections.h>
20
21 /*
22 * This define is a value used for error/unknown serial.
23 * If we really care about distinguishing errors and 0 is
24 * valid, we'll need a different one.
25 */
26 #define ERROR_READING_SERIAL_NUMBER 0
27
28 #ifdef CONFIG_MISC_INIT_R
29
30 #if IS_ENABLED(CONFIG_SIFIVE_OTP)
otp_read_serialnum(struct udevice * dev)31 static u32 otp_read_serialnum(struct udevice *dev)
32 {
33 int ret;
34 u32 serial[2] = {0};
35
36 for (int i = 0xfe * 4; i > 0; i -= 8) {
37 ret = misc_read(dev, i, serial, sizeof(serial));
38
39 if (ret != sizeof(serial)) {
40 printf("%s: error reading serial from OTP\n", __func__);
41 break;
42 }
43
44 if (serial[0] == ~serial[1])
45 return serial[0];
46 }
47
48 return ERROR_READING_SERIAL_NUMBER;
49 }
50 #endif
51
fu540_read_serialnum(void)52 static u32 fu540_read_serialnum(void)
53 {
54 u32 serial = ERROR_READING_SERIAL_NUMBER;
55
56 #if IS_ENABLED(CONFIG_SIFIVE_OTP)
57 struct udevice *dev;
58 int ret;
59
60 /* init OTP */
61 ret = uclass_get_device_by_driver(UCLASS_MISC,
62 DM_DRIVER_GET(sifive_otp), &dev);
63
64 if (ret) {
65 debug("%s: could not find otp device\n", __func__);
66 return serial;
67 }
68
69 /* read serial from OTP and set env var */
70 serial = otp_read_serialnum(dev);
71 #endif
72
73 return serial;
74 }
75
fu540_setup_macaddr(u32 serialnum)76 static void fu540_setup_macaddr(u32 serialnum)
77 {
78 /* Default MAC address */
79 unsigned char mac[6] = { 0x70, 0xb3, 0xd5, 0x92, 0xf0, 0x00 };
80
81 /*
82 * We derive our board MAC address by ORing last three bytes
83 * of board serial number to above default MAC address.
84 *
85 * This logic of deriving board MAC address is taken from
86 * SiFive FSBL and is kept unchanged.
87 */
88 mac[5] |= (serialnum >> 0) & 0xff;
89 mac[4] |= (serialnum >> 8) & 0xff;
90 mac[3] |= (serialnum >> 16) & 0xff;
91
92 /* Update environment variable */
93 eth_env_set_enetaddr("ethaddr", mac);
94 }
95
misc_init_r(void)96 int misc_init_r(void)
97 {
98 u32 serial_num;
99 char buf[9] = {0};
100
101 /* Set ethaddr environment variable from board serial number */
102 if (!env_get("serial#")) {
103 serial_num = fu540_read_serialnum();
104 if (!serial_num) {
105 WARN(true, "Board serial number should not be 0 !!\n");
106 return 0;
107 }
108 snprintf(buf, sizeof(buf), "%08x", serial_num);
109 env_set("serial#", buf);
110 fu540_setup_macaddr(serial_num);
111 }
112 return 0;
113 }
114
115 #endif
116
board_init(void)117 int board_init(void)
118 {
119 /* enable all cache ways */
120 enable_caches();
121
122 return 0;
123 }
124