OpenOCD with the ST-Link v2

There is an issue when trying to program a SAMD21 like in the Arduino Zero using OpenOCD with a ST-Link v2 which gives errors like this:

** Programming Started **
auto erase enabled
Info : SAMD MCU: SAMD21E18A (256KB Flash, 32KB RAM)
Error: Failed to erase row containing 00000000
Error: SAMD: failed to erase sector 0
Error: failed erasing sectors 0 to 0

The issue is that NVMCTRL_CTRLA is a half-word register and the ST-Link v2 emulates the half word write using two single byte writes.

The hack-around is to change to a word write:

diff --git a/src/flash/nor/at91samd.c b/src/flash/nor/at91samd.c
index 2673b0ee..f060bceb 100644
--- a/src/flash/nor/at91samd.c
+++ b/src/flash/nor/at91samd.c
@@ -472,7 +472,7 @@ static int samd_issue_nvmctrl_command(struct target *target, uint16_t cmd)

        /* Issue the NVM command */
-       res = target_write_u16(target,
+       res = target_write_u32(target,
                        SAMD_NVMCTRL + SAMD_NVMCTRL_CTRLA, SAMD_NVM_CMD(cmd));
        if (res != ERROR_OK)
                return res;

See for more.