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