flash/nor/kinetis_ke: add .help fields for tcl commands
[fw/openocd] / src / flash / nor / kinetis_ke.c
1 /***************************************************************************
2  *   Copyright (C) 2015 by Ivan Meleca                                     *
3  *   ivan@artekit.eu                                                       *
4  *                                                                         *
5  *   Modified from kinetis.c                                               *
6  *                                                                         *
7  *   Copyright (C) 2011 by Mathias Kuester                                 *
8  *   kesmtp@freenet.de                                                     *
9  *                                                                         *
10  *   Copyright (C) 2011 sleep(5) ltd                                       *
11  *   tomas@sleepfive.com                                                   *
12  *                                                                         *
13  *   Copyright (C) 2012 by Christopher D. Kilgour                          *
14  *   techie at whiterocker.com                                             *
15  *                                                                         *
16  *   Copyright (C) 2013 Nemui Trinomius                                    *
17  *   nemuisan_kawausogasuki@live.jp                                        *
18  *                                                                         *
19  *   Copyright (C) 2015 Tomas Vanek                                        *
20  *   vanekt@fbl.cz                                                         *
21  *                                                                         *
22  *   This program is free software; you can redistribute it and/or modify  *
23  *   it under the terms of the GNU General Public License as published by  *
24  *   the Free Software Foundation; either version 2 of the License, or     *
25  *   (at your option) any later version.                                   *
26  *                                                                         *
27  *   This program is distributed in the hope that it will be useful,       *
28  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
29  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
30  *   GNU General Public License for more details.                          *
31  *                                                                         *
32  *   You should have received a copy of the GNU General Public License     *
33  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
34  ***************************************************************************/
35
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39
40 #include "jtag/interface.h"
41 #include "imp.h"
42 #include <helper/binarybuffer.h>
43 #include <target/algorithm.h>
44 #include <target/arm_adi_v5.h>
45 #include <target/armv7m.h>
46 #include <target/cortex_m.h>
47
48 /* Addresses */
49 #define SIM_SRSID                                       0x40048000
50 #define ICS_C1                                          0x40064000
51 #define ICS_C2                                          0x40064001
52 #define ICS_C3                                          0x40064002
53 #define ICS_C4                                          0x40064003
54 #define ICS_S                                           0x40064004
55 #define SIM_BUSDIV                                      0x40048018
56 #define SIM_CLKDIV_KE06                         0x40048024
57 #define SIM_CLKDIV_KE04_44_64_80        0x40048024
58 #define SIM_CLKDIV_KE04_16_20_24        0x4004801C
59 #define WDOG_CS1                                        0x40052000
60
61 #define ICS_C2_BDIV_MASK                        0xE0
62 #define ICS_C2_BDIV_SHIFT                       5
63 #define ICS_C2_BDIV(x)                          (((uint8_t)(((uint8_t)(x))<<ICS_C2_BDIV_SHIFT))&ICS_C2_BDIV_MASK)
64 #define ICS_S_LOCK_MASK                         0x40
65 #define ICS_C4_SCFTRIM_MASK                     0x1
66 #define SIM_CLKDIV_OUTDIV2_MASK         0x1000000
67 #define FTMRX_FCLKDIV_FDIV_MASK         0x3F
68 #define FTMRX_FCLKDIV_FDIV_SHIFT        0
69 #define FTMRX_FCLKDIV_FDIV(x)           (((uint8_t)(((uint8_t)(x))<<FTMRX_FCLKDIV_FDIV_SHIFT))&FTMRX_FCLKDIV_FDIV_MASK)
70 #define FTMRX_FCLKDIV_FDIVLCK_MASK      0x40
71 #define FTMRX_FCLKDIV_FDIVLCK_SHIFT     6
72 #define FTMRX_FCLKDIV_FDIVLD_MASK       0x80
73 #define FTMRX_FCLKDIV_FDIVLD_SHIFT      7
74 #define FTMRX_FSTAT_CCIF_MASK           0x80
75 #define FTMRX_FSTAT_MGSTAT0_MASK        0x01
76 #define FTMRX_FSTAT_MGSTAT1_MASK        0x02
77
78 /* Commands */
79 #define FTMRX_CMD_ALLERASED                     0x01
80 #define FTMRX_CMD_BLOCKERASED           0x02
81 #define FTMRX_CMD_SECTIONERASED         0x03
82 #define FTMRX_CMD_READONCE                      0x04
83 #define FTMRX_CMD_PROGFLASH                     0x06
84 #define FTMRX_CMD_PROGONCE                      0x07
85 #define FTMRX_CMD_ERASEALL                      0x08
86 #define FTMRX_CMD_ERASEBLOCK            0x09
87 #define FTMRX_CMD_ERASESECTOR           0x0A
88 #define FTMRX_CMD_UNSECURE                      0x0B
89 #define FTMRX_CMD_VERIFYACCESS          0x0C
90 #define FTMRX_CMD_SETMARGINLVL          0x0D
91 #define FTMRX_CMD_SETFACTORYLVL         0x0E
92 #define FTMRX_CMD_CONFIGNVM                     0x0F
93
94 /* Error codes */
95 #define FTMRX_ERROR_ACCERR                      0x20
96 #define FTMRX_ERROR_FPVIOL                      0x10
97
98 #define KINETIS_KE_SRSID_FAMID(x)               ((x >> 28) & 0x0F)
99 #define KINETIS_KE_SRSID_SUBFAMID(x)    ((x >> 24) & 0x0F)
100 #define KINETIS_KE_SRSID_PINCOUNT(x)    ((x >> 16) & 0x0F)
101
102 #define KINETIS_KE_SRSID_KEX2   0x02
103 #define KINETIS_KE_SRSID_KEX4   0x04
104 #define KINETIS_KE_SRSID_KEX6   0x06
105
106 struct kinetis_ke_flash_bank {
107         uint32_t sector_size;
108         uint32_t protection_size;
109
110         uint32_t sim_srsid;
111         uint32_t ftmrx_fclkdiv_addr;
112         uint32_t ftmrx_fccobix_addr;
113         uint32_t ftmrx_fstat_addr;
114         uint32_t ftmrx_fprot_addr;
115         uint32_t ftmrx_fccobhi_addr;
116         uint32_t ftmrx_fccoblo_addr;
117 };
118
119 #define MDM_REG_STAT            0x00
120 #define MDM_REG_CTRL            0x04
121 #define MDM_REG_ID                      0xfc
122
123 #define MDM_STAT_FMEACK         (1<<0)
124 #define MDM_STAT_FREADY         (1<<1)
125 #define MDM_STAT_SYSSEC         (1<<2)
126 #define MDM_STAT_SYSRES         (1<<3)
127 #define MDM_STAT_FMEEN          (1<<5)
128 #define MDM_STAT_BACKDOOREN     (1<<6)
129 #define MDM_STAT_LPEN           (1<<7)
130 #define MDM_STAT_VLPEN          (1<<8)
131 #define MDM_STAT_LLSMODEXIT     (1<<9)
132 #define MDM_STAT_VLLSXMODEXIT   (1<<10)
133 #define MDM_STAT_CORE_HALTED    (1<<16)
134 #define MDM_STAT_CORE_SLEEPDEEP (1<<17)
135 #define MDM_STAT_CORESLEEPING   (1<<18)
136
137 #define MEM_CTRL_FMEIP          (1<<0)
138 #define MEM_CTRL_DBG_DIS        (1<<1)
139 #define MEM_CTRL_DBG_REQ        (1<<2)
140 #define MEM_CTRL_SYS_RES_REQ    (1<<3)
141 #define MEM_CTRL_CORE_HOLD_RES  (1<<4)
142 #define MEM_CTRL_VLLSX_DBG_REQ  (1<<5)
143 #define MEM_CTRL_VLLSX_DBG_ACK  (1<<6)
144 #define MEM_CTRL_VLLSX_STAT_ACK (1<<7)
145
146 #define MDM_ACCESS_TIMEOUT      3000 /* iterations */
147
148 static int kinetis_ke_mdm_write_register(struct adiv5_dap *dap, unsigned reg, uint32_t value)
149 {
150         int retval;
151         LOG_DEBUG("MDM_REG[0x%02x] <- %08" PRIX32, reg, value);
152
153         retval = dap_queue_ap_write(dap_ap(dap, 1), reg, value);
154         if (retval != ERROR_OK) {
155                 LOG_DEBUG("MDM: failed to queue a write request");
156                 return retval;
157         }
158
159         retval = dap_run(dap);
160         if (retval != ERROR_OK) {
161                 LOG_DEBUG("MDM: dap_run failed");
162                 return retval;
163         }
164
165         return ERROR_OK;
166 }
167
168 static int kinetis_ke_mdm_read_register(struct adiv5_dap *dap, unsigned reg, uint32_t *result)
169 {
170         int retval;
171         retval = dap_queue_ap_read(dap_ap(dap, 1), reg, result);
172         if (retval != ERROR_OK) {
173                 LOG_DEBUG("MDM: failed to queue a read request");
174                 return retval;
175         }
176
177         retval = dap_run(dap);
178         if (retval != ERROR_OK) {
179                 LOG_DEBUG("MDM: dap_run failed");
180                 return retval;
181         }
182
183         LOG_DEBUG("MDM_REG[0x%02x]: %08" PRIX32, reg, *result);
184         return ERROR_OK;
185 }
186
187 static int kinetis_ke_mdm_poll_register(struct adiv5_dap *dap, unsigned reg, uint32_t mask, uint32_t value)
188 {
189         uint32_t val;
190         int retval;
191         int timeout = MDM_ACCESS_TIMEOUT;
192
193         do {
194                 retval = kinetis_ke_mdm_read_register(dap, reg, &val);
195                 if (retval != ERROR_OK || (val & mask) == value)
196                         return retval;
197
198                 alive_sleep(1);
199         } while (timeout--);
200
201         LOG_DEBUG("MDM: polling timed out");
202         return ERROR_FAIL;
203 }
204
205 static int kinetis_ke_prepare_flash(struct flash_bank *bank)
206 {
207         struct target *target = bank->target;
208         struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
209         uint8_t c2, c3, c4, s = 0;
210         uint16_t trim_value = 0;
211         uint16_t timeout = 0;
212         uint32_t bus_clock = 0;
213         uint32_t bus_reg_val = 0;
214         uint32_t bus_reg_addr = 0;
215         uint32_t flash_clk_div;
216         uint8_t fclkdiv;
217         int result;
218
219         /*
220          * The RM states that the flash clock has to be set to 1MHz for writing and
221          * erasing operations (otherwise it can damage the flash).
222          * This function configures the entire clock tree to make sure we
223          * run at the specified clock. We'll set FEI mode running from the ~32KHz
224          * internal clock. So we need to:
225          * - Trim internal clock.
226          * - Configure the divider for ICSOUTCLK (ICS module).
227          * - Configure the divider to get a bus clock (SIM module).
228          * - Configure the flash clock that depends on the bus clock.
229          *
230          * For MKE02_40 and MKE02_20 we set ICSOUTCLK = 20MHz and bus clock = 20MHz.
231          * For MKE04 and MKE06 we run at ICSOUTCLK = 48MHz and bus clock = 24MHz.
232          */
233
234         /*
235          * Trim internal clock
236          */
237         switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
238
239                 case KINETIS_KE_SRSID_KEX2:
240                         /* Both KE02_20 and KE02_40 should get the same trim value */
241                         trim_value = 0x4C;
242                         break;
243
244                 case KINETIS_KE_SRSID_KEX4:
245                         trim_value = 0x54;
246                         break;
247
248                 case KINETIS_KE_SRSID_KEX6:
249                         trim_value = 0x58;
250                         break;
251         }
252
253         result = target_read_u8(target, ICS_C4, &c4);
254         if (result != ERROR_OK)
255                 return result;
256
257         c3 = trim_value;
258         c4 = (c4 & ~(ICS_C4_SCFTRIM_MASK)) | ((trim_value >> 8) & 0x01);
259
260         result = target_write_u8(target, ICS_C3, c3);
261         if (result != ERROR_OK)
262                 return result;
263
264         result = target_write_u8(target, ICS_C4, c4);
265         if (result != ERROR_OK)
266                 return result;
267
268         result = target_read_u8(target, ICS_S, &s);
269         if (result != ERROR_OK)
270                 return result;
271
272         /* Wait */
273         while (!(s & ICS_S_LOCK_MASK)) {
274
275                 if (timeout <= 1000) {
276                         timeout++;
277                         alive_sleep(1);
278                 } else {
279                         return ERROR_FAIL;
280                 }
281
282                 result = target_read_u8(target, ICS_S, &s);
283                 if (result != ERROR_OK)
284                         return result;
285         }
286
287         /* ... trim done ... */
288
289         /*
290          * Configure SIM (bus clock)
291          */
292         switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
293
294                 /* KE02 sub-family operates on SIM_BUSDIV */
295                 case KINETIS_KE_SRSID_KEX2:
296                         bus_reg_val = 0;
297                         bus_reg_addr = SIM_BUSDIV;
298                         bus_clock = 20000000;
299                         break;
300
301                 /* KE04 and KE06 sub-family operates on SIM_CLKDIV
302                  * Clocks are divided by:
303                  * DIV1 = core clock = 48MHz
304                  * DIV2 = bus clock = 24Mhz
305                  * DIV3 = timer clocks
306                  * So we need to configure SIM_CLKDIV, DIV1 and DIV2 value
307                  */
308                 case KINETIS_KE_SRSID_KEX4:
309                         /* KE04 devices have the SIM_CLKDIV register at a different offset
310                          * depending on the pin count. */
311                         switch (KINETIS_KE_SRSID_PINCOUNT(kinfo->sim_srsid)) {
312
313                                 /* 16, 20 and 24 pins */
314                                 case 1:
315                                 case 2:
316                                 case 3:
317                                         bus_reg_addr = SIM_CLKDIV_KE04_16_20_24;
318                                         break;
319
320                                 /* 44, 64 and 80 pins */
321                                 case 5:
322                                 case 7:
323                                 case 8:
324                                         bus_reg_addr = SIM_CLKDIV_KE04_44_64_80;
325                                         break;
326
327                                 default:
328                                         LOG_ERROR("KE04 - Unknown pin count");
329                                         return ERROR_FAIL;
330                         }
331
332                         bus_reg_val = SIM_CLKDIV_OUTDIV2_MASK;
333                         bus_clock = 24000000;
334                         break;
335
336                 case KINETIS_KE_SRSID_KEX6:
337                         bus_reg_val = SIM_CLKDIV_OUTDIV2_MASK;
338                         bus_reg_addr = SIM_CLKDIV_KE06;
339                         bus_clock = 24000000;
340                         break;
341         }
342
343         result = target_write_u32(target, bus_reg_addr, bus_reg_val);
344         if (result != ERROR_OK)
345                 return result;
346
347         /*
348          * Configure ICS to FEI (internal source)
349          */
350         result = target_read_u8(target, ICS_C2, &c2);
351         if (result != ERROR_OK)
352                 return result;
353
354         c2 &= ~ICS_C2_BDIV_MASK;
355
356         switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
357
358                 case KINETIS_KE_SRSID_KEX2:
359                         /* Note: since there are two KE02 types, the KE02_40 @ 40MHz and the
360                          * KE02_20 @ 20MHz, we divide here the ~40MHz ICSFLLCLK down to 20MHz,
361                          * for compatibility.
362                          */
363                         c2 |= ICS_C2_BDIV(1);
364                         break;
365
366                 case KINETIS_KE_SRSID_KEX4:
367                 case KINETIS_KE_SRSID_KEX6:
368                         /* For KE04 and KE06, the ICSFLLCLK can be 48MHz. */
369                         c2 |= ICS_C2_BDIV(0);
370                         break;
371         }
372
373         result = target_write_u8(target, ICS_C2, c2);
374         if (result != ERROR_OK)
375                 return result;
376
377         /* Internal clock as reference (IREFS = 1) */
378         result = target_write_u8(target, ICS_C1, 4);
379         if (result != ERROR_OK)
380                 return result;
381
382         /* Wait for FLL to lock */
383         result = target_read_u8(target, ICS_S, &s);
384         if (result != ERROR_OK)
385                 return result;
386
387         while (!(s & ICS_S_LOCK_MASK)) {
388
389                 if (timeout <= 1000) {
390                         timeout++;
391                         alive_sleep(1);
392                 } else {
393                         return ERROR_FLASH_OPERATION_FAILED;
394                 }
395
396                 result = target_read_u8(target, ICS_S, &s);
397                 if (result != ERROR_OK)
398                         return result;
399         }
400
401         /*
402          * Configure flash clock to 1MHz.
403          */
404         flash_clk_div = bus_clock / 1000000L - 1;
405
406         /* Check if the FCLKDIV register is locked */
407         result = target_read_u8(target, kinfo->ftmrx_fclkdiv_addr, &fclkdiv);
408         if (result != ERROR_OK)
409                 return result;
410
411         if (!(fclkdiv & FTMRX_FCLKDIV_FDIVLCK_MASK)) {
412                 /* Unlocked. Check if the register was configured, and if so, if it has the right value */
413                 if ((fclkdiv & FTMRX_FCLKDIV_FDIVLD_MASK) &&
414                         ((fclkdiv & FTMRX_FCLKDIV_FDIV_MASK) != FTMRX_FCLKDIV_FDIV(flash_clk_div))) {
415                         LOG_WARNING("Flash clock was already set and contains an invalid value.");
416                         LOG_WARNING("Please reset the target.");
417                         return ERROR_FAIL;
418                 }
419
420                 /* Finally, configure the flash clock */
421                 fclkdiv = (fclkdiv & ~(FTMRX_FCLKDIV_FDIV_MASK)) | FTMRX_FCLKDIV_FDIV(flash_clk_div);
422                 result = target_write_u8(target, kinfo->ftmrx_fclkdiv_addr, fclkdiv);
423                 if (result != ERROR_OK)
424                         return result;
425         } else {
426                 /* Locked. Check if the current value is correct. */
427                 if ((fclkdiv & FTMRX_FCLKDIV_FDIV_MASK) != FTMRX_FCLKDIV_FDIV(flash_clk_div)) {
428                         LOG_WARNING("Flash clock register is locked and contains an invalid value.");
429                         LOG_WARNING("Please reset the target.");
430                         return ERROR_FAIL;
431                 }
432         }
433
434         LOG_INFO("Flash clock ready");
435         return ERROR_OK;
436 }
437
438 static int kinetis_ke_stop_watchdog(struct target *target)
439 {
440         struct working_area *watchdog_algorithm;
441         struct armv7m_algorithm armv7m_info;
442         int retval;
443         uint8_t cs1;
444
445         static const uint8_t watchdog_code[] = {
446 #include "../../../contrib/loaders/flash/kinetis_ke/kinetis_ke_watchdog.inc"
447         };
448
449         if (target->state != TARGET_HALTED) {
450                 LOG_ERROR("Target not halted");
451                 return ERROR_TARGET_NOT_HALTED;
452         }
453
454         /* Check if the watchdog is enabled */
455         retval = target_read_u8(target, WDOG_CS1, &cs1);
456         if (retval != ERROR_OK)
457                 return retval;
458
459         if (!(cs1 & 0x80)) {
460                 /* Already stopped */
461                 return ERROR_OK;
462         }
463
464         /* allocate working area with watchdog code */
465         if (target_alloc_working_area(target, sizeof(watchdog_code), &watchdog_algorithm) != ERROR_OK) {
466                 LOG_WARNING("No working area available for watchdog algorithm");
467                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
468         }
469
470         retval = target_write_buffer(target, watchdog_algorithm->address,
471                         sizeof(watchdog_code), watchdog_code);
472         if (retval != ERROR_OK)
473                 return retval;
474
475         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
476         armv7m_info.core_mode = ARM_MODE_THREAD;
477
478         retval = target_run_algorithm(target, 0, NULL, 0, NULL,
479                         watchdog_algorithm->address, 0, 100000, &armv7m_info);
480         if (retval != ERROR_OK) {
481                 LOG_ERROR("Error executing Kinetis KE watchdog algorithm");
482         } else {
483                 LOG_INFO("Watchdog stopped");
484         }
485
486         target_free_working_area(target, watchdog_algorithm);
487
488         return retval;
489 }
490
491 COMMAND_HANDLER(kinetis_ke_disable_wdog_handler)
492 {
493         struct target *target = get_current_target(CMD_CTX);
494
495         if (CMD_ARGC > 0)
496                 return ERROR_COMMAND_SYNTAX_ERROR;
497
498         return kinetis_ke_stop_watchdog(target);
499 }
500
501 COMMAND_HANDLER(kinetis_ke_mdm_mass_erase)
502 {
503         struct target *target = get_current_target(CMD_CTX);
504         struct cortex_m_common *cortex_m = target_to_cm(target);
505         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
506
507         if (!dap) {
508                 LOG_ERROR("Cannot perform mass erase with a high-level adapter");
509                 return ERROR_FAIL;
510         }
511
512         int retval;
513
514         /* According to chapter 18.3.7.2 of the KE02 reference manual */
515
516         /* assert SRST */
517         if (jtag_get_reset_config() & RESET_HAS_SRST)
518                 adapter_assert_reset();
519
520         /*
521          * 1. Reset the device by asserting RESET pin or DAP_CTRL[3]
522          */
523         retval = kinetis_ke_mdm_write_register(dap, MDM_REG_CTRL, MEM_CTRL_SYS_RES_REQ);
524         if (retval != ERROR_OK)
525                 return retval;
526
527         /*
528          * ... Read the MDM-AP status register until the Flash Ready bit sets...
529          */
530         retval = kinetis_ke_mdm_poll_register(dap, MDM_REG_STAT,
531                                            MDM_STAT_FREADY | MDM_STAT_SYSRES,
532                                            MDM_STAT_FREADY);
533         if (retval != ERROR_OK) {
534                 LOG_ERROR("MDM : flash ready timeout");
535                 return retval;
536         }
537
538         /*
539          * 2. Set DAP_CTRL[0] bit to invoke debug mass erase via SWD
540          * 3. Release reset by deasserting RESET pin or DAP_CTRL[3] bit via SWD.
541          */
542         retval = kinetis_ke_mdm_write_register(dap, MDM_REG_CTRL, MEM_CTRL_FMEIP);
543         if (retval != ERROR_OK)
544                 return retval;
545
546         /* As a sanity check make sure that device started mass erase procedure */
547         retval = kinetis_ke_mdm_poll_register(dap, MDM_REG_STAT,
548                                            MDM_STAT_FMEACK, MDM_STAT_FMEACK);
549         if (retval != ERROR_OK)
550                 return retval;
551
552         /*
553          * 4. Wait till DAP_CTRL[0] bit is cleared (after mass erase completes,
554          * DAP_CTRL[0] bit is cleared automatically).
555          */
556         retval = kinetis_ke_mdm_poll_register(dap, MDM_REG_CTRL,
557                                            MEM_CTRL_FMEIP,
558                                            0);
559         if (retval != ERROR_OK)
560                 return retval;
561
562         if (jtag_get_reset_config() & RESET_HAS_SRST)
563                 adapter_deassert_reset();
564
565         return ERROR_OK;
566 }
567
568 static const uint32_t kinetis_ke_known_mdm_ids[] = {
569         0x001C0020,     /* Kinetis-L/M/V/E/KE Series */
570 };
571
572 /*
573  * This function implements the procedure to connect to
574  * SWD/JTAG on Kinetis K and L series of devices as it is described in
575  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
576  * and L-series MCUs" Section 4.1.1
577  */
578 COMMAND_HANDLER(kinetis_ke_check_flash_security_status)
579 {
580         struct target *target = get_current_target(CMD_CTX);
581         struct cortex_m_common *cortex_m = target_to_cm(target);
582         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
583
584         if (!dap) {
585                 LOG_WARNING("Cannot check flash security status with a high-level adapter");
586                 return ERROR_OK;
587         }
588
589         uint32_t val;
590         int retval;
591
592         /*
593          * ... The MDM-AP ID register can be read to verify that the
594          * connection is working correctly...
595          */
596         retval = kinetis_ke_mdm_read_register(dap, MDM_REG_ID, &val);
597         if (retval != ERROR_OK) {
598                 LOG_ERROR("MDM: failed to read ID register");
599                 goto fail;
600         }
601
602         bool found = false;
603         for (size_t i = 0; i < ARRAY_SIZE(kinetis_ke_known_mdm_ids); i++) {
604                 if (val == kinetis_ke_known_mdm_ids[i]) {
605                         found = true;
606                         break;
607                 }
608         }
609
610         if (!found)
611                 LOG_WARNING("MDM: unknown ID %08" PRIX32, val);
612
613         /*
614          * ... Read the MDM-AP status register until the Flash Ready bit sets...
615          */
616         retval = kinetis_ke_mdm_poll_register(dap, MDM_REG_STAT,
617                                            MDM_STAT_FREADY,
618                                            MDM_STAT_FREADY);
619         if (retval != ERROR_OK) {
620                 LOG_ERROR("MDM: flash ready timeout");
621                 goto fail;
622         }
623
624         /*
625          * ... Read the System Security bit to determine if security is enabled.
626          * If System Security = 0, then proceed. If System Security = 1, then
627          * communication with the internals of the processor, including the
628          * flash, will not be possible without issuing a mass erase command or
629          * unsecuring the part through other means (backdoor key unlock)...
630          */
631         retval = kinetis_ke_mdm_read_register(dap, MDM_REG_STAT, &val);
632         if (retval != ERROR_OK) {
633                 LOG_ERROR("MDM: failed to read MDM_REG_STAT");
634                 goto fail;
635         }
636
637         if (val & MDM_STAT_SYSSEC) {
638                 jtag_poll_set_enabled(false);
639
640                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
641                 LOG_WARNING("****                                                          ****");
642                 LOG_WARNING("**** Your Kinetis MCU is in secured state, which means that,  ****");
643                 LOG_WARNING("**** with exception for very basic communication, JTAG/SWD    ****");
644                 LOG_WARNING("**** interface will NOT work. In order to restore its         ****");
645                 LOG_WARNING("**** functionality please issue 'kinetis_ke mdm mass_erase'   ****");
646                 LOG_WARNING("**** command, power cycle the MCU and restart OpenOCD.        ****");
647                 LOG_WARNING("****                                                          ****");
648                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
649         } else {
650                 LOG_INFO("MDM: Chip is unsecured. Continuing.");
651                 jtag_poll_set_enabled(true);
652         }
653
654         return ERROR_OK;
655
656 fail:
657         LOG_ERROR("MDM: Failed to check security status of the MCU. Cannot proceed further");
658         jtag_poll_set_enabled(false);
659         return retval;
660 }
661
662 FLASH_BANK_COMMAND_HANDLER(kinetis_ke_flash_bank_command)
663 {
664         struct kinetis_ke_flash_bank *bank_info;
665
666         if (CMD_ARGC < 6)
667                 return ERROR_COMMAND_SYNTAX_ERROR;
668
669         LOG_INFO("add flash_bank kinetis_ke %s", bank->name);
670
671         bank_info = malloc(sizeof(struct kinetis_ke_flash_bank));
672
673         memset(bank_info, 0, sizeof(struct kinetis_ke_flash_bank));
674
675         bank->driver_priv = bank_info;
676
677         return ERROR_OK;
678 }
679
680 /* Kinetis Program-LongWord Microcodes */
681 static uint8_t kinetis_ke_flash_write_code[] = {
682 #include "../../../contrib/loaders/flash/kinetis_ke/kinetis_ke_flash.inc"
683 };
684
685 static int kinetis_ke_write_words(struct flash_bank *bank, const uint8_t *buffer,
686                                                                 uint32_t offset, uint32_t words)
687 {
688         struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
689         struct target *target = bank->target;
690         uint32_t ram_buffer_size = 512 + 16;
691         struct working_area *write_algorithm;
692         struct working_area *source;
693         uint32_t address = bank->base + offset;
694         struct reg_param reg_params[4];
695         struct armv7m_algorithm armv7m_info;
696         int retval = ERROR_OK;
697         uint32_t flash_code_size;
698
699         LOG_INFO("Kinetis KE: FLASH Write ...");
700
701         /* allocate working area with flash programming code */
702         if (target_alloc_working_area(target, sizeof(kinetis_ke_flash_write_code),
703                         &write_algorithm) != ERROR_OK) {
704                 LOG_WARNING("no working area available, can't do block memory writes");
705                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
706         }
707
708         /* Patch the FTMRx registers addresses */
709         flash_code_size = sizeof(kinetis_ke_flash_write_code);
710         buf_set_u32(&kinetis_ke_flash_write_code[flash_code_size-16], 0, 32, kinfo->ftmrx_fstat_addr);
711         buf_set_u32(&kinetis_ke_flash_write_code[flash_code_size-12], 0, 32, kinfo->ftmrx_fccobix_addr);
712         buf_set_u32(&kinetis_ke_flash_write_code[flash_code_size-8], 0, 32, kinfo->ftmrx_fccobhi_addr);
713         buf_set_u32(&kinetis_ke_flash_write_code[flash_code_size-4], 0, 32, kinfo->ftmrx_fccoblo_addr);
714
715         retval = target_write_buffer(target, write_algorithm->address,
716                 sizeof(kinetis_ke_flash_write_code), kinetis_ke_flash_write_code);
717         if (retval != ERROR_OK)
718                 return retval;
719
720         /* memory buffer */
721         if (target_alloc_working_area(target, ram_buffer_size, &source) != ERROR_OK) {
722                 /* free working area, write algorithm already allocated */
723                 target_free_working_area(target, write_algorithm);
724
725                 LOG_WARNING("No large enough working area available, can't do block memory writes");
726                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
727         }
728
729         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
730         armv7m_info.core_mode = ARM_MODE_THREAD;
731
732         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);
733         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
734         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
735         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
736
737         buf_set_u32(reg_params[0].value, 0, 32, address);
738         buf_set_u32(reg_params[1].value, 0, 32, words);
739         buf_set_u32(reg_params[2].value, 0, 32, source->address);
740         buf_set_u32(reg_params[3].value, 0, 32, source->address + source->size);
741
742         retval = target_run_flash_async_algorithm(target, buffer, words, 4,
743                         0, NULL,
744                         4, reg_params,
745                         source->address, source->size,
746                         write_algorithm->address, 0,
747                         &armv7m_info);
748
749         if (retval == ERROR_FLASH_OPERATION_FAILED) {
750                 if (buf_get_u32(reg_params[0].value, 0, 32) & FTMRX_ERROR_ACCERR)
751                         LOG_ERROR("flash access error");
752
753                 if (buf_get_u32(reg_params[0].value, 0, 32) & FTMRX_ERROR_FPVIOL)
754                         LOG_ERROR("flash protection violation");
755         }
756
757         target_free_working_area(target, source);
758         target_free_working_area(target, write_algorithm);
759
760         destroy_reg_param(&reg_params[0]);
761         destroy_reg_param(&reg_params[1]);
762         destroy_reg_param(&reg_params[2]);
763         destroy_reg_param(&reg_params[3]);
764
765         return retval;
766 }
767
768 static int kinetis_ke_protect(struct flash_bank *bank, int set,
769                 unsigned int first, unsigned int last)
770 {
771         LOG_WARNING("kinetis_ke_protect not supported yet");
772         /* FIXME: TODO */
773
774         if (bank->target->state != TARGET_HALTED) {
775                 LOG_ERROR("Target not halted");
776                 return ERROR_TARGET_NOT_HALTED;
777         }
778
779         return ERROR_FLASH_BANK_INVALID;
780 }
781
782 static int kinetis_ke_protect_check(struct flash_bank *bank)
783 {
784         struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
785
786         if (bank->target->state != TARGET_HALTED) {
787                 LOG_ERROR("Target not halted");
788                 return ERROR_TARGET_NOT_HALTED;
789         }
790
791         int result;
792         uint8_t fprot;
793         uint8_t fpopen, fpldis, fphdis;
794         uint8_t fphs, fpls;
795         uint32_t lprot_size = 0, hprot_size = 0;
796         uint32_t lprot_to = 0, hprot_from = 0;
797
798         /* read protection register */
799         result = target_read_u8(bank->target, kinfo->ftmrx_fprot_addr, &fprot);
800
801         if (result != ERROR_OK)
802                 return result;
803
804         fpopen = fprot & 0x80;
805         fpldis = fprot & 0x04;
806         fphdis = fprot & 0x20;
807         fphs = (fprot >> 3) & 0x03;
808         fpls = fprot & 0x03;
809
810         /* Fully unprotected? */
811         if (fpopen && fpldis && fphdis) {
812                 LOG_WARNING("No flash protection found.");
813
814                 for (unsigned int i = 0; i < bank->num_sectors; i++)
815                         bank->sectors[i].is_protected = 0;
816
817                 kinfo->protection_size = 0;
818         } else {
819                 LOG_WARNING("Flash protected. FPOPEN=%i FPLDIS=%i FPHDIS=%i FPLS=%i FPHS=%i",
820                                         fpopen ? 1 : 0, fpldis ? 1 : 0, fphdis ? 1 : 0, fpls, fphs);
821
822                 /* Retrieve which region is protected and how much */
823                 if (fpopen) {
824                         if (fpldis == 0)
825                                 lprot_size = (kinfo->sector_size * 4) << fpls;
826
827                         if (fphdis == 0)
828                                 hprot_size = (kinfo->sector_size * 2) << fphs;
829                 } else {
830                         if (fpldis == 1)
831                                 lprot_size = (kinfo->sector_size * 4) << fpls;
832
833                         if (fphdis == 1)
834                                 hprot_size = (kinfo->sector_size * 2) << fphs;
835                 }
836
837                 kinfo->protection_size = lprot_size + hprot_size;
838
839                 /* lprot_to indicates up to where the lower region is protected */
840                 lprot_to = lprot_size / kinfo->sector_size;
841
842                 /* hprot_from indicates from where the upper region is protected */
843                 hprot_from = (0x8000 - hprot_size) / kinfo->sector_size;
844
845                 for (unsigned int i = 0; i < bank->num_sectors; i++) {
846
847                         /* Check if the sector is in the lower region */
848                         if (bank->sectors[i].offset < 0x4000) {
849                                 /* Compare the sector start address against lprot_to */
850                                 if (lprot_to && (i < lprot_to))
851                                         bank->sectors[i].is_protected = 1;
852                                 else
853                                         bank->sectors[i].is_protected = 0;
854
855                         /* Check if the sector is between the lower and upper region
856                          * OR after the upper region */
857                         } else if (bank->sectors[i].offset < 0x6000 || bank->sectors[i].offset >= 0x8000) {
858                                 /* If fpopen is 1 then these regions are protected */
859                                 if (fpopen)
860                                         bank->sectors[i].is_protected = 0;
861                                 else
862                                         bank->sectors[i].is_protected = 1;
863
864                         /* Check if the sector is in the upper region */
865                         } else if (bank->sectors[i].offset < 0x8000) {
866                                 if (hprot_from && (i > hprot_from))
867                                         bank->sectors[i].is_protected = 1;
868                                 else
869                                         bank->sectors[i].is_protected = 0;
870                         }
871                 }
872         }
873
874         return ERROR_OK;
875 }
876
877 static int kinetis_ke_ftmrx_command(struct flash_bank *bank, uint8_t count,
878                                                                         uint8_t *FCCOBIX, uint8_t *FCCOBHI, uint8_t *FCCOBLO, uint8_t *fstat)
879 {
880         uint8_t i;
881         int result;
882         struct target *target = bank->target;
883         struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
884         uint32_t timeout = 0;
885
886         /* Clear error flags */
887         result = target_write_u8(target, kinfo->ftmrx_fstat_addr, 0x30);
888         if (result != ERROR_OK)
889                 return result;
890
891         for (i = 0; i < count; i++)     {
892                 /* Write index */
893                 result = target_write_u8(target, kinfo->ftmrx_fccobix_addr, FCCOBIX[i]);
894                 if (result != ERROR_OK)
895                         return result;
896
897                 /* Write high part */
898                 result = target_write_u8(target, kinfo->ftmrx_fccobhi_addr, FCCOBHI[i]);
899                 if (result != ERROR_OK)
900                         return result;
901
902                 /* Write low part (that is not always required) */
903                 if (FCCOBLO) {
904                         result = target_write_u8(target, kinfo->ftmrx_fccoblo_addr, FCCOBLO[i]);
905                         if (result != ERROR_OK)
906                                 return result;
907                 }
908         }
909
910         /* Launch the command */
911         result = target_write_u8(target, kinfo->ftmrx_fstat_addr, 0x80);
912         if (result != ERROR_OK)
913                 return result;
914
915         /* Wait for it to finish */
916         result = target_read_u8(target, kinfo->ftmrx_fstat_addr, fstat);
917         if (result != ERROR_OK)
918                 return result;
919
920         while (!(*fstat & FTMRX_FSTAT_CCIF_MASK)) {
921                 if (timeout <= 1000) {
922                         timeout++;
923                         alive_sleep(1);
924                 } else {
925                         return ERROR_FLASH_OPERATION_FAILED;
926                 }
927
928                 result = target_read_u8(target, kinfo->ftmrx_fstat_addr, fstat);
929                 if (result != ERROR_OK)
930                         return result;
931         }
932
933         return ERROR_OK;
934 }
935
936 COMMAND_HANDLER(kinetis_ke_securing_test)
937 {
938         int result;
939         struct target *target = get_current_target(CMD_CTX);
940         struct flash_bank *bank = NULL;
941         uint32_t address;
942
943         uint8_t FCCOBIX[2], FCCOBHI[2], FCCOBLO[2], fstat;
944
945         result = get_flash_bank_by_addr(target, 0x00000000, true, &bank);
946         if (result != ERROR_OK)
947                 return result;
948
949         assert(bank);
950
951         if (target->state != TARGET_HALTED) {
952                 LOG_ERROR("Target not halted");
953                 return ERROR_TARGET_NOT_HALTED;
954         }
955
956         address = bank->base + 0x00000400;
957
958         FCCOBIX[0] = 0;
959         FCCOBHI[0] = FTMRX_CMD_ERASESECTOR;
960         FCCOBLO[0] = address >> 16;
961
962         FCCOBIX[1] = 1;
963         FCCOBHI[1] = address >> 8;
964         FCCOBLO[1] = address;
965
966         return kinetis_ke_ftmrx_command(bank, 2, FCCOBIX, FCCOBHI, FCCOBLO, &fstat);
967 }
968
969 static int kinetis_ke_erase(struct flash_bank *bank, unsigned int first,
970                 unsigned int last)
971 {
972         int result;
973         uint8_t FCCOBIX[2], FCCOBHI[2], FCCOBLO[2], fstat;
974         bool fcf_erased = false;
975
976         if (bank->target->state != TARGET_HALTED) {
977                 LOG_ERROR("Target not halted");
978                 return ERROR_TARGET_NOT_HALTED;
979         }
980
981         if ((first > bank->num_sectors) || (last > bank->num_sectors))
982                 return ERROR_FLASH_OPERATION_FAILED;
983
984         result = kinetis_ke_prepare_flash(bank);
985         if (result != ERROR_OK)
986                 return result;
987
988         for (unsigned int i = first; i <= last; i++) {
989                 FCCOBIX[0] = 0;
990                 FCCOBHI[0] = FTMRX_CMD_ERASESECTOR;
991                 FCCOBLO[0] = (bank->base + bank->sectors[i].offset) >> 16;
992
993                 FCCOBIX[1] = 1;
994                 FCCOBHI[1] = (bank->base + bank->sectors[i].offset) >> 8;
995                 FCCOBLO[1] = (bank->base + bank->sectors[i].offset);
996
997                 result = kinetis_ke_ftmrx_command(bank, 2, FCCOBIX, FCCOBHI, FCCOBLO, &fstat);
998
999                 if (result != ERROR_OK) {
1000                         LOG_WARNING("erase sector %u failed", i);
1001                         return ERROR_FLASH_OPERATION_FAILED;
1002                 }
1003
1004                 if (i == 2)
1005                         fcf_erased = true;
1006         }
1007
1008         if (fcf_erased) {
1009                 LOG_WARNING
1010                         ("flash configuration field erased, please reset the device");
1011         }
1012
1013         return ERROR_OK;
1014 }
1015
1016 static int kinetis_ke_write(struct flash_bank *bank, const uint8_t *buffer,
1017                          uint32_t offset, uint32_t count)
1018 {
1019         int result;
1020         uint8_t *new_buffer = NULL;
1021         uint32_t words = count / 4;
1022
1023         if (bank->target->state != TARGET_HALTED) {
1024                 LOG_ERROR("Target not halted");
1025                 return ERROR_TARGET_NOT_HALTED;
1026         }
1027
1028         if (offset > bank->size)
1029                 return ERROR_FLASH_BANK_INVALID;
1030
1031         if (offset & 0x3) {
1032                 LOG_WARNING("offset 0x%" PRIx32 " breaks the required alignment", offset);
1033                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
1034         }
1035
1036         result = kinetis_ke_stop_watchdog(bank->target);
1037         if (result != ERROR_OK)
1038                         return result;
1039
1040         result = kinetis_ke_prepare_flash(bank);
1041         if (result != ERROR_OK)
1042                 return result;
1043
1044         if (count & 0x3) {
1045                 uint32_t old_count = count;
1046                 count = (old_count | 3) + 1;
1047                 new_buffer = malloc(count);
1048                 if (!new_buffer) {
1049                         LOG_ERROR("odd number of bytes to write and no memory "
1050                                 "for padding buffer");
1051                         return ERROR_FAIL;
1052                 }
1053
1054                 LOG_INFO("odd number of bytes to write (%" PRIu32 "), extending to %" PRIu32 " "
1055                         "and padding with 0xff", old_count, count);
1056
1057                 memset(new_buffer, 0xff, count);
1058                 buffer = memcpy(new_buffer, buffer, old_count);
1059                 words++;
1060         }
1061
1062         result = kinetis_ke_write_words(bank, buffer, offset, words);
1063         free(new_buffer);
1064
1065         return result;
1066 }
1067
1068 static int kinetis_ke_probe(struct flash_bank *bank)
1069 {
1070         int result;
1071         uint32_t offset = 0;
1072         struct target *target = bank->target;
1073         struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
1074
1075         result = target_read_u32(target, SIM_SRSID, &kinfo->sim_srsid);
1076         if (result != ERROR_OK)
1077                 return result;
1078
1079         if (KINETIS_KE_SRSID_FAMID(kinfo->sim_srsid) != 0x00) {
1080                 LOG_ERROR("Unsupported KE family");
1081                 return ERROR_FLASH_OPER_UNSUPPORTED;
1082         }
1083
1084         switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
1085                 case KINETIS_KE_SRSID_KEX2:
1086                         LOG_INFO("KE02 sub-family");
1087                         break;
1088
1089                 case KINETIS_KE_SRSID_KEX4:
1090                         LOG_INFO("KE04 sub-family");
1091                         break;
1092
1093                 case KINETIS_KE_SRSID_KEX6:
1094                         LOG_INFO("KE06 sub-family");
1095                         break;
1096
1097                 default:
1098                         LOG_ERROR("Unsupported KE sub-family");
1099                         return ERROR_FLASH_OPER_UNSUPPORTED;
1100         }
1101
1102         /* We can only retrieve the ke0x part, but there is no way to know
1103          * the flash size, so assume the maximum flash size for the entire
1104          * sub family.
1105          */
1106         bank->base = 0x00000000;
1107         kinfo->sector_size = 512;
1108
1109         switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
1110
1111                 case KINETIS_KE_SRSID_KEX2:
1112                         /* Max. 64KB */
1113                         bank->size = 0x00010000;
1114                         bank->num_sectors = 128;
1115
1116                         /* KE02 uses the FTMRH flash controller,
1117                          * and registers have a different offset from the
1118                          * FTMRE flash controller. Sort this out here.
1119                          */
1120                         kinfo->ftmrx_fclkdiv_addr = 0x40020000;
1121                         kinfo->ftmrx_fccobix_addr = 0x40020002;
1122                         kinfo->ftmrx_fstat_addr = 0x40020006;
1123                         kinfo->ftmrx_fprot_addr = 0x40020008;
1124                         kinfo->ftmrx_fccobhi_addr = 0x4002000A;
1125                         kinfo->ftmrx_fccoblo_addr = 0x4002000B;
1126                         break;
1127
1128                 case KINETIS_KE_SRSID_KEX6:
1129                 case KINETIS_KE_SRSID_KEX4:
1130                         /* Max. 128KB */
1131                         bank->size = 0x00020000;
1132                         bank->num_sectors = 256;
1133
1134                         /* KE04 and KE06 use the FTMRE flash controller,
1135                          * and registers have a different offset from the
1136                          * FTMRH flash controller. Sort this out here.
1137                          */
1138                         kinfo->ftmrx_fclkdiv_addr = 0x40020003;
1139                         kinfo->ftmrx_fccobix_addr = 0x40020001;
1140                         kinfo->ftmrx_fstat_addr = 0x40020005;
1141                         kinfo->ftmrx_fprot_addr = 0x4002000B;
1142                         kinfo->ftmrx_fccobhi_addr = 0x40020009;
1143                         kinfo->ftmrx_fccoblo_addr = 0x40020008;
1144                         break;
1145         }
1146
1147         free(bank->sectors);
1148
1149         assert(bank->num_sectors > 0);
1150         bank->sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
1151
1152         for (unsigned int i = 0; i < bank->num_sectors; i++) {
1153                 bank->sectors[i].offset = offset;
1154                 bank->sectors[i].size = kinfo->sector_size;
1155                 offset += kinfo->sector_size;
1156                 bank->sectors[i].is_erased = -1;
1157                 bank->sectors[i].is_protected = 1;
1158         }
1159
1160         return ERROR_OK;
1161 }
1162
1163 static int kinetis_ke_auto_probe(struct flash_bank *bank)
1164 {
1165         struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
1166
1167         if (kinfo->sim_srsid)
1168                 return ERROR_OK;
1169
1170         return kinetis_ke_probe(bank);
1171 }
1172
1173 static int kinetis_ke_info(struct flash_bank *bank, struct command_invocation *cmd)
1174 {
1175         command_print_sameline(cmd, "%s driver for flash bank %s at " TARGET_ADDR_FMT,
1176                         bank->driver->name,     bank->name, bank->base);
1177
1178         return ERROR_OK;
1179 }
1180
1181 static int kinetis_ke_blank_check(struct flash_bank *bank)
1182 {
1183         uint8_t FCCOBIX[3], FCCOBHI[3], FCCOBLO[3], fstat;
1184         uint16_t longwords = 0;
1185         int result;
1186
1187         if (bank->target->state != TARGET_HALTED) {
1188                 LOG_ERROR("Target not halted");
1189                 return ERROR_TARGET_NOT_HALTED;
1190         }
1191
1192         result = kinetis_ke_prepare_flash(bank);
1193         if (result != ERROR_OK)
1194                 return result;
1195
1196         /* check if whole bank is blank */
1197         FCCOBIX[0] = 0;
1198         FCCOBHI[0] = FTMRX_CMD_ALLERASED;
1199
1200         result = kinetis_ke_ftmrx_command(bank, 1, FCCOBIX, FCCOBHI, NULL, &fstat);
1201
1202         if (result != ERROR_OK)
1203                 return result;
1204
1205         if (fstat & (FTMRX_FSTAT_MGSTAT0_MASK | FTMRX_FSTAT_MGSTAT1_MASK)) {
1206                 /* the whole bank is not erased, check sector-by-sector */
1207                 for (unsigned int i = 0; i < bank->num_sectors; i++) {
1208                         FCCOBIX[0] = 0;
1209                         FCCOBHI[0] = FTMRX_CMD_SECTIONERASED;
1210                         FCCOBLO[0] = (bank->base + bank->sectors[i].offset) >> 16;
1211
1212                         FCCOBIX[1] = 1;
1213                         FCCOBHI[1] = (bank->base + bank->sectors[i].offset) >> 8;
1214                         FCCOBLO[1] = (bank->base + bank->sectors[i].offset);
1215
1216                         longwords = 128;
1217
1218                         FCCOBIX[2] = 2;
1219                         FCCOBHI[2] = longwords >> 8;
1220                         FCCOBLO[2] = longwords;
1221
1222                         result = kinetis_ke_ftmrx_command(bank, 3, FCCOBIX, FCCOBHI, FCCOBLO, &fstat);
1223
1224                         if (result == ERROR_OK) {
1225                                 bank->sectors[i].is_erased = !(fstat & (FTMRX_FSTAT_MGSTAT0_MASK | FTMRX_FSTAT_MGSTAT1_MASK));
1226                         } else {
1227                                 LOG_DEBUG("Ignoring error on PFlash sector blank-check");
1228                                 bank->sectors[i].is_erased = -1;
1229                         }
1230                 }
1231         } else {
1232                 /* the whole bank is erased, update all sectors */
1233                 for (unsigned int i = 0; i < bank->num_sectors; i++)
1234                         bank->sectors[i].is_erased = 1;
1235         }
1236
1237         return ERROR_OK;
1238 }
1239
1240 static const struct command_registration kinetis_ke_security_command_handlers[] = {
1241         {
1242                 .name = "check_security",
1243                 .mode = COMMAND_EXEC,
1244                 .help = "Check status of device security lock",
1245                 .usage = "",
1246                 .handler = kinetis_ke_check_flash_security_status,
1247         },
1248         {
1249                 .name = "mass_erase",
1250                 .mode = COMMAND_EXEC,
1251                 .help = "Issue a complete flash erase via the MDM-AP",
1252                 .usage = "",
1253                 .handler = kinetis_ke_mdm_mass_erase,
1254         },
1255         {
1256                 .name = "test_securing",
1257                 .mode = COMMAND_EXEC,
1258                 .help = "",
1259                 .usage = "",
1260                 .handler = kinetis_ke_securing_test,
1261         },
1262         COMMAND_REGISTRATION_DONE
1263 };
1264
1265 static const struct command_registration kinetis_ke_exec_command_handlers[] = {
1266         {
1267                 .name = "mdm",
1268                 .mode = COMMAND_ANY,
1269                 .help = "MDM-AP command group",
1270                 .usage = "",
1271                 .chain = kinetis_ke_security_command_handlers,
1272         },
1273         {
1274                 .name = "disable_wdog",
1275                 .mode = COMMAND_EXEC,
1276                 .help = "Disable the watchdog timer",
1277                 .usage = "",
1278                 .handler = kinetis_ke_disable_wdog_handler,
1279         },
1280         COMMAND_REGISTRATION_DONE
1281 };
1282
1283 static const struct command_registration kinetis_ke_command_handler[] = {
1284         {
1285                 .name = "kinetis_ke",
1286                 .mode = COMMAND_ANY,
1287                 .help = "Kinetis KE flash controller commands",
1288                 .usage = "",
1289                 .chain = kinetis_ke_exec_command_handlers,
1290         },
1291         COMMAND_REGISTRATION_DONE
1292 };
1293
1294 const struct flash_driver kinetis_ke_flash = {
1295         .name = "kinetis_ke",
1296         .commands = kinetis_ke_command_handler,
1297         .flash_bank_command = kinetis_ke_flash_bank_command,
1298         .erase = kinetis_ke_erase,
1299         .protect = kinetis_ke_protect,
1300         .write = kinetis_ke_write,
1301         .read = default_flash_read,
1302         .probe = kinetis_ke_probe,
1303         .auto_probe = kinetis_ke_auto_probe,
1304         .erase_check = kinetis_ke_blank_check,
1305         .protect_check = kinetis_ke_protect_check,
1306         .info = kinetis_ke_info,
1307         .free_driver_priv = default_flash_free_driver_priv,
1308 };