Timeout when programming flash on Stellaris devices

When programming the flash on a stellaris 3748 I have been getting the following error message.

flash write_image erase image.bin

auto erase enabled

Algorithm flash write 2048 words to 0x0, 11787 remaining

timed out while waiting for target halted

error executing stellaris flash write algorithm

flash writing failed with CRIS: 0x0

error writing to flash at address 0x00000000 at offset 0x00000000 (-902)

This only occurs for the first attempt. Subsequent attempts work correctly.

I noticed that several other posts in this forum had mentioned the same problem but none contained a solution.

This has been bugging me for some time so after some research I have found the solution. Before issuing the flash write command mask the interrupts using the following command:

cortex_m3 maskisr on

The reason this works is that the openocd stellaris flash write mechanism loads a small piece of code into the device memory along with the flash data. A breakpoint is inserted at the end of the code so that the processor halts once the code has finished writing the data to flash memory. The PC and some registers are then set up to execute this code. The halt flag is then cleared and in theory the code should then execute. However if there is an interrupt pending the interrupt code is run which may or may not be valid. In most cases the processor crashes, I observed a PC value of 0xfffffffe, and the flash code never executes. Openocd monitors the processor halt flag and times out after 5 seconds which is the reason for the message:

timed out while waiting for target halted

As the processor has crashed then no further interrupts occur and so subsequent writes work fine.

So masking the interrupts prior to writing to the flash prevents this from happening.

Remember to unmask interrupts after flash programming:

cortex_m3 maskisr off