+ struct reg_param reg_params[4];
+
+ init_reg_param(®_params[0], "a0", 32, PARAM_OUT); /* poiner to FLASH_SR */
+ init_reg_param(®_params[1], "a1", 32, PARAM_OUT); /* count (halfword-16bit) */
+ init_reg_param(®_params[2], "a2", 32, PARAM_OUT); /* buffer start */
+ init_reg_param(®_params[3], "a3", 32, PARAM_IN_OUT); /* target address */
+
+ while (hwords_count > 0) {
+ uint32_t thisrun_hwords = source->size / 2;
+
+ /* Limit to the amount of data we actually want to write */
+ if (thisrun_hwords > hwords_count)
+ thisrun_hwords = hwords_count;
+
+ /* Write data to buffer */
+ retval = target_write_buffer(target, source->address,
+ thisrun_hwords * 2, buffer);
+ if (retval != ERROR_OK)
+ break;
+
+ buf_set_u32(reg_params[0].value, 0, 32, stm32x_get_flash_reg(bank, STM32_FLASH_SR));
+ buf_set_u32(reg_params[1].value, 0, 32, thisrun_hwords);
+ buf_set_u32(reg_params[2].value, 0, 32, source->address);
+ buf_set_u32(reg_params[3].value, 0, 32, address);
+
+ retval = target_run_algorithm(target,
+ 0, NULL,
+ ARRAY_SIZE(reg_params), reg_params,
+ write_algorithm->address,
+ write_algorithm->address + sizeof(gd32vf103_flash_write_code) - 4,
+ 10000, NULL);
+
+ if (retval != ERROR_OK) {
+ LOG_ERROR("Failed to execute algorithm at 0x%" TARGET_PRIxADDR ": %d",
+ write_algorithm->address, retval);
+ break;
+ }
+
+ /* Actually we just need to check for programming errors
+ * stm32x_wait_status_busy also reports error and clears status bits
+ */
+ retval = stm32x_wait_status_busy(bank, 5);
+ if (retval != ERROR_OK) {
+ LOG_ERROR("flash write failed at address 0x%"PRIx32,
+ buf_get_u32(reg_params[3].value, 0, 32));
+ break;