STM32F4 and OpenOCD with flash erase error -304

Quick post about OpenOCD and flash erase error -304.

Getting the following error:

Open On-Chip Debugger 0.8.0 (2014-05-10-23:20)
Licensed under GNU GPL v2
For bug reports, read
        http://openocd.sourceforge.net/doc/doxygen/bugs.html
Info : This adapter doesn't support configurable speed
Info : STLINK v2 JTAG v17 API v2 SWIM v0 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 2.885664
Info : stm32f4x.cpu: hardware has 6 breakpoints, 4 watchpoints
    TargetName         Type       Endian TapName            State
--  ------------------ ---------- ------ ------------------ ------------
 0* stm32f4x.cpu       hla_target little stm32f4x.cpu       running
auto erase enabled
Info : device id = 0x10036413
Info : flash size = 1024kbytes
Info : Padding image section 1 with 4 bytes
Error: Target not halted
Error: failed erasing sectors 0 to 0
in procedure 'flash'

When trying the same with gdb, it raises the following error:

Error: flash_erase returned -304

The problem comes from the target not being halted. It is found in the source code of OpenOCD:

#define ERROR_TARGET_NOT_HALTED   (-304)

Why not trying a little...

-c halt

...on the OpenOCD command-line before flashing?

If the problem is not solved...

-c "debug_level 3"

...would show more information about what happens. It can be set to 3 and set back to 0 before and after the flash command (so as not to flood the console with debug information unrealted to flashing):

-c "debug_level 3" -c "flash write_image erase main.elf" -c "debug_level 0"