esp32c3: machine.Flash writes and erases fail past 2 MiB
On an ESP32-C3 with 4 MiB of flash, machine.Flash.Size() reports the space up to 4 MiB, but EraseBlocks and WriteAt fail for any address at or past 2 MiB. Below 2 MiB they work.
Board: XIAO ESP32C3 (4 MiB flash). TinyGo dev at fed7ac03.
Repro
package main
import (
"machine"
"time"
)
func main() {
time.Sleep(2 * time.Second)
f := machine.Flash
println("data start", machine.FlashDataStart(), "end", machine.FlashDataEnd(), "size", f.Size())
buf := make([]byte, 512)
for i := range buf {
buf[i] = byte(i)
}
rd := make([]byte, 512)
for _, mb := range []int64{1, 2, 3} {
// absolute physical offset mb MiB minus 4 KiB
off := mb<<20 - 4096 - (int64(machine.FlashDataStart()) - 0x3C000000)
if off < 0 || off+4096 > f.Size() {
println("skip", mb)
continue
}
eerr := f.EraseBlocks(off/4096, 1)
_, werr := f.WriteAt(buf, off)
f.ReadAt(rd, off)
println("MiB", mb, "off", off, "erase", errs(eerr), "write", errs(werr), "byte10", rd[10])
off += 4096
if off+4096 <= f.Size() {
eerr = f.EraseBlocks(off/4096, 1)
_, werr = f.WriteAt(buf, off)
f.ReadAt(rd, off)
println(" just past", mb, "MiB erase", errs(eerr), "write", errs(werr), "byte10", rd[10])
}
}
for {
time.Sleep(time.Second)
}
}
func errs(err error) string {
if err != nil {
return err.Error()
}
return "ok"
}Output:
data start 0x3c003000 end 0x3c400000 size 4182016
MiB 1 off 1032192 erase ok write ok byte10 10
just past 1 MiB erase ok write ok byte10 10
MiB 2 off 2080768 erase ok write ok byte10 10
just past 2 MiB erase cannot erase flash page write cannot write flash data byte10 255
MiB 3 off 3129344 erase cannot erase flash page write cannot write flash data byte10 255
just past 3 MiB erase cannot erase flash page write cannot write flash data byte10 255The block that ends at 2 MiB works and the block that starts at 2 MiB fails.
Likely cause
src/machine/machine_esp32c3_flash.go uses esp_rom_spiflash_erase_sector and esp_rom_spiflash_write. These check addresses against the chip size the ROM keeps in g_rom_flashchip, which starts at 2 MiB until esp_rom_spiflash_config_param sets the real size. ESP-IDF does that in its second stage bootloader. TinyGo boots without one, and targets/esp32c3.ld provides esp_rom_spiflash_config_param but nothing calls it.
Setting the chip size at startup, from the image header flash size or the flash JEDEC ID, should fix it. Until then Size() should probably not report space that cannot be written.
Source: tinygo-org/tinygo