Kinetis: suppress false alarms "MCU is secured"
[fw/openocd] / src / flash / nor / kinetis.c
1 /***************************************************************************
2  *   Copyright (C) 2011 by Mathias Kuester                                 *
3  *   kesmtp@freenet.de                                                     *
4  *                                                                         *
5  *   Copyright (C) 2011 sleep(5) ltd                                       *
6  *   tomas@sleepfive.com                                                   *
7  *                                                                         *
8  *   Copyright (C) 2012 by Christopher D. Kilgour                          *
9  *   techie at whiterocker.com                                             *
10  *                                                                         *
11  *   Copyright (C) 2013 Nemui Trinomius                                    *
12  *   nemuisan_kawausogasuki@live.jp                                        *
13  *                                                                         *
14  *   This program is free software; you can redistribute it and/or modify  *
15  *   it under the terms of the GNU General Public License as published by  *
16  *   the Free Software Foundation; either version 2 of the License, or     *
17  *   (at your option) any later version.                                   *
18  *                                                                         *
19  *   This program is distributed in the hope that it will be useful,       *
20  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
21  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
22  *   GNU General Public License for more details.                          *
23  *                                                                         *
24  *   You should have received a copy of the GNU General Public License     *
25  *   along with this program; if not, write to the                         *
26  *   Free Software Foundation, Inc.,                                       *
27  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
28  ***************************************************************************/
29
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
33
34 #include "jtag/interface.h"
35 #include "imp.h"
36 #include <helper/binarybuffer.h>
37 #include <target/target_type.h>
38 #include <target/algorithm.h>
39 #include <target/armv7m.h>
40 #include <target/cortex_m.h>
41
42 /*
43  * Implementation Notes
44  *
45  * The persistent memories in the Kinetis chip families K10 through
46  * K70 are all manipulated with the Flash Memory Module.  Some
47  * variants call this module the FTFE, others call it the FTFL.  To
48  * indicate that both are considered here, we use FTFX.
49  *
50  * Within the module, according to the chip variant, the persistent
51  * memory is divided into what Freescale terms Program Flash, FlexNVM,
52  * and FlexRAM.  All chip variants have Program Flash.  Some chip
53  * variants also have FlexNVM and FlexRAM, which always appear
54  * together.
55  *
56  * A given Kinetis chip may have 1, 2 or 4 blocks of flash.  Here we map
57  * each block to a separate bank.  Each block size varies by chip and
58  * may be determined by the read-only SIM_FCFG1 register.  The sector
59  * size within each bank/block varies by chip, and may be 1, 2 or 4k.
60  * The sector size may be different for flash and FlexNVM.
61  *
62  * The first half of the flash (1 or 2 blocks) is always Program Flash
63  * and always starts at address 0x00000000.  The "PFLSH" flag, bit 23
64  * of the read-only SIM_FCFG2 register, determines whether the second
65  * half of the flash is also Program Flash or FlexNVM+FlexRAM.  When
66  * PFLSH is set, the second from the first half.  When PFLSH is clear,
67  * the second half of flash is FlexNVM and always starts at address
68  * 0x10000000.  FlexRAM, which is also present when PFLSH is clear,
69  * always starts at address 0x14000000.
70  *
71  * The Flash Memory Module provides a register set where flash
72  * commands are loaded to perform flash operations like erase and
73  * program.  Different commands are available depending on whether
74  * Program Flash or FlexNVM/FlexRAM is being manipulated.  Although
75  * the commands used are quite consistent between flash blocks, the
76  * parameters they accept differ according to the flash sector size.
77  *
78  */
79
80 /* Addressess */
81 #define FLEXRAM         0x14000000
82 #define FTFx_FSTAT      0x40020000
83 #define FTFx_FCNFG      0x40020001
84 #define FTFx_FCCOB3     0x40020004
85 #define FTFx_FPROT3     0x40020010
86 #define SIM_SDID        0x40048024
87 #define SIM_SOPT1       0x40047000
88 #define SIM_FCFG1       0x4004804c
89 #define SIM_FCFG2       0x40048050
90 #define WDOG_STCTRH     0x40052000
91
92 /* Commands */
93 #define FTFx_CMD_BLOCKSTAT  0x00
94 #define FTFx_CMD_SECTSTAT   0x01
95 #define FTFx_CMD_LWORDPROG  0x06
96 #define FTFx_CMD_SECTERASE  0x09
97 #define FTFx_CMD_SECTWRITE  0x0b
98 #define FTFx_CMD_SETFLEXRAM 0x81
99 #define FTFx_CMD_MASSERASE  0x44
100
101 /* The older Kinetis K series uses the following SDID layout :
102  * Bit 31-16 : 0
103  * Bit 15-12 : REVID
104  * Bit 11-7  : DIEID
105  * Bit 6-4   : FAMID
106  * Bit 3-0   : PINID
107  *
108  * The newer Kinetis series uses the following SDID layout :
109  * Bit 31-28 : FAMID
110  * Bit 27-24 : SUBFAMID
111  * Bit 23-20 : SERIESID
112  * Bit 19-16 : SRAMSIZE
113  * Bit 15-12 : REVID
114  * Bit 6-4   : Reserved (0)
115  * Bit 3-0   : PINID
116  *
117  * We assume that if bits 31-16 are 0 then it's an older
118  * K-series MCU.
119  */
120
121 #define KINETIS_SOPT1_RAMSIZE_MASK  0x0000F000
122 #define KINETIS_SOPT1_RAMSIZE_K24FN1M 0x0000B000
123
124 #define KINETIS_SDID_K_SERIES_MASK  0x0000FFFF
125
126 #define KINETIS_SDID_DIEID_MASK 0x00000F80
127
128 #define KINETIS_SDID_DIEID_K22FN128     0x00000680 /* smaller pflash with FTFA */
129 #define KINETIS_SDID_DIEID_K22FN256     0x00000A80
130 #define KINETIS_SDID_DIEID_K22FN512     0x00000E80
131 #define KINETIS_SDID_DIEID_K24FN256     0x00000700
132
133 #define KINETIS_SDID_DIEID_K24FN1M      0x00000300 /* Detect Errata 7534 */
134
135 /* We can't rely solely on the FAMID field to determine the MCU
136  * type since some FAMID values identify multiple MCUs with
137  * different flash sector sizes (K20 and K22 for instance).
138  * Therefore we combine it with the DIEID bits which may possibly
139  * break if Freescale bumps the DIEID for a particular MCU. */
140 #define KINETIS_K_SDID_TYPE_MASK 0x00000FF0
141 #define KINETIS_K_SDID_K10_M50   0x00000000
142 #define KINETIS_K_SDID_K10_M72   0x00000080
143 #define KINETIS_K_SDID_K10_M100  0x00000100
144 #define KINETIS_K_SDID_K10_M120  0x00000180
145 #define KINETIS_K_SDID_K11               0x00000220
146 #define KINETIS_K_SDID_K12               0x00000200
147 #define KINETIS_K_SDID_K20_M50   0x00000010
148 #define KINETIS_K_SDID_K20_M72   0x00000090
149 #define KINETIS_K_SDID_K20_M100  0x00000110
150 #define KINETIS_K_SDID_K20_M120  0x00000190
151 #define KINETIS_K_SDID_K21_M50   0x00000230
152 #define KINETIS_K_SDID_K21_M120  0x00000330
153 #define KINETIS_K_SDID_K22_M50   0x00000210
154 #define KINETIS_K_SDID_K22_M120  0x00000310
155 #define KINETIS_K_SDID_K30_M72   0x000000A0
156 #define KINETIS_K_SDID_K30_M100  0x00000120
157 #define KINETIS_K_SDID_K40_M72   0x000000B0
158 #define KINETIS_K_SDID_K40_M100  0x00000130
159 #define KINETIS_K_SDID_K50_M72   0x000000E0
160 #define KINETIS_K_SDID_K51_M72   0x000000F0
161 #define KINETIS_K_SDID_K53               0x00000170
162 #define KINETIS_K_SDID_K60_M100  0x00000140
163 #define KINETIS_K_SDID_K60_M150  0x000001C0
164 #define KINETIS_K_SDID_K70_M150  0x000001D0
165
166 #define KINETIS_SDID_SERIESID_MASK 0x00F00000
167 #define KINETIS_SDID_SERIESID_K   0x00000000
168 #define KINETIS_SDID_SERIESID_KL   0x00100000
169 #define KINETIS_SDID_SERIESID_KW   0x00500000
170 #define KINETIS_SDID_SERIESID_KV   0x00600000
171
172 #define KINETIS_SDID_SUBFAMID_MASK  0x0F000000
173 #define KINETIS_SDID_SUBFAMID_KX0   0x00000000
174 #define KINETIS_SDID_SUBFAMID_KX1   0x01000000
175 #define KINETIS_SDID_SUBFAMID_KX2   0x02000000
176 #define KINETIS_SDID_SUBFAMID_KX3   0x03000000
177 #define KINETIS_SDID_SUBFAMID_KX4   0x04000000
178 #define KINETIS_SDID_SUBFAMID_KX5   0x05000000
179 #define KINETIS_SDID_SUBFAMID_KX6   0x06000000
180
181 #define KINETIS_SDID_FAMILYID_MASK  0xF0000000
182 #define KINETIS_SDID_FAMILYID_K0X   0x00000000
183 #define KINETIS_SDID_FAMILYID_K1X   0x10000000
184 #define KINETIS_SDID_FAMILYID_K2X   0x20000000
185 #define KINETIS_SDID_FAMILYID_K3X   0x30000000
186 #define KINETIS_SDID_FAMILYID_K4X   0x40000000
187 #define KINETIS_SDID_FAMILYID_K6X   0x60000000
188 #define KINETIS_SDID_FAMILYID_K7X   0x70000000
189
190 struct kinetis_flash_bank {
191         unsigned bank_ordinal;
192         uint32_t sector_size;
193         uint32_t max_flash_prog_size;
194         uint32_t protection_size;
195
196         uint32_t sim_sdid;
197         uint32_t sim_fcfg1;
198         uint32_t sim_fcfg2;
199
200         enum {
201                 FC_AUTO = 0,
202                 FC_PFLASH,
203                 FC_FLEX_NVM,
204                 FC_FLEX_RAM,
205         } flash_class;
206
207         enum {
208                 FS_PROGRAM_SECTOR = 1,
209                 FS_PROGRAM_LONGWORD = 2,
210                 FS_PROGRAM_PHRASE = 4, /* Unsupported */
211         } flash_support;
212 };
213
214 #define MDM_REG_STAT            0x00
215 #define MDM_REG_CTRL            0x04
216 #define MDM_REG_ID              0xfc
217
218 #define MDM_STAT_FMEACK         (1<<0)
219 #define MDM_STAT_FREADY         (1<<1)
220 #define MDM_STAT_SYSSEC         (1<<2)
221 #define MDM_STAT_SYSRES         (1<<3)
222 #define MDM_STAT_FMEEN          (1<<5)
223 #define MDM_STAT_BACKDOOREN     (1<<6)
224 #define MDM_STAT_LPEN           (1<<7)
225 #define MDM_STAT_VLPEN          (1<<8)
226 #define MDM_STAT_LLSMODEXIT     (1<<9)
227 #define MDM_STAT_VLLSXMODEXIT   (1<<10)
228 #define MDM_STAT_CORE_HALTED    (1<<16)
229 #define MDM_STAT_CORE_SLEEPDEEP (1<<17)
230 #define MDM_STAT_CORESLEEPING   (1<<18)
231
232 #define MEM_CTRL_FMEIP          (1<<0)
233 #define MEM_CTRL_DBG_DIS        (1<<1)
234 #define MEM_CTRL_DBG_REQ        (1<<2)
235 #define MEM_CTRL_SYS_RES_REQ    (1<<3)
236 #define MEM_CTRL_CORE_HOLD_RES  (1<<4)
237 #define MEM_CTRL_VLLSX_DBG_REQ  (1<<5)
238 #define MEM_CTRL_VLLSX_DBG_ACK  (1<<6)
239 #define MEM_CTRL_VLLSX_STAT_ACK (1<<7)
240
241 #define MDM_ACCESS_TIMEOUT      3000 /* iterations */
242
243 static int kinetis_mdm_write_register(struct adiv5_dap *dap, unsigned reg, uint32_t value)
244 {
245         int retval;
246         LOG_DEBUG("MDM_REG[0x%02x] <- %08" PRIX32, reg, value);
247
248         retval = dap_queue_ap_write(dap, reg, value);
249         if (retval != ERROR_OK) {
250                 LOG_DEBUG("MDM: failed to queue a write request");
251                 return retval;
252         }
253
254         retval = dap_run(dap);
255         if (retval != ERROR_OK) {
256                 LOG_DEBUG("MDM: dap_run failed");
257                 return retval;
258         }
259
260
261         return ERROR_OK;
262 }
263
264 static int kinetis_mdm_read_register(struct adiv5_dap *dap, unsigned reg, uint32_t *result)
265 {
266         int retval;
267         retval = dap_queue_ap_read(dap, reg, result);
268         if (retval != ERROR_OK) {
269                 LOG_DEBUG("MDM: failed to queue a read request");
270                 return retval;
271         }
272
273         retval = dap_run(dap);
274         if (retval != ERROR_OK) {
275                 LOG_DEBUG("MDM: dap_run failed");
276                 return retval;
277         }
278
279         LOG_DEBUG("MDM_REG[0x%02x]: %08" PRIX32, reg, *result);
280         return ERROR_OK;
281 }
282
283 static int kinetis_mdm_poll_register(struct adiv5_dap *dap, unsigned reg, uint32_t mask, uint32_t value)
284 {
285         uint32_t val;
286         int retval;
287         int timeout = MDM_ACCESS_TIMEOUT;
288
289         do {
290                 retval = kinetis_mdm_read_register(dap, reg, &val);
291                 if (retval != ERROR_OK || (val & mask) == value)
292                         return retval;
293
294                 alive_sleep(1);
295         } while (timeout--);
296
297         LOG_DEBUG("MDM: polling timed out");
298         return ERROR_FAIL;
299 }
300
301 /*
302  * This function implements the procedure to mass erase the flash via
303  * SWD/JTAG on Kinetis K and L series of devices as it is described in
304  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
305  * and L-series MCUs" Section 4.2.1
306  */
307 COMMAND_HANDLER(kinetis_mdm_mass_erase)
308 {
309         struct target *target = get_current_target(CMD_CTX);
310         struct cortex_m_common *cortex_m = target_to_cm(target);
311         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
312
313         if (!dap) {
314                 LOG_ERROR("Cannot perform mass erase with a high-level adapter");
315                 return ERROR_FAIL;
316         }
317
318         int retval;
319         const uint8_t original_ap = dap->ap_current;
320
321         /*
322          * ... Power on the processor, or if power has already been
323          * applied, assert the RESET pin to reset the processor. For
324          * devices that do not have a RESET pin, write the System
325          * Reset Request bit in the MDM-AP control register after
326          * establishing communication...
327          */
328
329         /* assert SRST */
330         if (jtag_get_reset_config() & RESET_HAS_SRST)
331                 adapter_assert_reset();
332         else
333                 LOG_WARNING("Attempting mass erase without hardware reset. This is not reliable; "
334                             "it's recommended you connect SRST and use ``reset_config srst_only''.");
335
336         dap_ap_select(dap, 1);
337
338         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, MEM_CTRL_SYS_RES_REQ);
339         if (retval != ERROR_OK)
340                 return retval;
341
342         /*
343          * ... Read the MDM-AP status register until the Flash Ready bit sets...
344          */
345         retval = kinetis_mdm_poll_register(dap, MDM_REG_STAT,
346                                            MDM_STAT_FREADY | MDM_STAT_SYSRES,
347                                            MDM_STAT_FREADY);
348         if (retval != ERROR_OK) {
349                 LOG_ERROR("MDM : flash ready timeout");
350                 return retval;
351         }
352
353         /*
354          * ... Write the MDM-AP control register to set the Flash Mass
355          * Erase in Progress bit. This will start the mass erase
356          * process...
357          */
358         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL,
359                                             MEM_CTRL_SYS_RES_REQ | MEM_CTRL_FMEIP);
360         if (retval != ERROR_OK)
361                 return retval;
362
363         /* As a sanity check make sure that device started mass erase procedure */
364         retval = kinetis_mdm_poll_register(dap, MDM_REG_STAT,
365                                            MDM_STAT_FMEACK, MDM_STAT_FMEACK);
366         if (retval != ERROR_OK)
367                 return retval;
368
369         /*
370          * ... Read the MDM-AP control register until the Flash Mass
371          * Erase in Progress bit clears...
372          */
373         retval = kinetis_mdm_poll_register(dap, MDM_REG_CTRL,
374                                            MEM_CTRL_FMEIP,
375                                            0);
376         if (retval != ERROR_OK)
377                 return retval;
378
379         /*
380          * ... Negate the RESET signal or clear the System Reset Request
381          * bit in the MDM-AP control register...
382          */
383         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
384         if (retval != ERROR_OK)
385                 return retval;
386
387         dap_ap_select(dap, original_ap);
388
389         if (jtag_get_reset_config() & RESET_HAS_SRST) {
390                 /* halt MCU otherwise it loops in hard fault - WDOG reset cycle */
391                 target->reset_halt = true;
392                 target->type->assert_reset(target);
393                 target->type->deassert_reset(target);
394         }
395
396         return ERROR_OK;
397 }
398
399 static const uint32_t kinetis_known_mdm_ids[] = {
400         0x001C0000,     /* Kinetis-K Series */
401         0x001C0020,     /* Kinetis-L/M/V/E Series */
402 };
403
404 /*
405  * This function implements the procedure to connect to
406  * SWD/JTAG on Kinetis K and L series of devices as it is described in
407  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
408  * and L-series MCUs" Section 4.1.1
409  */
410 COMMAND_HANDLER(kinetis_check_flash_security_status)
411 {
412         struct target *target = get_current_target(CMD_CTX);
413         struct cortex_m_common *cortex_m = target_to_cm(target);
414         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
415
416         if (!dap) {
417                 LOG_WARNING("Cannot check flash security status with a high-level adapter");
418                 return ERROR_OK;
419         }
420
421         uint32_t val;
422         int retval;
423         const uint8_t origninal_ap = dap->ap_current;
424
425         dap_ap_select(dap, 1);
426
427
428         /*
429          * ... The MDM-AP ID register can be read to verify that the
430          * connection is working correctly...
431          */
432         retval = kinetis_mdm_read_register(dap, MDM_REG_ID, &val);
433         if (retval != ERROR_OK) {
434                 LOG_ERROR("MDM: failed to read ID register");
435                 goto fail;
436         }
437
438         bool found = false;
439         for (size_t i = 0; i < ARRAY_SIZE(kinetis_known_mdm_ids); i++) {
440                 if (val == kinetis_known_mdm_ids[i]) {
441                         found = true;
442                         break;
443                 }
444         }
445
446         if (!found)
447                 LOG_WARNING("MDM: unknown ID %08" PRIX32, val);
448
449         /*
450          * ... Read the MDM-AP status register until the Flash Ready bit sets...
451          */
452         retval = kinetis_mdm_poll_register(dap, MDM_REG_STAT,
453                                            MDM_STAT_FREADY,
454                                            MDM_STAT_FREADY);
455         if (retval != ERROR_OK) {
456                 LOG_ERROR("MDM: flash ready timeout");
457                 goto fail;
458         }
459
460         /*
461          * ... Read the System Security bit to determine if security is enabled.
462          * If System Security = 0, then proceed. If System Security = 1, then
463          * communication with the internals of the processor, including the
464          * flash, will not be possible without issuing a mass erase command or
465          * unsecuring the part through other means (backdoor key unlock)...
466          */
467         retval = kinetis_mdm_read_register(dap, MDM_REG_STAT, &val);
468         if (retval != ERROR_OK) {
469                 LOG_ERROR("MDM: failed to read MDM_REG_STAT");
470                 goto fail;
471         }
472
473         if ((val & (MDM_STAT_SYSSEC | MDM_STAT_CORE_HALTED)) == MDM_STAT_SYSSEC) {
474                 LOG_WARNING("MDM: Secured MCU state detected however it may be a false alarm");
475                 LOG_WARNING("MDM: Halting target to detect secured state reliably");
476
477                 dap_ap_select(dap, origninal_ap);
478                 retval = target_halt(target);
479                 if (retval == ERROR_OK)
480                         retval = target_wait_state(target, TARGET_HALTED, 100);
481
482                 if (retval != ERROR_OK) {
483                         LOG_WARNING("MDM: Target not halted, trying reset halt");
484                         target->reset_halt = true;
485                         target->type->assert_reset(target);
486                         target->type->deassert_reset(target);
487                 }
488
489                 /* re-read status */
490                 dap_ap_select(dap, 1);
491                 retval = kinetis_mdm_read_register(dap, MDM_REG_STAT, &val);
492                 if (retval != ERROR_OK) {
493                         LOG_ERROR("MDM: failed to read MDM_REG_STAT");
494                         goto fail;
495                 }
496         }
497
498         if (val & MDM_STAT_SYSSEC) {
499                 jtag_poll_set_enabled(false);
500
501                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
502                 LOG_WARNING("****                                                          ****");
503                 LOG_WARNING("**** Your Kinetis MCU is in secured state, which means that,  ****");
504                 LOG_WARNING("**** with exception for very basic communication, JTAG/SWD    ****");
505                 LOG_WARNING("**** interface will NOT work. In order to restore its         ****");
506                 LOG_WARNING("**** functionality please issue 'kinetis mdm mass_erase'      ****");
507                 LOG_WARNING("**** command, power cycle the MCU and restart OpenOCD.        ****");
508                 LOG_WARNING("****                                                          ****");
509                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
510         } else {
511                 LOG_INFO("MDM: Chip is unsecured. Continuing.");
512                 jtag_poll_set_enabled(true);
513         }
514
515         dap_ap_select(dap, origninal_ap);
516
517         return ERROR_OK;
518
519 fail:
520         LOG_ERROR("MDM: Failed to check security status of the MCU. Cannot proceed further");
521         jtag_poll_set_enabled(false);
522         return retval;
523 }
524
525 FLASH_BANK_COMMAND_HANDLER(kinetis_flash_bank_command)
526 {
527         struct kinetis_flash_bank *bank_info;
528
529         if (CMD_ARGC < 6)
530                 return ERROR_COMMAND_SYNTAX_ERROR;
531
532         LOG_INFO("add flash_bank kinetis %s", bank->name);
533
534         bank_info = malloc(sizeof(struct kinetis_flash_bank));
535
536         memset(bank_info, 0, sizeof(struct kinetis_flash_bank));
537
538         bank->driver_priv = bank_info;
539
540         return ERROR_OK;
541 }
542
543 /* Disable the watchdog on Kinetis devices */
544 int kinetis_disable_wdog(struct target *target, uint32_t sim_sdid)
545 {
546         struct working_area *wdog_algorithm;
547         struct armv7m_algorithm armv7m_info;
548         uint16_t wdog;
549         int retval;
550
551         static const uint8_t kinetis_unlock_wdog_code[] = {
552                 /* WDOG_UNLOCK = 0xC520 */
553                 0x4f, 0xf4, 0x00, 0x53,    /* mov.w   r3, #8192     ; 0x2000  */
554                 0xc4, 0xf2, 0x05, 0x03,    /* movt    r3, #16389    ; 0x4005  */
555                 0x4c, 0xf2, 0x20, 0x52,   /* movw    r2, #50464    ; 0xc520  */
556                 0xda, 0x81,               /* strh    r2, [r3, #14]  */
557
558                 /* WDOG_UNLOCK = 0xD928 */
559                 0x4f, 0xf4, 0x00, 0x53,   /* mov.w   r3, #8192     ; 0x2000  */
560                 0xc4, 0xf2, 0x05, 0x03,   /* movt    r3, #16389    ; 0x4005  */
561                 0x4d, 0xf6, 0x28, 0x12,   /* movw    r2, #55592    ; 0xd928  */
562                 0xda, 0x81,               /* strh    r2, [r3, #14]  */
563
564                 /* WDOG_SCR = 0x1d2 */
565                 0x4f, 0xf4, 0x00, 0x53,   /* mov.w   r3, #8192     ; 0x2000  */
566                 0xc4, 0xf2, 0x05, 0x03,   /* movt    r3, #16389    ; 0x4005  */
567                 0x4f, 0xf4, 0xe9, 0x72,   /* mov.w   r2, #466      ; 0x1d2  */
568                 0x1a, 0x80,               /* strh    r2, [r3, #0]  */
569
570                 /* END */
571                 0x00, 0xBE,               /* bkpt #0 */
572         };
573
574         /* Decide whether the connected device needs watchdog disabling.
575          * Disable for all Kx devices, i.e., return if it is a KLx */
576
577         if ((sim_sdid & KINETIS_SDID_SERIESID_MASK) == KINETIS_SDID_SERIESID_KL)
578                 return ERROR_OK;
579
580         /* The connected device requires watchdog disabling. */
581         retval = target_read_u16(target, WDOG_STCTRH, &wdog);
582         if (retval != ERROR_OK)
583                 return retval;
584
585         if ((wdog & 0x1) == 0) {
586                 /* watchdog already disabled */
587                 return ERROR_OK;
588         }
589         LOG_INFO("Disabling Kinetis watchdog (initial WDOG_STCTRLH = 0x%x)", wdog);
590
591         if (target->state != TARGET_HALTED) {
592                 LOG_ERROR("Target not halted");
593                 return ERROR_TARGET_NOT_HALTED;
594         }
595
596         retval = target_alloc_working_area(target, sizeof(kinetis_unlock_wdog_code), &wdog_algorithm);
597         if (retval != ERROR_OK)
598                 return retval;
599
600         retval = target_write_buffer(target, wdog_algorithm->address,
601                         sizeof(kinetis_unlock_wdog_code), (uint8_t *)kinetis_unlock_wdog_code);
602         if (retval != ERROR_OK) {
603                 target_free_working_area(target, wdog_algorithm);
604                 return retval;
605         }
606
607         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
608         armv7m_info.core_mode = ARM_MODE_THREAD;
609
610         retval = target_run_algorithm(target, 0, NULL, 0, NULL, wdog_algorithm->address,
611                         wdog_algorithm->address + (sizeof(kinetis_unlock_wdog_code) - 2),
612                         10000, &armv7m_info);
613
614         if (retval != ERROR_OK)
615                 LOG_ERROR("error executing kinetis wdog unlock algorithm");
616
617         retval = target_read_u16(target, WDOG_STCTRH, &wdog);
618         if (retval != ERROR_OK)
619                 return retval;
620         LOG_INFO("WDOG_STCTRLH = 0x%x", wdog);
621
622         target_free_working_area(target, wdog_algorithm);
623
624         return retval;
625 }
626
627 COMMAND_HANDLER(kinetis_disable_wdog_handler)
628 {
629         int result;
630         uint32_t sim_sdid;
631         struct target *target = get_current_target(CMD_CTX);
632
633         if (CMD_ARGC > 0)
634                 return ERROR_COMMAND_SYNTAX_ERROR;
635
636         result = target_read_u32(target, SIM_SDID, &sim_sdid);
637         if (result != ERROR_OK) {
638                 LOG_ERROR("Failed to read SIMSDID");
639                 return result;
640         }
641
642         result = kinetis_disable_wdog(target, sim_sdid);
643         return result;
644 }
645
646
647 /* Kinetis Program-LongWord Microcodes */
648 static const uint8_t kinetis_flash_write_code[] = {
649         /* Params:
650          * r0 - workarea buffer
651         * r1 - target address
652         * r2 - wordcount
653         * Clobbered:
654         * r4 - tmp
655         * r5 - tmp
656         * r6 - tmp
657         * r7 - tmp
658         */
659
660                                                         /* .L1: */
661                                                 /* for(register uint32_t i=0;i<wcount;i++){ */
662         0x04, 0x1C,                                     /* mov    r4, r0          */
663         0x00, 0x23,                                     /* mov    r3, #0          */
664                                                         /* .L2: */
665         0x0E, 0x1A,                                     /* sub    r6, r1, r0      */
666         0xA6, 0x19,                                     /* add    r6, r4, r6      */
667         0x93, 0x42,                                     /* cmp    r3, r2          */
668         0x16, 0xD0,                                     /* beq    .L9             */
669                                                         /* .L5: */
670                                                 /* while((FTFx_FSTAT&FTFA_FSTAT_CCIF_MASK) != FTFA_FSTAT_CCIF_MASK){}; */
671         0x0B, 0x4D,                                     /* ldr    r5, .L10        */
672         0x2F, 0x78,                                     /* ldrb   r7, [r5]        */
673         0x7F, 0xB2,                                     /* sxtb   r7, r7          */
674         0x00, 0x2F,                                     /* cmp    r7, #0          */
675         0xFA, 0xDA,                                     /* bge    .L5             */
676                                                 /* FTFx_FSTAT = FTFA_FSTAT_ACCERR_MASK|FTFA_FSTAT_FPVIOL_MASK|FTFA_FSTAT_RDCO */
677         0x70, 0x27,                                     /* mov    r7, #112        */
678         0x2F, 0x70,                                     /* strb   r7, [r5]        */
679                                                 /* FTFx_FCCOB3 = faddr; */
680         0x09, 0x4F,                                     /* ldr    r7, .L10+4      */
681         0x3E, 0x60,                                     /* str    r6, [r7]        */
682         0x06, 0x27,                                     /* mov    r7, #6          */
683                                                 /* FTFx_FCCOB0 = 0x06;  */
684         0x08, 0x4E,                                     /* ldr    r6, .L10+8      */
685         0x37, 0x70,                                     /* strb   r7, [r6]        */
686                                                 /* FTFx_FCCOB7 = *pLW;  */
687         0x80, 0xCC,                                     /* ldmia  r4!, {r7}       */
688         0x08, 0x4E,                                     /* ldr    r6, .L10+12     */
689         0x37, 0x60,                                     /* str    r7, [r6]        */
690                                                 /* FTFx_FSTAT = FTFA_FSTAT_CCIF_MASK; */
691         0x80, 0x27,                                     /* mov    r7, #128        */
692         0x2F, 0x70,                                     /* strb   r7, [r5]        */
693                                                         /* .L4: */
694                                                 /* while((FTFx_FSTAT&FTFA_FSTAT_CCIF_MASK) != FTFA_FSTAT_CCIF_MASK){}; */
695         0x2E, 0x78,                                     /* ldrb    r6, [r5]       */
696         0x77, 0xB2,                                     /* sxtb    r7, r6         */
697         0x00, 0x2F,                                     /* cmp     r7, #0         */
698         0xFB, 0xDA,                                     /* bge     .L4            */
699         0x01, 0x33,                                     /* add     r3, r3, #1     */
700         0xE4, 0xE7,                                     /* b       .L2            */
701                                                         /* .L9: */
702         0x00, 0xBE,                                     /* bkpt #0                */
703                                                         /* .L10: */
704         0x00, 0x00, 0x02, 0x40,         /* .word    1073872896    */
705         0x04, 0x00, 0x02, 0x40,         /* .word    1073872900    */
706         0x07, 0x00, 0x02, 0x40,         /* .word    1073872903    */
707         0x08, 0x00, 0x02, 0x40,         /* .word    1073872904    */
708 };
709
710 /* Program LongWord Block Write */
711 static int kinetis_write_block(struct flash_bank *bank, const uint8_t *buffer,
712                 uint32_t offset, uint32_t wcount)
713 {
714         struct target *target = bank->target;
715         uint32_t buffer_size = 2048;            /* Default minimum value */
716         struct working_area *write_algorithm;
717         struct working_area *source;
718         uint32_t address = bank->base + offset;
719         struct reg_param reg_params[3];
720         struct armv7m_algorithm armv7m_info;
721         int retval = ERROR_OK;
722
723         /* Params:
724          * r0 - workarea buffer
725          * r1 - target address
726          * r2 - wordcount
727          * Clobbered:
728          * r4 - tmp
729          * r5 - tmp
730          * r6 - tmp
731          * r7 - tmp
732          */
733
734         /* Increase buffer_size if needed */
735         if (buffer_size < (target->working_area_size/2))
736                 buffer_size = (target->working_area_size/2);
737
738         LOG_INFO("Kinetis: FLASH Write ...");
739
740         /* check code alignment */
741         if (offset & 0x1) {
742                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
743                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
744         }
745
746         /* allocate working area with flash programming code */
747         if (target_alloc_working_area(target, sizeof(kinetis_flash_write_code),
748                         &write_algorithm) != ERROR_OK) {
749                 LOG_WARNING("no working area available, can't do block memory writes");
750                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
751         }
752
753         retval = target_write_buffer(target, write_algorithm->address,
754                 sizeof(kinetis_flash_write_code), kinetis_flash_write_code);
755         if (retval != ERROR_OK)
756                 return retval;
757
758         /* memory buffer */
759         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK) {
760                 buffer_size /= 4;
761                 if (buffer_size <= 256) {
762                         /* free working area, write algorithm already allocated */
763                         target_free_working_area(target, write_algorithm);
764
765                         LOG_WARNING("No large enough working area available, can't do block memory writes");
766                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
767                 }
768         }
769
770         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
771         armv7m_info.core_mode = ARM_MODE_THREAD;
772
773         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT); /* *pLW (*buffer) */
774         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT); /* faddr */
775         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT); /* number of words to program */
776
777         /* write code buffer and use Flash programming code within kinetis       */
778         /* Set breakpoint to 0 with time-out of 1000 ms                          */
779         while (wcount > 0) {
780                 uint32_t thisrun_count = (wcount > (buffer_size / 4)) ? (buffer_size / 4) : wcount;
781
782                 retval = target_write_buffer(target, source->address, thisrun_count * 4, buffer);
783                 if (retval != ERROR_OK)
784                         break;
785
786                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
787                 buf_set_u32(reg_params[1].value, 0, 32, address);
788                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count);
789
790                 retval = target_run_algorithm(target, 0, NULL, 3, reg_params,
791                                 write_algorithm->address, 0, 100000, &armv7m_info);
792                 if (retval != ERROR_OK) {
793                         LOG_ERROR("Error executing kinetis Flash programming algorithm");
794                         retval = ERROR_FLASH_OPERATION_FAILED;
795                         break;
796                 }
797
798                 buffer += thisrun_count * 4;
799                 address += thisrun_count * 4;
800                 wcount -= thisrun_count;
801         }
802
803         target_free_working_area(target, source);
804         target_free_working_area(target, write_algorithm);
805
806         destroy_reg_param(&reg_params[0]);
807         destroy_reg_param(&reg_params[1]);
808         destroy_reg_param(&reg_params[2]);
809
810         return retval;
811 }
812
813 static int kinetis_protect(struct flash_bank *bank, int set, int first, int last)
814 {
815         LOG_WARNING("kinetis_protect not supported yet");
816         /* FIXME: TODO */
817
818         if (bank->target->state != TARGET_HALTED) {
819                 LOG_ERROR("Target not halted");
820                 return ERROR_TARGET_NOT_HALTED;
821         }
822
823         return ERROR_FLASH_BANK_INVALID;
824 }
825
826 static int kinetis_protect_check(struct flash_bank *bank)
827 {
828         struct kinetis_flash_bank *kinfo = bank->driver_priv;
829
830         if (bank->target->state != TARGET_HALTED) {
831                 LOG_ERROR("Target not halted");
832                 return ERROR_TARGET_NOT_HALTED;
833         }
834
835         if (kinfo->flash_class == FC_PFLASH) {
836                 int result;
837                 uint8_t buffer[4];
838                 uint32_t fprot, psec;
839                 int i, b;
840
841                 /* read protection register */
842                 result = target_read_memory(bank->target, FTFx_FPROT3, 1, 4, buffer);
843
844                 if (result != ERROR_OK)
845                         return result;
846
847                 fprot = target_buffer_get_u32(bank->target, buffer);
848
849                 /*
850                  * Every bit protects 1/32 of the full flash (not necessarily
851                  * just this bank), but we enforce the bank ordinals for
852                  * PFlash to start at zero.
853                  */
854                 b = kinfo->bank_ordinal * (bank->size / kinfo->protection_size);
855                 for (psec = 0, i = 0; i < bank->num_sectors; i++) {
856                         if ((fprot >> b) & 1)
857                                 bank->sectors[i].is_protected = 0;
858                         else
859                                 bank->sectors[i].is_protected = 1;
860
861                         psec += bank->sectors[i].size;
862
863                         if (psec >= kinfo->protection_size) {
864                                 psec = 0;
865                                 b++;
866                         }
867                 }
868         } else {
869                 LOG_ERROR("Protection checks for FlexNVM not yet supported");
870                 return ERROR_FLASH_BANK_INVALID;
871         }
872
873         return ERROR_OK;
874 }
875
876 static int kinetis_ftfx_command(struct flash_bank *bank, uint8_t fcmd, uint32_t faddr,
877                                 uint8_t fccob4, uint8_t fccob5, uint8_t fccob6, uint8_t fccob7,
878                                 uint8_t fccob8, uint8_t fccob9, uint8_t fccoba, uint8_t fccobb,
879                                 uint8_t *ftfx_fstat)
880 {
881         uint8_t command[12] = {faddr & 0xff, (faddr >> 8) & 0xff, (faddr >> 16) & 0xff, fcmd,
882                         fccob7, fccob6, fccob5, fccob4,
883                         fccobb, fccoba, fccob9, fccob8};
884         int result, i;
885         uint8_t buffer;
886
887         /* wait for done */
888         for (i = 0; i < 50; i++) {
889                 result =
890                         target_read_memory(bank->target, FTFx_FSTAT, 1, 1, &buffer);
891
892                 if (result != ERROR_OK)
893                         return result;
894
895                 if (buffer & 0x80)
896                         break;
897
898                 buffer = 0x00;
899         }
900
901         if (buffer != 0x80) {
902                 /* reset error flags */
903                 buffer = 0x30;
904                 result =
905                         target_write_memory(bank->target, FTFx_FSTAT, 1, 1, &buffer);
906                 if (result != ERROR_OK)
907                         return result;
908         }
909
910         result = target_write_memory(bank->target, FTFx_FCCOB3, 4, 3, command);
911
912         if (result != ERROR_OK)
913                 return result;
914
915         /* start command */
916         buffer = 0x80;
917         result = target_write_memory(bank->target, FTFx_FSTAT, 1, 1, &buffer);
918         if (result != ERROR_OK)
919                 return result;
920
921         /* wait for done */
922         for (i = 0; i < 240; i++) { /* Need longtime for "Mass Erase" Command Nemui Changed */
923                 result =
924                         target_read_memory(bank->target, FTFx_FSTAT, 1, 1, ftfx_fstat);
925
926                 if (result != ERROR_OK)
927                         return result;
928
929                 if (*ftfx_fstat & 0x80)
930                         break;
931         }
932
933         if ((*ftfx_fstat & 0xf0) != 0x80) {
934                 LOG_ERROR
935                         ("ftfx command failed FSTAT: %02X FCCOB: %02X%02X%02X%02X %02X%02X%02X%02X %02X%02X%02X%02X",
936                          *ftfx_fstat, command[3], command[2], command[1], command[0],
937                          command[7], command[6], command[5], command[4],
938                          command[11], command[10], command[9], command[8]);
939                 return ERROR_FLASH_OPERATION_FAILED;
940         }
941
942         return ERROR_OK;
943 }
944
945 COMMAND_HANDLER(kinetis_securing_test)
946 {
947         int result;
948         uint8_t ftfx_fstat;
949         struct target *target = get_current_target(CMD_CTX);
950         struct flash_bank *bank = NULL;
951
952         result = get_flash_bank_by_addr(target, 0x00000000, true, &bank);
953         if (result != ERROR_OK)
954                 return result;
955
956         assert(bank != NULL);
957
958         if (target->state != TARGET_HALTED) {
959                 LOG_ERROR("Target not halted");
960                 return ERROR_TARGET_NOT_HALTED;
961         }
962
963         return kinetis_ftfx_command(bank, FTFx_CMD_SECTERASE, bank->base + 0x00000400,
964                                       0, 0, 0, 0,  0, 0, 0, 0,  &ftfx_fstat);
965 }
966
967 static int kinetis_erase(struct flash_bank *bank, int first, int last)
968 {
969         int result, i;
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         /*
980          * FIXME: TODO: use the 'Erase Flash Block' command if the
981          * requested erase is PFlash or NVM and encompasses the entire
982          * block.  Should be quicker.
983          */
984         for (i = first; i <= last; i++) {
985                 uint8_t ftfx_fstat;
986                 /* set command and sector address */
987                 result = kinetis_ftfx_command(bank, FTFx_CMD_SECTERASE, bank->base + bank->sectors[i].offset,
988                                 0, 0, 0, 0,  0, 0, 0, 0,  &ftfx_fstat);
989
990                 if (result != ERROR_OK) {
991                         LOG_WARNING("erase sector %d failed", i);
992                         return ERROR_FLASH_OPERATION_FAILED;
993                 }
994
995                 bank->sectors[i].is_erased = 1;
996         }
997
998         if (first == 0) {
999                 LOG_WARNING
1000                         ("flash configuration field erased, please reset the device");
1001         }
1002
1003         return ERROR_OK;
1004 }
1005
1006 static int kinetis_write(struct flash_bank *bank, const uint8_t *buffer,
1007                          uint32_t offset, uint32_t count)
1008 {
1009         unsigned int i, result, fallback = 0;
1010         uint8_t buf[8];
1011         uint32_t wc;
1012         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1013         uint8_t *new_buffer = NULL;
1014
1015         if (bank->target->state != TARGET_HALTED) {
1016                 LOG_ERROR("Target not halted");
1017                 return ERROR_TARGET_NOT_HALTED;
1018         }
1019
1020         if (!(kinfo->flash_support & FS_PROGRAM_SECTOR)) {
1021                 /* fallback to longword write */
1022                 fallback = 1;
1023                 LOG_WARNING("This device supports Program Longword execution only.");
1024                 LOG_DEBUG("flash write into PFLASH @08%" PRIX32, offset);
1025
1026         } else if (kinfo->flash_class == FC_FLEX_NVM) {
1027                 uint8_t ftfx_fstat;
1028
1029                 LOG_DEBUG("flash write into FlexNVM @%08" PRIX32, offset);
1030
1031                 /* make flex ram available */
1032                 result = kinetis_ftfx_command(bank, FTFx_CMD_SETFLEXRAM, 0x00ff0000, 0, 0, 0, 0,  0, 0, 0, 0,  &ftfx_fstat);
1033
1034                 if (result != ERROR_OK)
1035                         return ERROR_FLASH_OPERATION_FAILED;
1036
1037                 /* check if ram ready */
1038                 result = target_read_memory(bank->target, FTFx_FCNFG, 1, 1, buf);
1039
1040                 if (result != ERROR_OK)
1041                         return result;
1042
1043                 if (!(buf[0] & (1 << 1))) {
1044                         /* fallback to longword write */
1045                         fallback = 1;
1046
1047                         LOG_WARNING("ram not ready, fallback to slow longword write (FCNFG: %02X)", buf[0]);
1048                 }
1049         } else {
1050                 LOG_DEBUG("flash write into PFLASH @08%" PRIX32, offset);
1051         }
1052
1053
1054         /* program section command */
1055         if (fallback == 0) {
1056                 /*
1057                  * Kinetis uses different terms for the granularity of
1058                  * sector writes, e.g. "phrase" or "128 bits".  We use
1059                  * the generic term "chunk". The largest possible
1060                  * Kinetis "chunk" is 16 bytes (128 bits).
1061                  */
1062                 unsigned prog_section_chunk_bytes = kinfo->sector_size >> 8;
1063                 unsigned prog_size_bytes = kinfo->max_flash_prog_size;
1064                 for (i = 0; i < count; i += prog_size_bytes) {
1065                         uint8_t residual_buffer[16];
1066                         uint8_t ftfx_fstat;
1067                         uint32_t section_count = prog_size_bytes / prog_section_chunk_bytes;
1068                         uint32_t residual_wc = 0;
1069
1070                         /*
1071                          * Assume the word count covers an entire
1072                          * sector.
1073                          */
1074                         wc = prog_size_bytes / 4;
1075
1076                         /*
1077                          * If bytes to be programmed are less than the
1078                          * full sector, then determine the number of
1079                          * full-words to program, and put together the
1080                          * residual buffer so that a full "section"
1081                          * may always be programmed.
1082                          */
1083                         if ((count - i) < prog_size_bytes) {
1084                                 /* number of bytes to program beyond full section */
1085                                 unsigned residual_bc = (count-i) % prog_section_chunk_bytes;
1086
1087                                 /* number of complete words to copy directly from buffer */
1088                                 wc = (count - i - residual_bc) / 4;
1089
1090                                 /* number of total sections to write, including residual */
1091                                 section_count = DIV_ROUND_UP((count-i), prog_section_chunk_bytes);
1092
1093                                 /* any residual bytes delivers a whole residual section */
1094                                 residual_wc = (residual_bc ? prog_section_chunk_bytes : 0)/4;
1095
1096                                 /* clear residual buffer then populate residual bytes */
1097                                 (void) memset(residual_buffer, 0xff, prog_section_chunk_bytes);
1098                                 (void) memcpy(residual_buffer, &buffer[i+4*wc], residual_bc);
1099                         }
1100
1101                         LOG_DEBUG("write section @ %08" PRIX32 " with length %" PRIu32 " bytes",
1102                                   offset + i, (uint32_t)wc*4);
1103
1104                         /* write data to flexram as whole-words */
1105                         result = target_write_memory(bank->target, FLEXRAM, 4, wc,
1106                                         buffer + i);
1107
1108                         if (result != ERROR_OK) {
1109                                 LOG_ERROR("target_write_memory failed");
1110                                 return result;
1111                         }
1112
1113                         /* write the residual words to the flexram */
1114                         if (residual_wc) {
1115                                 result = target_write_memory(bank->target,
1116                                                 FLEXRAM+4*wc,
1117                                                 4, residual_wc,
1118                                                 residual_buffer);
1119
1120                                 if (result != ERROR_OK) {
1121                                         LOG_ERROR("target_write_memory failed");
1122                                         return result;
1123                                 }
1124                         }
1125
1126                         /* execute section-write command */
1127                         result = kinetis_ftfx_command(bank, FTFx_CMD_SECTWRITE, bank->base + offset + i,
1128                                         section_count>>8, section_count, 0, 0,
1129                                         0, 0, 0, 0,  &ftfx_fstat);
1130
1131                         if (result != ERROR_OK)
1132                                 return ERROR_FLASH_OPERATION_FAILED;
1133                 }
1134         }
1135         /* program longword command, not supported in "SF3" devices */
1136         else if (kinfo->flash_support & FS_PROGRAM_LONGWORD) {
1137                 if (count & 0x3) {
1138                         uint32_t old_count = count;
1139                         count = (old_count | 3) + 1;
1140                         new_buffer = malloc(count);
1141                         if (new_buffer == NULL) {
1142                                 LOG_ERROR("odd number of bytes to write and no memory "
1143                                         "for padding buffer");
1144                                 return ERROR_FAIL;
1145                         }
1146                         LOG_INFO("odd number of bytes to write (%" PRIu32 "), extending to %" PRIu32 " "
1147                                 "and padding with 0xff", old_count, count);
1148                         memset(new_buffer, 0xff, count);
1149                         buffer = memcpy(new_buffer, buffer, old_count);
1150                 }
1151
1152                 uint32_t words_remaining = count / 4;
1153
1154                 kinetis_disable_wdog(bank->target, kinfo->sim_sdid);
1155
1156                 /* try using a block write */
1157                 int retval = kinetis_write_block(bank, buffer, offset, words_remaining);
1158
1159                 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
1160                         /* if block write failed (no sufficient working area),
1161                          * we use normal (slow) single word accesses */
1162                         LOG_WARNING("couldn't use block writes, falling back to single "
1163                                 "memory accesses");
1164
1165                         for (i = 0; i < count; i += 4) {
1166                                 uint8_t ftfx_fstat;
1167
1168                                 LOG_DEBUG("write longword @ %08" PRIX32, (uint32_t)(offset + i));
1169
1170                                 uint8_t padding[4] = {0xff, 0xff, 0xff, 0xff};
1171                                 memcpy(padding, buffer + i, MIN(4, count-i));
1172
1173                                 result = kinetis_ftfx_command(bank, FTFx_CMD_LWORDPROG, bank->base + offset + i,
1174                                                 padding[3], padding[2], padding[1], padding[0],
1175                                                 0, 0, 0, 0,  &ftfx_fstat);
1176
1177                                 if (result != ERROR_OK)
1178                                         return ERROR_FLASH_OPERATION_FAILED;
1179                         }
1180                 }
1181         } else {
1182                 LOG_ERROR("Flash write strategy not implemented");
1183                 return ERROR_FLASH_OPERATION_FAILED;
1184         }
1185
1186         return ERROR_OK;
1187 }
1188
1189 static int kinetis_read_part_info(struct flash_bank *bank)
1190 {
1191         int result, i;
1192         uint32_t offset = 0;
1193         uint8_t fcfg1_nvmsize, fcfg1_pfsize, fcfg1_eesize, fcfg2_pflsh;
1194         uint32_t nvm_size = 0, pf_size = 0, ee_size = 0;
1195         unsigned num_blocks = 0, num_pflash_blocks = 0, num_nvm_blocks = 0, first_nvm_bank = 0,
1196                         reassign = 0, pflash_sector_size_bytes = 0, nvm_sector_size_bytes = 0;
1197         struct target *target = bank->target;
1198         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1199
1200         result = target_read_u32(target, SIM_SDID, &kinfo->sim_sdid);
1201         if (result != ERROR_OK)
1202                 return result;
1203
1204         if ((kinfo->sim_sdid & (~KINETIS_SDID_K_SERIES_MASK)) == 0) {
1205                 /* older K-series MCU */
1206                 uint32_t mcu_type = kinfo->sim_sdid & KINETIS_K_SDID_TYPE_MASK;
1207
1208                 switch (mcu_type) {
1209                 case KINETIS_K_SDID_K10_M50:
1210                 case KINETIS_K_SDID_K20_M50:
1211                         /* 1kB sectors */
1212                         pflash_sector_size_bytes = 1<<10;
1213                         nvm_sector_size_bytes = 1<<10;
1214                         num_blocks = 2;
1215                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR;
1216                         break;
1217                 case KINETIS_K_SDID_K10_M72:
1218                 case KINETIS_K_SDID_K20_M72:
1219                 case KINETIS_K_SDID_K30_M72:
1220                 case KINETIS_K_SDID_K30_M100:
1221                 case KINETIS_K_SDID_K40_M72:
1222                 case KINETIS_K_SDID_K40_M100:
1223                 case KINETIS_K_SDID_K50_M72:
1224                         /* 2kB sectors, 1kB FlexNVM sectors */
1225                         pflash_sector_size_bytes = 2<<10;
1226                         nvm_sector_size_bytes = 1<<10;
1227                         num_blocks = 2;
1228                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR;
1229                         kinfo->max_flash_prog_size = 1<<10;
1230                         break;
1231                 case KINETIS_K_SDID_K10_M100:
1232                 case KINETIS_K_SDID_K20_M100:
1233                 case KINETIS_K_SDID_K11:
1234                 case KINETIS_K_SDID_K12:
1235                 case KINETIS_K_SDID_K21_M50:
1236                 case KINETIS_K_SDID_K22_M50:
1237                 case KINETIS_K_SDID_K51_M72:
1238                 case KINETIS_K_SDID_K53:
1239                 case KINETIS_K_SDID_K60_M100:
1240                         /* 2kB sectors */
1241                         pflash_sector_size_bytes = 2<<10;
1242                         nvm_sector_size_bytes = 2<<10;
1243                         num_blocks = 2;
1244                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR;
1245                         break;
1246                 case KINETIS_K_SDID_K21_M120:
1247                 case KINETIS_K_SDID_K22_M120:
1248                         /* 4kB sectors (MK21FN1M0, MK21FX512, MK22FN1M0, MK22FX512) */
1249                         pflash_sector_size_bytes = 4<<10;
1250                         kinfo->max_flash_prog_size = 1<<10;
1251                         nvm_sector_size_bytes = 4<<10;
1252                         num_blocks = 2;
1253                         kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
1254                         break;
1255                 case KINETIS_K_SDID_K10_M120:
1256                 case KINETIS_K_SDID_K20_M120:
1257                 case KINETIS_K_SDID_K60_M150:
1258                 case KINETIS_K_SDID_K70_M150:
1259                         /* 4kB sectors */
1260                         pflash_sector_size_bytes = 4<<10;
1261                         nvm_sector_size_bytes = 4<<10;
1262                         num_blocks = 4;
1263                         kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
1264                         break;
1265                 default:
1266                         LOG_ERROR("Unsupported K-family FAMID");
1267                 }
1268         } else {
1269                 /* Newer K-series or KL series MCU */
1270                 switch (kinfo->sim_sdid & KINETIS_SDID_SERIESID_MASK) {
1271                 case KINETIS_SDID_SERIESID_K:
1272                         switch (kinfo->sim_sdid & (KINETIS_SDID_FAMILYID_MASK | KINETIS_SDID_SUBFAMID_MASK)) {
1273                         case KINETIS_SDID_FAMILYID_K0X | KINETIS_SDID_SUBFAMID_KX2:
1274                                 /* K02FN64, K02FN128: FTFA, 2kB sectors */
1275                                 pflash_sector_size_bytes = 2<<10;
1276                                 num_blocks = 1;
1277                                 kinfo->flash_support = FS_PROGRAM_LONGWORD;
1278                                 break;
1279
1280                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX2: {
1281                                 /* MK24FN1M reports as K22, this should detect it (according to errata note 1N83J) */
1282                                 uint32_t sopt1;
1283                                 result = target_read_u32(target, SIM_SOPT1, &sopt1);
1284                                 if (result != ERROR_OK)
1285                                         return result;
1286
1287                                 if (((kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K24FN1M) &&
1288                                                 ((sopt1 & KINETIS_SOPT1_RAMSIZE_MASK) == KINETIS_SOPT1_RAMSIZE_K24FN1M)) {
1289                                         /* MK24FN1M */
1290                                         pflash_sector_size_bytes = 4<<10;
1291                                         num_blocks = 2;
1292                                         kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
1293                                         kinfo->max_flash_prog_size = 1<<10;
1294                                         break;
1295                                 }
1296                                 if ((kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K22FN128
1297                                         || (kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K22FN256
1298                                         || (kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K22FN512) {
1299                                         /* K22 with new-style SDID - smaller pflash with FTFA, 2kB sectors */
1300                                         pflash_sector_size_bytes = 2<<10;
1301                                         num_blocks = 2;         /* 1 or 2 blocks */
1302                                         kinfo->flash_support = FS_PROGRAM_LONGWORD;
1303                                         break;
1304                                 }
1305                                 LOG_ERROR("Unsupported Kinetis K22 DIEID");
1306                                 break;
1307                         }
1308                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX4:
1309                                 pflash_sector_size_bytes = 4<<10;
1310                                 if ((kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K24FN256) {
1311                                         /* K24FN256 - smaller pflash with FTFA */
1312                                         num_blocks = 1;
1313                                         kinfo->flash_support = FS_PROGRAM_LONGWORD;
1314                                         break;
1315                                 }
1316                                 /* K24FN1M without errata 7534 */
1317                                 num_blocks = 2;
1318                                 kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
1319                                 kinfo->max_flash_prog_size = 1<<10;
1320                                 break;
1321
1322                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX3:
1323                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX1:     /* errata 7534 - should be K63 */
1324                                 /* K63FN1M0 */
1325                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX4:
1326                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX2:     /* errata 7534 - should be K64 */
1327                                 /* K64FN1M0, K64FX512 */
1328                                 pflash_sector_size_bytes = 4<<10;
1329                                 nvm_sector_size_bytes = 4<<10;
1330                                 kinfo->max_flash_prog_size = 1<<10;
1331                                 num_blocks = 2;
1332                                 kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
1333                                 break;
1334
1335                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX6:
1336                                 /* K26FN2M0 */
1337                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX6:
1338                                 /* K66FN2M0, K66FX1M0 */
1339                                 pflash_sector_size_bytes = 4<<10;
1340                                 nvm_sector_size_bytes = 4<<10;
1341                                 kinfo->max_flash_prog_size = 1<<10;
1342                                 num_blocks = 4;
1343                                 kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
1344                                 break;
1345                         default:
1346                                 LOG_ERROR("Unsupported Kinetis FAMILYID SUBFAMID");
1347                         }
1348                         break;
1349                 case KINETIS_SDID_SERIESID_KL:
1350                         /* KL-series */
1351                         pflash_sector_size_bytes = 1<<10;
1352                         nvm_sector_size_bytes = 1<<10;
1353                         num_blocks = 1;
1354                         kinfo->flash_support = FS_PROGRAM_LONGWORD;
1355                         break;
1356                 default:
1357                         LOG_ERROR("Unsupported K-series");
1358                 }
1359         }
1360
1361         if (pflash_sector_size_bytes == 0) {
1362                 LOG_ERROR("MCU is unsupported, SDID 0x%08" PRIx32, kinfo->sim_sdid);
1363                 return ERROR_FLASH_OPER_UNSUPPORTED;
1364         }
1365
1366         result = target_read_u32(target, SIM_FCFG1, &kinfo->sim_fcfg1);
1367         if (result != ERROR_OK)
1368                 return result;
1369
1370         result = target_read_u32(target, SIM_FCFG2, &kinfo->sim_fcfg2);
1371         if (result != ERROR_OK)
1372                 return result;
1373         fcfg2_pflsh = (kinfo->sim_fcfg2 >> 23) & 0x01;
1374
1375         LOG_DEBUG("SDID: 0x%08" PRIX32 " FCFG1: 0x%08" PRIX32 " FCFG2: 0x%08" PRIX32, kinfo->sim_sdid,
1376                         kinfo->sim_fcfg1, kinfo->sim_fcfg2);
1377
1378         fcfg1_nvmsize = (uint8_t)((kinfo->sim_fcfg1 >> 28) & 0x0f);
1379         fcfg1_pfsize = (uint8_t)((kinfo->sim_fcfg1 >> 24) & 0x0f);
1380         fcfg1_eesize = (uint8_t)((kinfo->sim_fcfg1 >> 16) & 0x0f);
1381
1382         /* when the PFLSH bit is set, there is no FlexNVM/FlexRAM */
1383         if (!fcfg2_pflsh) {
1384                 switch (fcfg1_nvmsize) {
1385                 case 0x03:
1386                 case 0x07:
1387                 case 0x09:
1388                 case 0x0b:
1389                         nvm_size = 1 << (14 + (fcfg1_nvmsize >> 1));
1390                         break;
1391                 case 0x0f:
1392                         if (pflash_sector_size_bytes >= 4<<10)
1393                                 nvm_size = 512<<10;
1394                         else
1395                                 /* K20_100 */
1396                                 nvm_size = 256<<10;
1397                         break;
1398                 default:
1399                         nvm_size = 0;
1400                         break;
1401                 }
1402
1403                 switch (fcfg1_eesize) {
1404                 case 0x00:
1405                 case 0x01:
1406                 case 0x02:
1407                 case 0x03:
1408                 case 0x04:
1409                 case 0x05:
1410                 case 0x06:
1411                 case 0x07:
1412                 case 0x08:
1413                 case 0x09:
1414                         ee_size = (16 << (10 - fcfg1_eesize));
1415                         break;
1416                 default:
1417                         ee_size = 0;
1418                         break;
1419                 }
1420         }
1421
1422         switch (fcfg1_pfsize) {
1423         case 0x03:
1424         case 0x05:
1425         case 0x07:
1426         case 0x09:
1427         case 0x0b:
1428         case 0x0d:
1429                 pf_size = 1 << (14 + (fcfg1_pfsize >> 1));
1430                 break;
1431         case 0x0f:
1432                 if (pflash_sector_size_bytes >= 4<<10)
1433                         pf_size = 1024<<10;
1434                 else if (fcfg2_pflsh)
1435                         pf_size = 512<<10;
1436                 else
1437                         pf_size = 256<<10;
1438                 break;
1439         default:
1440                 pf_size = 0;
1441                 break;
1442         }
1443
1444         LOG_DEBUG("FlexNVM: %" PRIu32 " PFlash: %" PRIu32 " FlexRAM: %" PRIu32 " PFLSH: %d",
1445                   nvm_size, pf_size, ee_size, fcfg2_pflsh);
1446
1447         num_pflash_blocks = num_blocks / (2 - fcfg2_pflsh);
1448         first_nvm_bank = num_pflash_blocks;
1449         num_nvm_blocks = num_blocks - num_pflash_blocks;
1450
1451         LOG_DEBUG("%d blocks total: %d PFlash, %d FlexNVM",
1452                         num_blocks, num_pflash_blocks, num_nvm_blocks);
1453
1454         /*
1455          * If the flash class is already assigned, verify the
1456          * parameters.
1457          */
1458         if (kinfo->flash_class != FC_AUTO) {
1459                 if (kinfo->bank_ordinal != (unsigned) bank->bank_number) {
1460                         LOG_WARNING("Flash ordinal/bank number mismatch");
1461                         reassign = 1;
1462                 } else {
1463                         switch (kinfo->flash_class) {
1464                         case FC_PFLASH:
1465                                 if (kinfo->bank_ordinal >= first_nvm_bank) {
1466                                         LOG_WARNING("Class mismatch, bank %d is not PFlash", bank->bank_number);
1467                                         reassign = 1;
1468                                 } else if (bank->size != (pf_size / num_pflash_blocks)) {
1469                                         LOG_WARNING("PFlash size mismatch");
1470                                         reassign = 1;
1471                                 } else if (bank->base !=
1472                                          (0x00000000 + bank->size * kinfo->bank_ordinal)) {
1473                                         LOG_WARNING("PFlash address range mismatch");
1474                                         reassign = 1;
1475                                 } else if (kinfo->sector_size != pflash_sector_size_bytes) {
1476                                         LOG_WARNING("PFlash sector size mismatch");
1477                                         reassign = 1;
1478                                 } else {
1479                                         LOG_DEBUG("PFlash bank %d already configured okay",
1480                                                   kinfo->bank_ordinal);
1481                                 }
1482                                 break;
1483                         case FC_FLEX_NVM:
1484                                 if ((kinfo->bank_ordinal >= num_blocks) ||
1485                                                 (kinfo->bank_ordinal < first_nvm_bank)) {
1486                                         LOG_WARNING("Class mismatch, bank %d is not FlexNVM", bank->bank_number);
1487                                         reassign = 1;
1488                                 } else if (bank->size != (nvm_size / num_nvm_blocks)) {
1489                                         LOG_WARNING("FlexNVM size mismatch");
1490                                         reassign = 1;
1491                                 } else if (bank->base !=
1492                                                 (0x10000000 + bank->size * kinfo->bank_ordinal)) {
1493                                         LOG_WARNING("FlexNVM address range mismatch");
1494                                         reassign = 1;
1495                                 } else if (kinfo->sector_size != nvm_sector_size_bytes) {
1496                                         LOG_WARNING("FlexNVM sector size mismatch");
1497                                         reassign = 1;
1498                                 } else {
1499                                         LOG_DEBUG("FlexNVM bank %d already configured okay",
1500                                                   kinfo->bank_ordinal);
1501                                 }
1502                                 break;
1503                         case FC_FLEX_RAM:
1504                                 if (kinfo->bank_ordinal != num_blocks) {
1505                                         LOG_WARNING("Class mismatch, bank %d is not FlexRAM", bank->bank_number);
1506                                         reassign = 1;
1507                                 } else if (bank->size != ee_size) {
1508                                         LOG_WARNING("FlexRAM size mismatch");
1509                                         reassign = 1;
1510                                 } else if (bank->base != FLEXRAM) {
1511                                         LOG_WARNING("FlexRAM address mismatch");
1512                                         reassign = 1;
1513                                 } else if (kinfo->sector_size != nvm_sector_size_bytes) {
1514                                         LOG_WARNING("FlexRAM sector size mismatch");
1515                                         reassign = 1;
1516                                 } else {
1517                                         LOG_DEBUG("FlexRAM bank %d already configured okay", kinfo->bank_ordinal);
1518                                 }
1519                                 break;
1520
1521                         default:
1522                                 LOG_WARNING("Unknown or inconsistent flash class");
1523                                 reassign = 1;
1524                                 break;
1525                         }
1526                 }
1527         } else {
1528                 LOG_INFO("Probing flash info for bank %d", bank->bank_number);
1529                 reassign = 1;
1530         }
1531
1532         if (!reassign)
1533                 return ERROR_OK;
1534
1535         if ((unsigned)bank->bank_number < num_pflash_blocks) {
1536                 /* pflash, banks start at address zero */
1537                 kinfo->flash_class = FC_PFLASH;
1538                 bank->size = (pf_size / num_pflash_blocks);
1539                 bank->base = 0x00000000 + bank->size * bank->bank_number;
1540                 kinfo->sector_size = pflash_sector_size_bytes;
1541                 kinfo->protection_size = pf_size / 32;
1542         } else if ((unsigned)bank->bank_number < num_blocks) {
1543                 /* nvm, banks start at address 0x10000000 */
1544                 kinfo->flash_class = FC_FLEX_NVM;
1545                 bank->size = (nvm_size / num_nvm_blocks);
1546                 bank->base = 0x10000000 + bank->size * (bank->bank_number - first_nvm_bank);
1547                 kinfo->sector_size = nvm_sector_size_bytes;
1548                 kinfo->protection_size = 0; /* FIXME: TODO: depends on DEPART bits, chip */
1549         } else if ((unsigned)bank->bank_number == num_blocks) {
1550                 LOG_ERROR("FlexRAM support not yet implemented");
1551                 return ERROR_FLASH_OPER_UNSUPPORTED;
1552         } else {
1553                 LOG_ERROR("Cannot determine parameters for bank %d, only %d banks on device",
1554                                 bank->bank_number, num_blocks);
1555                 return ERROR_FLASH_BANK_INVALID;
1556         }
1557
1558         if (bank->sectors) {
1559                 free(bank->sectors);
1560                 bank->sectors = NULL;
1561         }
1562
1563         if (kinfo->sector_size == 0) {
1564                 LOG_ERROR("Unknown sector size for bank %d", bank->bank_number);
1565                 return ERROR_FLASH_BANK_INVALID;
1566         }
1567
1568         if (kinfo->flash_support & FS_PROGRAM_SECTOR
1569                          && kinfo->max_flash_prog_size == 0) {
1570                 kinfo->max_flash_prog_size = kinfo->sector_size;
1571                 /* Program section size is equal to sector size by default */
1572         }
1573
1574         bank->num_sectors = bank->size / kinfo->sector_size;
1575         assert(bank->num_sectors > 0);
1576         bank->sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
1577
1578         for (i = 0; i < bank->num_sectors; i++) {
1579                 bank->sectors[i].offset = offset;
1580                 bank->sectors[i].size = kinfo->sector_size;
1581                 offset += kinfo->sector_size;
1582                 bank->sectors[i].is_erased = -1;
1583                 bank->sectors[i].is_protected = 1;
1584         }
1585
1586         return ERROR_OK;
1587 }
1588
1589 static int kinetis_probe(struct flash_bank *bank)
1590 {
1591         if (bank->target->state != TARGET_HALTED) {
1592                 LOG_WARNING("Cannot communicate... target not halted.");
1593                 return ERROR_TARGET_NOT_HALTED;
1594         }
1595
1596         return kinetis_read_part_info(bank);
1597 }
1598
1599 static int kinetis_auto_probe(struct flash_bank *bank)
1600 {
1601         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1602
1603         if (kinfo->sim_sdid)
1604                 return ERROR_OK;
1605
1606         return kinetis_probe(bank);
1607 }
1608
1609 static int kinetis_info(struct flash_bank *bank, char *buf, int buf_size)
1610 {
1611         const char *bank_class_names[] = {
1612                 "(ANY)", "PFlash", "FlexNVM", "FlexRAM"
1613         };
1614
1615         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1616
1617         (void) snprintf(buf, buf_size,
1618                         "%s driver for %s flash bank %s at 0x%8.8" PRIx32 "",
1619                         bank->driver->name, bank_class_names[kinfo->flash_class],
1620                         bank->name, bank->base);
1621
1622         return ERROR_OK;
1623 }
1624
1625 static int kinetis_blank_check(struct flash_bank *bank)
1626 {
1627         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1628
1629         if (bank->target->state != TARGET_HALTED) {
1630                 LOG_ERROR("Target not halted");
1631                 return ERROR_TARGET_NOT_HALTED;
1632         }
1633
1634         if (kinfo->flash_class == FC_PFLASH) {
1635                 int result;
1636                 uint8_t ftfx_fstat;
1637
1638                 /* check if whole bank is blank */
1639                 result = kinetis_ftfx_command(bank, FTFx_CMD_BLOCKSTAT, bank->base, 0, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
1640
1641                 if (result != ERROR_OK)
1642                         return result;
1643
1644                 if (ftfx_fstat & 0x01) {
1645                         /* the whole bank is not erased, check sector-by-sector */
1646                         int i;
1647                         for (i = 0; i < bank->num_sectors; i++) {
1648                                 /* normal margin */
1649                                 result = kinetis_ftfx_command(bank, FTFx_CMD_SECTSTAT, bank->base + bank->sectors[i].offset,
1650                                                 1, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
1651
1652                                 if (result == ERROR_OK) {
1653                                         bank->sectors[i].is_erased = !(ftfx_fstat & 0x01);
1654                                 } else {
1655                                         LOG_DEBUG("Ignoring errored PFlash sector blank-check");
1656                                         bank->sectors[i].is_erased = -1;
1657                                 }
1658                         }
1659                 } else {
1660                         /* the whole bank is erased, update all sectors */
1661                         int i;
1662                         for (i = 0; i < bank->num_sectors; i++)
1663                                 bank->sectors[i].is_erased = 1;
1664                 }
1665         } else {
1666                 LOG_WARNING("kinetis_blank_check not supported yet for FlexNVM");
1667                 return ERROR_FLASH_OPERATION_FAILED;
1668         }
1669
1670         return ERROR_OK;
1671 }
1672
1673 static const struct command_registration kinetis_securtiy_command_handlers[] = {
1674         {
1675                 .name = "check_security",
1676                 .mode = COMMAND_EXEC,
1677                 .help = "",
1678                 .usage = "",
1679                 .handler = kinetis_check_flash_security_status,
1680         },
1681         {
1682                 .name = "mass_erase",
1683                 .mode = COMMAND_EXEC,
1684                 .help = "",
1685                 .usage = "",
1686                 .handler = kinetis_mdm_mass_erase,
1687         },
1688         {
1689                 .name = "test_securing",
1690                 .mode = COMMAND_EXEC,
1691                 .help = "",
1692                 .usage = "",
1693                 .handler = kinetis_securing_test,
1694         },
1695         COMMAND_REGISTRATION_DONE
1696 };
1697
1698 static const struct command_registration kinetis_exec_command_handlers[] = {
1699         {
1700                 .name = "mdm",
1701                 .mode = COMMAND_ANY,
1702                 .help = "",
1703                 .usage = "",
1704                 .chain = kinetis_securtiy_command_handlers,
1705         },
1706         {
1707                 .name = "disable_wdog",
1708                 .mode = COMMAND_EXEC,
1709                 .help = "Disable the watchdog timer",
1710                 .usage = "",
1711                 .handler = kinetis_disable_wdog_handler,
1712         },
1713         COMMAND_REGISTRATION_DONE
1714 };
1715
1716 static const struct command_registration kinetis_command_handler[] = {
1717         {
1718                 .name = "kinetis",
1719                 .mode = COMMAND_ANY,
1720                 .help = "kinetis NAND flash controller commands",
1721                 .usage = "",
1722                 .chain = kinetis_exec_command_handlers,
1723         },
1724         COMMAND_REGISTRATION_DONE
1725 };
1726
1727
1728
1729 struct flash_driver kinetis_flash = {
1730         .name = "kinetis",
1731         .commands = kinetis_command_handler,
1732         .flash_bank_command = kinetis_flash_bank_command,
1733         .erase = kinetis_erase,
1734         .protect = kinetis_protect,
1735         .write = kinetis_write,
1736         .read = default_flash_read,
1737         .probe = kinetis_probe,
1738         .auto_probe = kinetis_auto_probe,
1739         .erase_check = kinetis_blank_check,
1740         .protect_check = kinetis_protect_check,
1741         .info = kinetis_info,
1742 };