How to check in openocd script if flash is protected or not?

How to check in openocd script if flash in hifive1-revb is protected or not before performing any read/write operation?

The fespi driver is here and the flash check does nothing.

Good question @bsvtgc there’s a lot of control over this process that you can do at the tcl level. See Jim-tcl Crash Course for a primer.

You don’t really need to worry about whether a memory device is locked or not, only be thoughtful to keep it in the right state at all times (i.e., good use of initialize and finalize steps).

Instead, there are a few very important things to check, when it comes to programming memory:

  1. Pre-verify the target memory to make sure writing is even necessary; in other words, don’t program a device with same data that’s already in there.
  2. When writing is necessary, pre-check the target memory to make sure erasing is even necessary; in other words, don’t erase a device that is already erased (erasing operation is a rough, high voltage operation).
  3. Determines smallest portion of target memory to work with, for best programming speed and target memory endurance (lifetime); in other words, don’t program more (blocks, pages) than you really need.

You can do all this at the openocd command line, and/or configuration script, using the tcl language.

set rc [catch {flash verify_bank 0 ${program}-rom.bin} err]  ;# trap exit on verify fail
  if {[expr $rc == 0]} {
    echo "flash device already up to date - nothing to do"
  } else {
    echo [flash protect 0 0 ${endsec} off]
    if {! $is_erased} {
      echo [flash erase_sector 0 0 ${endsec}]
    }
    echo [flash write_bank 0 ${program}-rom.bin]
    echo [flash verify_bank 0 ${program}-rom.bin]
    echo [flash protect 0 0 ${endsec} on]
  }

You can see how I unprotect (flash protect ... off) and then re-protect (flash protect ... on) the flash in appropriate sequence.

Notice the use of [catch {...} err] to trap errors of low-level and/or O/S commands that are not otherwise easily sensed by programmatic control.

I’ve put all this together as an asic_rom_load command (and an equivalent command for loading a _ram_ target) in Demystifying OpenOCD, see the fe310-g002.cfg file, and the my_prog.mk top level makefile. It’s specific to an ft2232-like hardware wiring interface right now, but easy to change for, e.g., bitbang connections by revising the top few lines of the .cfg file.