+static int kinetis_check_run_mode(struct target *target)
+{
+ int result, i;
+ uint8_t pmctrl, pmstat;
+
+ if (target->state != TARGET_HALTED) {
+ LOG_ERROR("Target not halted");
+ return ERROR_TARGET_NOT_HALTED;
+ }
+
+ 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;
+}
+
+