+ result = target_read_u8(target, SMC_PMSTAT, &pmstat);
+ if (result != ERROR_OK)
+ return result;
+
+ if (pmstat == PM_STAT_RUN)
+ return ERROR_OK;
+
+ if (pmstat == PM_STAT_VLPR) {
+ /* It is safe to switch from VLPR to RUN mode without changing clock */
+ LOG_INFO("Switching from VLPR to RUN mode.");
+ pmctrl = PM_CTRL_RUNM_RUN;
+ result = target_write_u8(target, SMC_PMCTRL, pmctrl);
+ if (result != ERROR_OK)
+ return result;
+
+ for (i = 100; i; i--) {
+ result = target_read_u8(target, SMC_PMSTAT, &pmstat);
+ if (result != ERROR_OK)
+ return result;
+
+ if (pmstat == PM_STAT_RUN)
+ return ERROR_OK;
+ }
+ }
+
+ LOG_ERROR("Flash operation not possible in current run mode: SMC_PMSTAT: 0x%x", pmstat);
+ LOG_ERROR("Issue a 'reset init' command.");
+ return ERROR_TARGET_NOT_HALTED;
+}
+
+
+static void kinetis_invalidate_flash_cache(struct flash_bank *bank)
+{
+ struct kinetis_flash_bank *kinfo = bank->driver_priv;
+ uint8_t pfb01cr_byte2 = 0xf0;
+
+ if (!(kinfo->flash_support & FS_INVALIDATE_CACHE))
+ return;
+
+ target_write_memory(bank->target, FMC_PFB01CR + 2, 1, 1, &pfb01cr_byte2);
+ return;
+}
+
+
+static int kinetis_erase(struct flash_bank *bank, int first, int last)
+{
+ int result, i;
+ struct kinetis_flash_bank *kinfo = bank->driver_priv;
+
+ result = kinetis_check_run_mode(bank->target);
+ if (result != ERROR_OK)
+ return result;
+