Procházet zdrojové kódy

projects/riscv_usb: Add better functions to access unique ID from flash

Signed-off-by: Sylvain Munaut <tnt@246tNt.com>
Sylvain Munaut před 5 roky
rodič
revize
6b77ba5809

+ 30 - 1
projects/riscv_usb/fw/firmware.c

@@ -27,12 +27,36 @@
 
 #include "console.h"
 #include "led.h"
+#include "mini-printf.h"
+#include "spi.h"
 #include "usb.h"
 
 
+static char *
+hexstr(void *d, int n)
+{
+	static const char * const hex = "0123456789abcdef";
+	static char buf[96];
+	uint8_t *p = d;
+	char *s = buf;
+	char c;
+
+	while (n--) {
+		c = *p++;
+		*s++ = hex[c >> 4];
+		*s++ = hex[c & 0xf];
+		*s++ = ' ';
+	}
+
+	s[-1] = '\0';
+
+	return buf;
+}
+
 void main()
 {
 	bool usb_active = false;
+	uint8_t buf[8];
 	int cmd = 0;
 
 	/* Init console IO */
@@ -48,7 +72,12 @@ void main()
 
 	/* SPI */
 	spi_init();
-	printf("Flash ID: %08x\n", flash_id());
+
+	flash_manuf_id(buf);
+	puts("Flash Manuf ID  : "); puts(hexstr(buf, 3)); puts("\n");
+
+	flash_unique_id(buf);
+	puts("Flash Unique ID : "); puts(hexstr(buf, 8)); puts("\n");
 
 	/* Main loop */
 	while (1)

+ 21 - 7
projects/riscv_usb/fw/spi.c

@@ -104,7 +104,8 @@ spi_xfer(unsigned cs, struct spi_xfer_chunk *xfer, unsigned n)
 }
 
 
-void flash_cmd(uint8_t cmd)
+void
+flash_cmd(uint8_t cmd)
 {
 	struct spi_xfer_chunk xfer[1] = {
 		{ .data = (void*)&cmd, .len = 1, .read = false, .write = true,  },
@@ -112,18 +113,31 @@ void flash_cmd(uint8_t cmd)
 	spi_xfer(SPI_CS_FLASH, xfer, 1);
 }
 
-uint32_t flash_id(void)
+void
+flash_manuf_id(void *manuf)
 {
-	uint32_t buf = 0x9f;
+	uint8_t cmd = 0x9f;
 	struct spi_xfer_chunk xfer[2] = {
-		{ .data = (void*)&buf, .len = 1, .read = false, .write = true,  },
-		{ .data = (void*)&buf, .len = 3, .read = true,  .write = false, },
+		{ .data = (void*)&cmd,  .len = 1, .read = false, .write = true,  },
+		{ .data = (void*)manuf, .len = 3, .read = true,  .write = false, },
 	};
 	spi_xfer(SPI_CS_FLASH, xfer, 2);
-	return buf;
 }
 
-void flash_read(void *dst, uint32_t addr, unsigned len)
+void
+flash_unique_id(void *id)
+{
+	uint8_t cmd = 0x4b;
+	struct spi_xfer_chunk xfer[3] = {
+		{ .data = (void*)&cmd, .len = 1, .read = false, .write = true,  },
+		{ .data = (void*)0,    .len = 4, .read = false, .write = false, },
+		{ .data = (void*)id,   .len = 8, .read = true,  .write = false, },
+	};
+	spi_xfer(SPI_CS_FLASH, xfer, 3);
+}
+
+void
+flash_read(void *dst, uint32_t addr, unsigned len)
 {
 	uint8_t cmd[4] = { 0x03, ((addr >> 16) & 0xff), ((addr >> 8) & 0xff), (addr & 0xff)  };
 	struct spi_xfer_chunk xfer[2] = {

+ 2 - 1
projects/riscv_usb/fw/spi.h

@@ -39,7 +39,8 @@ void spi_init(void);
 void spi_xfer(unsigned cs, struct spi_xfer_chunk *xfer, unsigned n);
 
 void flash_cmd(uint8_t cmd);
-uint32_t flash_id(void);
+void flash_manuf_id(void *manuf);
+void flash_unique_id(void *id);
 void flash_read(void *dst, uint32_t addr, unsigned len);
 
 static inline void flash_power_up(void)   { flash_cmd(0xab); };