flash Kinetis: reduce a flash write message severity to info
[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  *   Copyright (C) 2015 Tomas Vanek                                        *
15  *   vanekt@fbl.cz                                                         *
16  *                                                                         *
17  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
29  ***************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #include "jtag/interface.h"
36 #include "imp.h"
37 #include <helper/binarybuffer.h>
38 #include <helper/time_support.h>
39 #include <target/target_type.h>
40 #include <target/algorithm.h>
41 #include <target/armv7m.h>
42 #include <target/cortex_m.h>
43
44 /*
45  * Implementation Notes
46  *
47  * The persistent memories in the Kinetis chip families K10 through
48  * K70 are all manipulated with the Flash Memory Module.  Some
49  * variants call this module the FTFE, others call it the FTFL.  To
50  * indicate that both are considered here, we use FTFX.
51  *
52  * Within the module, according to the chip variant, the persistent
53  * memory is divided into what Freescale terms Program Flash, FlexNVM,
54  * and FlexRAM.  All chip variants have Program Flash.  Some chip
55  * variants also have FlexNVM and FlexRAM, which always appear
56  * together.
57  *
58  * A given Kinetis chip may have 1, 2 or 4 blocks of flash.  Here we map
59  * each block to a separate bank.  Each block size varies by chip and
60  * may be determined by the read-only SIM_FCFG1 register.  The sector
61  * size within each bank/block varies by chip, and may be 1, 2 or 4k.
62  * The sector size may be different for flash and FlexNVM.
63  *
64  * The first half of the flash (1 or 2 blocks) is always Program Flash
65  * and always starts at address 0x00000000.  The "PFLSH" flag, bit 23
66  * of the read-only SIM_FCFG2 register, determines whether the second
67  * half of the flash is also Program Flash or FlexNVM+FlexRAM.  When
68  * PFLSH is set, the second from the first half.  When PFLSH is clear,
69  * the second half of flash is FlexNVM and always starts at address
70  * 0x10000000.  FlexRAM, which is also present when PFLSH is clear,
71  * always starts at address 0x14000000.
72  *
73  * The Flash Memory Module provides a register set where flash
74  * commands are loaded to perform flash operations like erase and
75  * program.  Different commands are available depending on whether
76  * Program Flash or FlexNVM/FlexRAM is being manipulated.  Although
77  * the commands used are quite consistent between flash blocks, the
78  * parameters they accept differ according to the flash sector size.
79  *
80  */
81
82 /* Addressess */
83 #define FCF_ADDRESS     0x00000400
84 #define FCF_FPROT       0x8
85 #define FCF_FSEC        0xc
86 #define FCF_FOPT        0xd
87 #define FCF_FDPROT      0xf
88 #define FCF_SIZE        0x10
89
90 #define FLEXRAM         0x14000000
91
92 #define FMC_PFB01CR     0x4001f004
93 #define FTFx_FSTAT      0x40020000
94 #define FTFx_FCNFG      0x40020001
95 #define FTFx_FCCOB3     0x40020004
96 #define FTFx_FPROT3     0x40020010
97 #define FTFx_FDPROT     0x40020017
98 #define SIM_SDID        0x40048024
99 #define SIM_SOPT1       0x40047000
100 #define SIM_FCFG1       0x4004804c
101 #define SIM_FCFG2       0x40048050
102 #define WDOG_STCTRH     0x40052000
103 #define SMC_PMCTRL      0x4007E001
104 #define SMC_PMSTAT      0x4007E003
105 #define MCM_PLACR       0xF000300C
106
107 /* Values */
108 #define PM_STAT_RUN             0x01
109 #define PM_STAT_VLPR            0x04
110 #define PM_CTRL_RUNM_RUN        0x00
111
112 /* Commands */
113 #define FTFx_CMD_BLOCKSTAT  0x00
114 #define FTFx_CMD_SECTSTAT   0x01
115 #define FTFx_CMD_LWORDPROG  0x06
116 #define FTFx_CMD_SECTERASE  0x09
117 #define FTFx_CMD_SECTWRITE  0x0b
118 #define FTFx_CMD_MASSERASE  0x44
119 #define FTFx_CMD_PGMPART    0x80
120 #define FTFx_CMD_SETFLEXRAM 0x81
121
122 /* The older Kinetis K series uses the following SDID layout :
123  * Bit 31-16 : 0
124  * Bit 15-12 : REVID
125  * Bit 11-7  : DIEID
126  * Bit 6-4   : FAMID
127  * Bit 3-0   : PINID
128  *
129  * The newer Kinetis series uses the following SDID layout :
130  * Bit 31-28 : FAMID
131  * Bit 27-24 : SUBFAMID
132  * Bit 23-20 : SERIESID
133  * Bit 19-16 : SRAMSIZE
134  * Bit 15-12 : REVID
135  * Bit 6-4   : Reserved (0)
136  * Bit 3-0   : PINID
137  *
138  * We assume that if bits 31-16 are 0 then it's an older
139  * K-series MCU.
140  */
141
142 #define KINETIS_SOPT1_RAMSIZE_MASK  0x0000F000
143 #define KINETIS_SOPT1_RAMSIZE_K24FN1M 0x0000B000
144
145 #define KINETIS_SDID_K_SERIES_MASK  0x0000FFFF
146
147 #define KINETIS_SDID_DIEID_MASK 0x00000F80
148
149 #define KINETIS_SDID_DIEID_K22FN128     0x00000680 /* smaller pflash with FTFA */
150 #define KINETIS_SDID_DIEID_K22FN256     0x00000A80
151 #define KINETIS_SDID_DIEID_K22FN512     0x00000E80
152 #define KINETIS_SDID_DIEID_K24FN256     0x00000700
153
154 #define KINETIS_SDID_DIEID_K24FN1M      0x00000300 /* Detect Errata 7534 */
155
156 /* We can't rely solely on the FAMID field to determine the MCU
157  * type since some FAMID values identify multiple MCUs with
158  * different flash sector sizes (K20 and K22 for instance).
159  * Therefore we combine it with the DIEID bits which may possibly
160  * break if Freescale bumps the DIEID for a particular MCU. */
161 #define KINETIS_K_SDID_TYPE_MASK 0x00000FF0
162 #define KINETIS_K_SDID_K10_M50   0x00000000
163 #define KINETIS_K_SDID_K10_M72   0x00000080
164 #define KINETIS_K_SDID_K10_M100  0x00000100
165 #define KINETIS_K_SDID_K10_M120  0x00000180
166 #define KINETIS_K_SDID_K11               0x00000220
167 #define KINETIS_K_SDID_K12               0x00000200
168 #define KINETIS_K_SDID_K20_M50   0x00000010
169 #define KINETIS_K_SDID_K20_M72   0x00000090
170 #define KINETIS_K_SDID_K20_M100  0x00000110
171 #define KINETIS_K_SDID_K20_M120  0x00000190
172 #define KINETIS_K_SDID_K21_M50   0x00000230
173 #define KINETIS_K_SDID_K21_M120  0x00000330
174 #define KINETIS_K_SDID_K22_M50   0x00000210
175 #define KINETIS_K_SDID_K22_M120  0x00000310
176 #define KINETIS_K_SDID_K30_M72   0x000000A0
177 #define KINETIS_K_SDID_K30_M100  0x00000120
178 #define KINETIS_K_SDID_K40_M72   0x000000B0
179 #define KINETIS_K_SDID_K40_M100  0x00000130
180 #define KINETIS_K_SDID_K50_M72   0x000000E0
181 #define KINETIS_K_SDID_K51_M72   0x000000F0
182 #define KINETIS_K_SDID_K53               0x00000170
183 #define KINETIS_K_SDID_K60_M100  0x00000140
184 #define KINETIS_K_SDID_K60_M150  0x000001C0
185 #define KINETIS_K_SDID_K70_M150  0x000001D0
186
187 #define KINETIS_SDID_SERIESID_MASK 0x00F00000
188 #define KINETIS_SDID_SERIESID_K   0x00000000
189 #define KINETIS_SDID_SERIESID_KL   0x00100000
190 #define KINETIS_SDID_SERIESID_KW   0x00500000
191 #define KINETIS_SDID_SERIESID_KV   0x00600000
192
193 #define KINETIS_SDID_SUBFAMID_MASK  0x0F000000
194 #define KINETIS_SDID_SUBFAMID_KX0   0x00000000
195 #define KINETIS_SDID_SUBFAMID_KX1   0x01000000
196 #define KINETIS_SDID_SUBFAMID_KX2   0x02000000
197 #define KINETIS_SDID_SUBFAMID_KX3   0x03000000
198 #define KINETIS_SDID_SUBFAMID_KX4   0x04000000
199 #define KINETIS_SDID_SUBFAMID_KX5   0x05000000
200 #define KINETIS_SDID_SUBFAMID_KX6   0x06000000
201
202 #define KINETIS_SDID_FAMILYID_MASK  0xF0000000
203 #define KINETIS_SDID_FAMILYID_K0X   0x00000000
204 #define KINETIS_SDID_FAMILYID_K1X   0x10000000
205 #define KINETIS_SDID_FAMILYID_K2X   0x20000000
206 #define KINETIS_SDID_FAMILYID_K3X   0x30000000
207 #define KINETIS_SDID_FAMILYID_K4X   0x40000000
208 #define KINETIS_SDID_FAMILYID_K6X   0x60000000
209 #define KINETIS_SDID_FAMILYID_K7X   0x70000000
210 #define KINETIS_SDID_FAMILYID_K8X   0x80000000
211
212 struct kinetis_flash_bank {
213         bool probed;
214         uint32_t sector_size;
215         uint32_t max_flash_prog_size;
216         uint32_t protection_size;
217         uint32_t prog_base;             /* base address for FTFx operations */
218                                         /* same as bank->base for pflash, differs for FlexNVM */
219         uint32_t protection_block;      /* number of first protection block in this bank */
220
221         uint32_t sim_sdid;
222         uint32_t sim_fcfg1;
223         uint32_t sim_fcfg2;
224
225         enum {
226                 FC_AUTO = 0,
227                 FC_PFLASH,
228                 FC_FLEX_NVM,
229                 FC_FLEX_RAM,
230         } flash_class;
231
232         enum {
233                 FS_PROGRAM_SECTOR = 1,
234                 FS_PROGRAM_LONGWORD = 2,
235                 FS_PROGRAM_PHRASE = 4, /* Unsupported */
236                 FS_INVALIDATE_CACHE_K = 8,
237                 FS_INVALIDATE_CACHE_L = 0x10,
238         } flash_support;
239 };
240
241 #define MDM_AP                  1
242
243 #define MDM_REG_STAT            0x00
244 #define MDM_REG_CTRL            0x04
245 #define MDM_REG_ID              0xfc
246
247 #define MDM_STAT_FMEACK         (1<<0)
248 #define MDM_STAT_FREADY         (1<<1)
249 #define MDM_STAT_SYSSEC         (1<<2)
250 #define MDM_STAT_SYSRES         (1<<3)
251 #define MDM_STAT_FMEEN          (1<<5)
252 #define MDM_STAT_BACKDOOREN     (1<<6)
253 #define MDM_STAT_LPEN           (1<<7)
254 #define MDM_STAT_VLPEN          (1<<8)
255 #define MDM_STAT_LLSMODEXIT     (1<<9)
256 #define MDM_STAT_VLLSXMODEXIT   (1<<10)
257 #define MDM_STAT_CORE_HALTED    (1<<16)
258 #define MDM_STAT_CORE_SLEEPDEEP (1<<17)
259 #define MDM_STAT_CORESLEEPING   (1<<18)
260
261 #define MDM_CTRL_FMEIP          (1<<0)
262 #define MDM_CTRL_DBG_DIS        (1<<1)
263 #define MDM_CTRL_DBG_REQ        (1<<2)
264 #define MDM_CTRL_SYS_RES_REQ    (1<<3)
265 #define MDM_CTRL_CORE_HOLD_RES  (1<<4)
266 #define MDM_CTRL_VLLSX_DBG_REQ  (1<<5)
267 #define MDM_CTRL_VLLSX_DBG_ACK  (1<<6)
268 #define MDM_CTRL_VLLSX_STAT_ACK (1<<7)
269
270 #define MDM_ACCESS_TIMEOUT      500 /* msec */
271
272
273 static bool allow_fcf_writes;
274 static uint8_t fcf_fopt = 0xff;
275
276
277 struct flash_driver kinetis_flash;
278 static int kinetis_write_inner(struct flash_bank *bank, const uint8_t *buffer,
279                         uint32_t offset, uint32_t count);
280 static int kinetis_auto_probe(struct flash_bank *bank);
281
282
283 static int kinetis_mdm_write_register(struct adiv5_dap *dap, unsigned reg, uint32_t value)
284 {
285         int retval;
286         LOG_DEBUG("MDM_REG[0x%02x] <- %08" PRIX32, reg, value);
287
288         retval = dap_queue_ap_write(dap_ap(dap, MDM_AP), reg, value);
289         if (retval != ERROR_OK) {
290                 LOG_DEBUG("MDM: failed to queue a write request");
291                 return retval;
292         }
293
294         retval = dap_run(dap);
295         if (retval != ERROR_OK) {
296                 LOG_DEBUG("MDM: dap_run failed");
297                 return retval;
298         }
299
300
301         return ERROR_OK;
302 }
303
304 static int kinetis_mdm_read_register(struct adiv5_dap *dap, unsigned reg, uint32_t *result)
305 {
306         int retval;
307
308         retval = dap_queue_ap_read(dap_ap(dap, MDM_AP), reg, result);
309         if (retval != ERROR_OK) {
310                 LOG_DEBUG("MDM: failed to queue a read request");
311                 return retval;
312         }
313
314         retval = dap_run(dap);
315         if (retval != ERROR_OK) {
316                 LOG_DEBUG("MDM: dap_run failed");
317                 return retval;
318         }
319
320         LOG_DEBUG("MDM_REG[0x%02x]: %08" PRIX32, reg, *result);
321         return ERROR_OK;
322 }
323
324 static int kinetis_mdm_poll_register(struct adiv5_dap *dap, unsigned reg,
325                         uint32_t mask, uint32_t value, uint32_t timeout_ms)
326 {
327         uint32_t val;
328         int retval;
329         int64_t ms_timeout = timeval_ms() + timeout_ms;
330
331         do {
332                 retval = kinetis_mdm_read_register(dap, reg, &val);
333                 if (retval != ERROR_OK || (val & mask) == value)
334                         return retval;
335
336                 alive_sleep(1);
337         } while (timeval_ms() < ms_timeout);
338
339         LOG_DEBUG("MDM: polling timed out");
340         return ERROR_FAIL;
341 }
342
343 /*
344  * This command can be used to break a watchdog reset loop when
345  * connecting to an unsecured target. Unlike other commands, halt will
346  * automatically retry as it does not know how far into the boot process
347  * it is when the command is called.
348  */
349 COMMAND_HANDLER(kinetis_mdm_halt)
350 {
351         struct target *target = get_current_target(CMD_CTX);
352         struct cortex_m_common *cortex_m = target_to_cm(target);
353         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
354         int retval;
355         int tries = 0;
356         uint32_t stat;
357         int64_t ms_timeout = timeval_ms() + MDM_ACCESS_TIMEOUT;
358
359         if (!dap) {
360                 LOG_ERROR("Cannot perform halt with a high-level adapter");
361                 return ERROR_FAIL;
362         }
363
364         while (true) {
365                 tries++;
366
367                 kinetis_mdm_write_register(dap, MDM_REG_CTRL, MDM_CTRL_CORE_HOLD_RES);
368
369                 alive_sleep(1);
370
371                 retval = kinetis_mdm_read_register(dap, MDM_REG_STAT, &stat);
372                 if (retval != ERROR_OK) {
373                         LOG_DEBUG("MDM: failed to read MDM_REG_STAT");
374                         continue;
375                 }
376
377                 /* Repeat setting MDM_CTRL_CORE_HOLD_RES until system is out of
378                  * reset with flash ready and without security
379                  */
380                 if ((stat & (MDM_STAT_FREADY | MDM_STAT_SYSSEC | MDM_STAT_SYSRES))
381                                 == (MDM_STAT_FREADY | MDM_STAT_SYSRES))
382                         break;
383
384                 if (timeval_ms() >= ms_timeout) {
385                         LOG_ERROR("MDM: halt timed out");
386                         return ERROR_FAIL;
387                 }
388         }
389
390         LOG_DEBUG("MDM: halt succeded after %d attempts.", tries);
391
392         target_poll(target);
393         /* enable polling in case kinetis_check_flash_security_status disabled it */
394         jtag_poll_set_enabled(true);
395
396         alive_sleep(100);
397
398         target->reset_halt = true;
399         target->type->assert_reset(target);
400
401         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
402         if (retval != ERROR_OK) {
403                 LOG_ERROR("MDM: failed to clear MDM_REG_CTRL");
404                 return retval;
405         }
406
407         target->type->deassert_reset(target);
408
409         return ERROR_OK;
410 }
411
412 COMMAND_HANDLER(kinetis_mdm_reset)
413 {
414         struct target *target = get_current_target(CMD_CTX);
415         struct cortex_m_common *cortex_m = target_to_cm(target);
416         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
417         int retval;
418
419         if (!dap) {
420                 LOG_ERROR("Cannot perform reset with a high-level adapter");
421                 return ERROR_FAIL;
422         }
423
424         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, MDM_CTRL_SYS_RES_REQ);
425         if (retval != ERROR_OK) {
426                 LOG_ERROR("MDM: failed to write MDM_REG_CTRL");
427                 return retval;
428         }
429
430         retval = kinetis_mdm_poll_register(dap, MDM_REG_STAT, MDM_STAT_SYSRES, 0, 500);
431         if (retval != ERROR_OK) {
432                 LOG_ERROR("MDM: failed to assert reset");
433                 return retval;
434         }
435
436         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
437         if (retval != ERROR_OK) {
438                 LOG_ERROR("MDM: failed to clear MDM_REG_CTRL");
439                 return retval;
440         }
441
442         return ERROR_OK;
443 }
444
445 /*
446  * This function implements the procedure to mass erase the flash via
447  * SWD/JTAG on Kinetis K and L series of devices as it is described in
448  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
449  * and L-series MCUs" Section 4.2.1. To prevent a watchdog reset loop,
450  * the core remains halted after this function completes as suggested
451  * by the application note.
452  */
453 COMMAND_HANDLER(kinetis_mdm_mass_erase)
454 {
455         struct target *target = get_current_target(CMD_CTX);
456         struct cortex_m_common *cortex_m = target_to_cm(target);
457         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
458
459         if (!dap) {
460                 LOG_ERROR("Cannot perform mass erase with a high-level adapter");
461                 return ERROR_FAIL;
462         }
463
464         int retval;
465
466         /*
467          * ... Power on the processor, or if power has already been
468          * applied, assert the RESET pin to reset the processor. For
469          * devices that do not have a RESET pin, write the System
470          * Reset Request bit in the MDM-AP control register after
471          * establishing communication...
472          */
473
474         /* assert SRST if configured */
475         bool has_srst = jtag_get_reset_config() & RESET_HAS_SRST;
476         if (has_srst)
477                 adapter_assert_reset();
478
479         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, MDM_CTRL_SYS_RES_REQ);
480         if (retval != ERROR_OK && !has_srst) {
481                 LOG_ERROR("MDM: failed to assert reset");
482                 goto deassert_reset_and_exit;
483         }
484
485         /*
486          * ... Read the MDM-AP status register repeatedly and wait for
487          * stable conditions suitable for mass erase:
488          * - mass erase is enabled
489          * - flash is ready
490          * - reset is finished
491          *
492          * Mass erase is started as soon as all conditions are met in 32
493          * subsequent status reads.
494          *
495          * In case of not stable conditions (RESET/WDOG loop in secured device)
496          * the user is asked for manual pressing of RESET button
497          * as a last resort.
498          */
499         int cnt_mass_erase_disabled = 0;
500         int cnt_ready = 0;
501         int64_t ms_start = timeval_ms();
502         bool man_reset_requested = false;
503
504         do {
505                 uint32_t stat = 0;
506                 int64_t ms_elapsed = timeval_ms() - ms_start;
507
508                 if (!man_reset_requested && ms_elapsed > 100) {
509                         LOG_INFO("MDM: Press RESET button now if possible.");
510                         man_reset_requested = true;
511                 }
512
513                 if (ms_elapsed > 3000) {
514                         LOG_ERROR("MDM: waiting for mass erase conditions timed out.");
515                         LOG_INFO("Mass erase of a secured MCU is not possible without hardware reset.");
516                         LOG_INFO("Connect SRST, use 'reset_config srst_only' and retry.");
517                         goto deassert_reset_and_exit;
518                 }
519                 retval = kinetis_mdm_read_register(dap, MDM_REG_STAT, &stat);
520                 if (retval != ERROR_OK) {
521                         cnt_ready = 0;
522                         continue;
523                 }
524
525                 if (!(stat & MDM_STAT_FMEEN)) {
526                         cnt_ready = 0;
527                         cnt_mass_erase_disabled++;
528                         if (cnt_mass_erase_disabled > 10) {
529                                 LOG_ERROR("MDM: mass erase is disabled");
530                                 goto deassert_reset_and_exit;
531                         }
532                         continue;
533                 }
534
535                 if ((stat & (MDM_STAT_FREADY | MDM_STAT_SYSRES)) == MDM_STAT_FREADY)
536                         cnt_ready++;
537                 else
538                         cnt_ready = 0;
539
540         } while (cnt_ready < 32);
541
542         /*
543          * ... Write the MDM-AP control register to set the Flash Mass
544          * Erase in Progress bit. This will start the mass erase
545          * process...
546          */
547         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, MDM_CTRL_SYS_RES_REQ | MDM_CTRL_FMEIP);
548         if (retval != ERROR_OK) {
549                 LOG_ERROR("MDM: failed to start mass erase");
550                 goto deassert_reset_and_exit;
551         }
552
553         /*
554          * ... Read the MDM-AP control register until the Flash Mass
555          * Erase in Progress bit clears...
556          * Data sheed defines erase time <3.6 sec/512kB flash block.
557          * The biggest device has 4 pflash blocks => timeout 16 sec.
558          */
559         retval = kinetis_mdm_poll_register(dap, MDM_REG_CTRL, MDM_CTRL_FMEIP, 0, 16000);
560         if (retval != ERROR_OK) {
561                 LOG_ERROR("MDM: mass erase timeout");
562                 goto deassert_reset_and_exit;
563         }
564
565         target_poll(target);
566         /* enable polling in case kinetis_check_flash_security_status disabled it */
567         jtag_poll_set_enabled(true);
568
569         alive_sleep(100);
570
571         target->reset_halt = true;
572         target->type->assert_reset(target);
573
574         /*
575          * ... Negate the RESET signal or clear the System Reset Request
576          * bit in the MDM-AP control register.
577          */
578         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
579         if (retval != ERROR_OK)
580                 LOG_ERROR("MDM: failed to clear MDM_REG_CTRL");
581
582         target->type->deassert_reset(target);
583
584         return retval;
585
586 deassert_reset_and_exit:
587         kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
588         if (has_srst)
589                 adapter_deassert_reset();
590         return retval;
591 }
592
593 static const uint32_t kinetis_known_mdm_ids[] = {
594         0x001C0000,     /* Kinetis-K Series */
595         0x001C0020,     /* Kinetis-L/M/V/E Series */
596 };
597
598 /*
599  * This function implements the procedure to connect to
600  * SWD/JTAG on Kinetis K and L series of devices as it is described in
601  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
602  * and L-series MCUs" Section 4.1.1
603  */
604 COMMAND_HANDLER(kinetis_check_flash_security_status)
605 {
606         struct target *target = get_current_target(CMD_CTX);
607         struct cortex_m_common *cortex_m = target_to_cm(target);
608         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
609
610         if (!dap) {
611                 LOG_WARNING("Cannot check flash security status with a high-level adapter");
612                 return ERROR_OK;
613         }
614
615         if (!dap->ops)
616                 return ERROR_OK;        /* too early to check, in JTAG mode ops may not be initialised */
617
618         uint32_t val;
619         int retval;
620
621         /*
622          * ... The MDM-AP ID register can be read to verify that the
623          * connection is working correctly...
624          */
625         retval = kinetis_mdm_read_register(dap, MDM_REG_ID, &val);
626         if (retval != ERROR_OK) {
627                 LOG_ERROR("MDM: failed to read ID register");
628                 return ERROR_OK;
629         }
630
631         if (val == 0)
632                 return ERROR_OK;        /* dap not yet initialised */
633
634         bool found = false;
635         for (size_t i = 0; i < ARRAY_SIZE(kinetis_known_mdm_ids); i++) {
636                 if (val == kinetis_known_mdm_ids[i]) {
637                         found = true;
638                         break;
639                 }
640         }
641
642         if (!found)
643                 LOG_WARNING("MDM: unknown ID %08" PRIX32, val);
644
645         /*
646          * ... Read the System Security bit to determine if security is enabled.
647          * If System Security = 0, then proceed. If System Security = 1, then
648          * communication with the internals of the processor, including the
649          * flash, will not be possible without issuing a mass erase command or
650          * unsecuring the part through other means (backdoor key unlock)...
651          */
652         retval = kinetis_mdm_read_register(dap, MDM_REG_STAT, &val);
653         if (retval != ERROR_OK) {
654                 LOG_ERROR("MDM: failed to read MDM_REG_STAT");
655                 return ERROR_OK;
656         }
657
658         /*
659          * System Security bit is also active for short time during reset.
660          * If a MCU has blank flash and runs in RESET/WDOG loop,
661          * System Security bit is active most of time!
662          * We should observe Flash Ready bit and read status several times
663          * to avoid false detection of secured MCU
664          */
665         int secured_score = 0, flash_not_ready_score = 0;
666
667         if ((val & (MDM_STAT_SYSSEC | MDM_STAT_FREADY)) != MDM_STAT_FREADY) {
668                 uint32_t stats[32];
669                 int i;
670
671                 for (i = 0; i < 32; i++) {
672                         stats[i] = MDM_STAT_FREADY;
673                         dap_queue_ap_read(dap_ap(dap, MDM_AP), MDM_REG_STAT, &stats[i]);
674                 }
675                 retval = dap_run(dap);
676                 if (retval != ERROR_OK) {
677                         LOG_DEBUG("MDM: dap_run failed when validating secured state");
678                         return ERROR_OK;
679                 }
680                 for (i = 0; i < 32; i++) {
681                         if (stats[i] & MDM_STAT_SYSSEC)
682                                 secured_score++;
683                         if (!(stats[i] & MDM_STAT_FREADY))
684                                 flash_not_ready_score++;
685                 }
686         }
687
688         if (flash_not_ready_score <= 8 && secured_score > 24) {
689                 jtag_poll_set_enabled(false);
690
691                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
692                 LOG_WARNING("****                                                          ****");
693                 LOG_WARNING("**** Your Kinetis MCU is in secured state, which means that,  ****");
694                 LOG_WARNING("**** with exception for very basic communication, JTAG/SWD    ****");
695                 LOG_WARNING("**** interface will NOT work. In order to restore its         ****");
696                 LOG_WARNING("**** functionality please issue 'kinetis mdm mass_erase'      ****");
697                 LOG_WARNING("**** command, power cycle the MCU and restart OpenOCD.        ****");
698                 LOG_WARNING("****                                                          ****");
699                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
700
701         } else if (flash_not_ready_score > 24) {
702                 jtag_poll_set_enabled(false);
703                 LOG_WARNING("**** Your Kinetis MCU is probably locked-up in RESET/WDOG loop. ****");
704                 LOG_WARNING("**** Common reason is a blank flash (at least a reset vector).  ****");
705                 LOG_WARNING("**** Issue 'kinetis mdm halt' command or if SRST is connected   ****");
706                 LOG_WARNING("**** and configured, use 'reset halt'                           ****");
707                 LOG_WARNING("**** If MCU cannot be halted, it is likely secured and running  ****");
708                 LOG_WARNING("**** in RESET/WDOG loop. Issue 'kinetis mdm mass_erase'         ****");
709
710         } else {
711                 LOG_INFO("MDM: Chip is unsecured. Continuing.");
712                 jtag_poll_set_enabled(true);
713         }
714
715         return ERROR_OK;
716 }
717
718 FLASH_BANK_COMMAND_HANDLER(kinetis_flash_bank_command)
719 {
720         struct kinetis_flash_bank *bank_info;
721
722         if (CMD_ARGC < 6)
723                 return ERROR_COMMAND_SYNTAX_ERROR;
724
725         LOG_INFO("add flash_bank kinetis %s", bank->name);
726
727         bank_info = malloc(sizeof(struct kinetis_flash_bank));
728
729         memset(bank_info, 0, sizeof(struct kinetis_flash_bank));
730
731         bank->driver_priv = bank_info;
732
733         return ERROR_OK;
734 }
735
736 /* Disable the watchdog on Kinetis devices */
737 int kinetis_disable_wdog(struct target *target, uint32_t sim_sdid)
738 {
739         struct working_area *wdog_algorithm;
740         struct armv7m_algorithm armv7m_info;
741         uint16_t wdog;
742         int retval;
743
744         static const uint8_t kinetis_unlock_wdog_code[] = {
745 #include "../../../contrib/loaders/watchdog/armv7m_kinetis_wdog.inc"
746         };
747
748         /* Decide whether the connected device needs watchdog disabling.
749          * Disable for all Kx and KVx devices, return if it is a KLx */
750
751         if ((sim_sdid & KINETIS_SDID_SERIESID_MASK) == KINETIS_SDID_SERIESID_KL)
752                 return ERROR_OK;
753
754         /* The connected device requires watchdog disabling. */
755         retval = target_read_u16(target, WDOG_STCTRH, &wdog);
756         if (retval != ERROR_OK)
757                 return retval;
758
759         if ((wdog & 0x1) == 0) {
760                 /* watchdog already disabled */
761                 return ERROR_OK;
762         }
763         LOG_INFO("Disabling Kinetis watchdog (initial WDOG_STCTRLH = 0x%x)", wdog);
764
765         if (target->state != TARGET_HALTED) {
766                 LOG_ERROR("Target not halted");
767                 return ERROR_TARGET_NOT_HALTED;
768         }
769
770         retval = target_alloc_working_area(target, sizeof(kinetis_unlock_wdog_code), &wdog_algorithm);
771         if (retval != ERROR_OK)
772                 return retval;
773
774         retval = target_write_buffer(target, wdog_algorithm->address,
775                         sizeof(kinetis_unlock_wdog_code), (uint8_t *)kinetis_unlock_wdog_code);
776         if (retval != ERROR_OK) {
777                 target_free_working_area(target, wdog_algorithm);
778                 return retval;
779         }
780
781         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
782         armv7m_info.core_mode = ARM_MODE_THREAD;
783
784         retval = target_run_algorithm(target, 0, NULL, 0, NULL, wdog_algorithm->address,
785                         wdog_algorithm->address + (sizeof(kinetis_unlock_wdog_code) - 2),
786                         10000, &armv7m_info);
787
788         if (retval != ERROR_OK)
789                 LOG_ERROR("error executing kinetis wdog unlock algorithm");
790
791         retval = target_read_u16(target, WDOG_STCTRH, &wdog);
792         if (retval != ERROR_OK)
793                 return retval;
794         LOG_INFO("WDOG_STCTRLH = 0x%x", wdog);
795
796         target_free_working_area(target, wdog_algorithm);
797
798         return retval;
799 }
800
801 COMMAND_HANDLER(kinetis_disable_wdog_handler)
802 {
803         int result;
804         uint32_t sim_sdid;
805         struct target *target = get_current_target(CMD_CTX);
806
807         if (CMD_ARGC > 0)
808                 return ERROR_COMMAND_SYNTAX_ERROR;
809
810         result = target_read_u32(target, SIM_SDID, &sim_sdid);
811         if (result != ERROR_OK) {
812                 LOG_ERROR("Failed to read SIMSDID");
813                 return result;
814         }
815
816         result = kinetis_disable_wdog(target, sim_sdid);
817         return result;
818 }
819
820
821 static int kinetis_ftfx_decode_error(uint8_t fstat)
822 {
823         if (fstat & 0x20) {
824                 LOG_ERROR("Flash operation failed, illegal command");
825                 return ERROR_FLASH_OPER_UNSUPPORTED;
826
827         } else if (fstat & 0x10)
828                 LOG_ERROR("Flash operation failed, protection violated");
829
830         else if (fstat & 0x40)
831                 LOG_ERROR("Flash operation failed, read collision");
832
833         else if (fstat & 0x80)
834                 return ERROR_OK;
835
836         else
837                 LOG_ERROR("Flash operation timed out");
838
839         return ERROR_FLASH_OPERATION_FAILED;
840 }
841
842
843 static int kinetis_ftfx_prepare(struct target *target)
844 {
845         int result, i;
846         uint8_t fstat;
847
848         /* wait until busy */
849         for (i = 0; i < 50; i++) {
850                 result = target_read_u8(target, FTFx_FSTAT, &fstat);
851                 if (result != ERROR_OK)
852                         return result;
853
854                 if (fstat & 0x80)
855                         break;
856         }
857
858         if ((fstat & 0x80) == 0) {
859                 LOG_ERROR("Flash controller is busy");
860                 return ERROR_FLASH_OPERATION_FAILED;
861         }
862         if (fstat != 0x80) {
863                 /* reset error flags */
864                 result = target_write_u8(target, FTFx_FSTAT, 0x70);
865         }
866         return result;
867 }
868
869 /* Kinetis Program-LongWord Microcodes */
870 static const uint8_t kinetis_flash_write_code[] = {
871 #include "../../../contrib/loaders/flash/kinetis/kinetis_flash.inc"
872 };
873
874 /* Program LongWord Block Write */
875 static int kinetis_write_block(struct flash_bank *bank, const uint8_t *buffer,
876                 uint32_t offset, uint32_t wcount)
877 {
878         struct target *target = bank->target;
879         uint32_t buffer_size = 2048;            /* Default minimum value */
880         struct working_area *write_algorithm;
881         struct working_area *source;
882         struct kinetis_flash_bank *kinfo = bank->driver_priv;
883         uint32_t address = kinfo->prog_base + offset;
884         uint32_t end_address;
885         struct reg_param reg_params[5];
886         struct armv7m_algorithm armv7m_info;
887         int retval;
888         uint8_t fstat;
889
890         /* Increase buffer_size if needed */
891         if (buffer_size < (target->working_area_size/2))
892                 buffer_size = (target->working_area_size/2);
893
894         /* allocate working area with flash programming code */
895         if (target_alloc_working_area(target, sizeof(kinetis_flash_write_code),
896                         &write_algorithm) != ERROR_OK) {
897                 LOG_WARNING("no working area available, can't do block memory writes");
898                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
899         }
900
901         retval = target_write_buffer(target, write_algorithm->address,
902                 sizeof(kinetis_flash_write_code), kinetis_flash_write_code);
903         if (retval != ERROR_OK)
904                 return retval;
905
906         /* memory buffer */
907         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK) {
908                 buffer_size /= 4;
909                 if (buffer_size <= 256) {
910                         /* free working area, write algorithm already allocated */
911                         target_free_working_area(target, write_algorithm);
912
913                         LOG_WARNING("No large enough working area available, can't do block memory writes");
914                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
915                 }
916         }
917
918         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
919         armv7m_info.core_mode = ARM_MODE_THREAD;
920
921         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* address */
922         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT); /* word count */
923         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
924         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
925         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);
926
927         buf_set_u32(reg_params[0].value, 0, 32, address);
928         buf_set_u32(reg_params[1].value, 0, 32, wcount);
929         buf_set_u32(reg_params[2].value, 0, 32, source->address);
930         buf_set_u32(reg_params[3].value, 0, 32, source->address + source->size);
931         buf_set_u32(reg_params[4].value, 0, 32, FTFx_FSTAT);
932
933         retval = target_run_flash_async_algorithm(target, buffer, wcount, 4,
934                                                 0, NULL,
935                                                 5, reg_params,
936                                                 source->address, source->size,
937                                                 write_algorithm->address, 0,
938                                                 &armv7m_info);
939
940         if (retval == ERROR_FLASH_OPERATION_FAILED) {
941                 end_address = buf_get_u32(reg_params[0].value, 0, 32);
942
943                 LOG_ERROR("Error writing flash at %08" PRIx32, end_address);
944
945                 retval = target_read_u8(target, FTFx_FSTAT, &fstat);
946                 if (retval == ERROR_OK) {
947                         retval = kinetis_ftfx_decode_error(fstat);
948
949                         /* reset error flags */
950                         target_write_u8(target, FTFx_FSTAT, 0x70);
951                 }
952         } else if (retval != ERROR_OK)
953                 LOG_ERROR("Error executing kinetis Flash programming algorithm");
954
955         target_free_working_area(target, source);
956         target_free_working_area(target, write_algorithm);
957
958         destroy_reg_param(&reg_params[0]);
959         destroy_reg_param(&reg_params[1]);
960         destroy_reg_param(&reg_params[2]);
961         destroy_reg_param(&reg_params[3]);
962         destroy_reg_param(&reg_params[4]);
963
964         return retval;
965 }
966
967 static int kinetis_protect(struct flash_bank *bank, int set, int first, int last)
968 {
969         int i;
970
971         if (allow_fcf_writes) {
972                 LOG_ERROR("Protection setting is possible with 'kinetis fcf_source protection' only!");
973                 return ERROR_FAIL;
974         }
975
976         if (!bank->prot_blocks || bank->num_prot_blocks == 0) {
977                 LOG_ERROR("No protection possible for current bank!");
978                 return ERROR_FLASH_BANK_INVALID;
979         }
980
981         for (i = first; i < bank->num_prot_blocks && i <= last; i++)
982                 bank->prot_blocks[i].is_protected = set;
983
984         LOG_INFO("Protection bits will be written at the next FCF sector erase or write.");
985         LOG_INFO("Do not issue 'flash info' command until protection is written,");
986         LOG_INFO("doing so would re-read protection status from MCU.");
987
988         return ERROR_OK;
989 }
990
991 static int kinetis_protect_check(struct flash_bank *bank)
992 {
993         struct kinetis_flash_bank *kinfo = bank->driver_priv;
994         int result;
995         int i, b;
996         uint32_t fprot;
997
998         if (kinfo->flash_class == FC_PFLASH) {
999
1000                 /* read protection register */
1001                 result = target_read_u32(bank->target, FTFx_FPROT3, &fprot);
1002                 if (result != ERROR_OK)
1003                         return result;
1004
1005                 /* Every bit protects 1/32 of the full flash (not necessarily just this bank) */
1006
1007         } else if (kinfo->flash_class == FC_FLEX_NVM) {
1008                 uint8_t fdprot;
1009
1010                 /* read protection register */
1011                 result = target_read_u8(bank->target, FTFx_FDPROT, &fdprot);
1012                 if (result != ERROR_OK)
1013                         return result;
1014
1015                 fprot = fdprot;
1016
1017         } else {
1018                 LOG_ERROR("Protection checks for FlexRAM not supported");
1019                 return ERROR_FLASH_BANK_INVALID;
1020         }
1021
1022         b = kinfo->protection_block;
1023         for (i = 0; i < bank->num_prot_blocks; i++) {
1024                 if ((fprot >> b) & 1)
1025                         bank->prot_blocks[i].is_protected = 0;
1026                 else
1027                         bank->prot_blocks[i].is_protected = 1;
1028
1029                 b++;
1030         }
1031
1032         return ERROR_OK;
1033 }
1034
1035
1036 static int kinetis_fill_fcf(struct flash_bank *bank, uint8_t *fcf)
1037 {
1038         uint32_t fprot = 0xffffffff;
1039         uint8_t fsec = 0xfe;             /* set MCU unsecure */
1040         uint8_t fdprot = 0xff;
1041         int i;
1042         uint32_t pflash_bit;
1043         uint8_t dflash_bit;
1044         struct flash_bank *bank_iter;
1045         struct kinetis_flash_bank *kinfo;
1046
1047         memset(fcf, 0xff, FCF_SIZE);
1048
1049         pflash_bit = 1;
1050         dflash_bit = 1;
1051
1052         /* iterate over all kinetis banks */
1053         /* current bank is bank 0, it contains FCF */
1054         for (bank_iter = bank; bank_iter; bank_iter = bank_iter->next) {
1055                 if (bank_iter->driver != &kinetis_flash
1056                     || bank_iter->target != bank->target)
1057                         continue;
1058
1059                 kinetis_auto_probe(bank_iter);
1060
1061                 kinfo = bank->driver_priv;
1062                 if (!kinfo)
1063                         continue;
1064
1065                 if (kinfo->flash_class == FC_PFLASH) {
1066                         for (i = 0; i < bank_iter->num_prot_blocks; i++) {
1067                                 if (bank_iter->prot_blocks[i].is_protected == 1)
1068                                         fprot &= ~pflash_bit;
1069
1070                                 pflash_bit <<= 1;
1071                         }
1072
1073                 } else if (kinfo->flash_class == FC_FLEX_NVM) {
1074                         for (i = 0; i < bank_iter->num_prot_blocks; i++) {
1075                                 if (bank_iter->prot_blocks[i].is_protected == 1)
1076                                         fdprot &= ~dflash_bit;
1077
1078                                 dflash_bit <<= 1;
1079                         }
1080
1081                 }
1082         }
1083
1084         target_buffer_set_u32(bank->target, fcf + FCF_FPROT, fprot);
1085         fcf[FCF_FSEC] = fsec;
1086         fcf[FCF_FOPT] = fcf_fopt;
1087         fcf[FCF_FDPROT] = fdprot;
1088         return ERROR_OK;
1089 }
1090
1091 static int kinetis_ftfx_command(struct target *target, uint8_t fcmd, uint32_t faddr,
1092                                 uint8_t fccob4, uint8_t fccob5, uint8_t fccob6, uint8_t fccob7,
1093                                 uint8_t fccob8, uint8_t fccob9, uint8_t fccoba, uint8_t fccobb,
1094                                 uint8_t *ftfx_fstat)
1095 {
1096         uint8_t command[12] = {faddr & 0xff, (faddr >> 8) & 0xff, (faddr >> 16) & 0xff, fcmd,
1097                         fccob7, fccob6, fccob5, fccob4,
1098                         fccobb, fccoba, fccob9, fccob8};
1099         int result;
1100         uint8_t fstat;
1101         int64_t ms_timeout = timeval_ms() + 250;
1102
1103         result = target_write_memory(target, FTFx_FCCOB3, 4, 3, command);
1104         if (result != ERROR_OK)
1105                 return result;
1106
1107         /* start command */
1108         result = target_write_u8(target, FTFx_FSTAT, 0x80);
1109         if (result != ERROR_OK)
1110                 return result;
1111
1112         /* wait for done */
1113         do {
1114                 result = target_read_u8(target, FTFx_FSTAT, &fstat);
1115
1116                 if (result != ERROR_OK)
1117                         return result;
1118
1119                 if (fstat & 0x80)
1120                         break;
1121
1122         } while (timeval_ms() < ms_timeout);
1123
1124         if (ftfx_fstat)
1125                 *ftfx_fstat = fstat;
1126
1127         if ((fstat & 0xf0) != 0x80) {
1128                 LOG_DEBUG("ftfx command failed FSTAT: %02X FCCOB: %02X%02X%02X%02X %02X%02X%02X%02X %02X%02X%02X%02X",
1129                          fstat, command[3], command[2], command[1], command[0],
1130                          command[7], command[6], command[5], command[4],
1131                          command[11], command[10], command[9], command[8]);
1132
1133                 return kinetis_ftfx_decode_error(fstat);
1134         }
1135
1136         return ERROR_OK;
1137 }
1138
1139
1140 static int kinetis_check_run_mode(struct target *target)
1141 {
1142         int result, i;
1143         uint8_t pmctrl, pmstat;
1144
1145         if (target->state != TARGET_HALTED) {
1146                 LOG_ERROR("Target not halted");
1147                 return ERROR_TARGET_NOT_HALTED;
1148         }
1149
1150         result = target_read_u8(target, SMC_PMSTAT, &pmstat);
1151         if (result != ERROR_OK)
1152                 return result;
1153
1154         if (pmstat == PM_STAT_RUN)
1155                 return ERROR_OK;
1156
1157         if (pmstat == PM_STAT_VLPR) {
1158                 /* It is safe to switch from VLPR to RUN mode without changing clock */
1159                 LOG_INFO("Switching from VLPR to RUN mode.");
1160                 pmctrl = PM_CTRL_RUNM_RUN;
1161                 result = target_write_u8(target, SMC_PMCTRL, pmctrl);
1162                 if (result != ERROR_OK)
1163                         return result;
1164
1165                 for (i = 100; i; i--) {
1166                         result = target_read_u8(target, SMC_PMSTAT, &pmstat);
1167                         if (result != ERROR_OK)
1168                                 return result;
1169
1170                         if (pmstat == PM_STAT_RUN)
1171                                 return ERROR_OK;
1172                 }
1173         }
1174
1175         LOG_ERROR("Flash operation not possible in current run mode: SMC_PMSTAT: 0x%x", pmstat);
1176         LOG_ERROR("Issue a 'reset init' command.");
1177         return ERROR_TARGET_NOT_HALTED;
1178 }
1179
1180
1181 static void kinetis_invalidate_flash_cache(struct flash_bank *bank)
1182 {
1183         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1184
1185         if (kinfo->flash_support & FS_INVALIDATE_CACHE_K)
1186                 target_write_u8(bank->target, FMC_PFB01CR + 2, 0xf0);
1187
1188         else if (kinfo->flash_support & FS_INVALIDATE_CACHE_L)
1189                 target_write_u8(bank->target, MCM_PLACR + 1, 0x04);
1190
1191         return;
1192 }
1193
1194
1195 static int kinetis_erase(struct flash_bank *bank, int first, int last)
1196 {
1197         int result, i;
1198         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1199
1200         result = kinetis_check_run_mode(bank->target);
1201         if (result != ERROR_OK)
1202                 return result;
1203
1204         /* reset error flags */
1205         result = kinetis_ftfx_prepare(bank->target);
1206         if (result != ERROR_OK)
1207                 return result;
1208
1209         if ((first > bank->num_sectors) || (last > bank->num_sectors))
1210                 return ERROR_FLASH_OPERATION_FAILED;
1211
1212         /*
1213          * FIXME: TODO: use the 'Erase Flash Block' command if the
1214          * requested erase is PFlash or NVM and encompasses the entire
1215          * block.  Should be quicker.
1216          */
1217         for (i = first; i <= last; i++) {
1218                 /* set command and sector address */
1219                 result = kinetis_ftfx_command(bank->target, FTFx_CMD_SECTERASE, kinfo->prog_base + bank->sectors[i].offset,
1220                                 0, 0, 0, 0,  0, 0, 0, 0,  NULL);
1221
1222                 if (result != ERROR_OK) {
1223                         LOG_WARNING("erase sector %d failed", i);
1224                         return ERROR_FLASH_OPERATION_FAILED;
1225                 }
1226
1227                 bank->sectors[i].is_erased = 1;
1228
1229                 if (bank->base == 0
1230                         && bank->sectors[i].offset <= FCF_ADDRESS
1231                         && bank->sectors[i].offset + bank->sectors[i].size > FCF_ADDRESS + FCF_SIZE) {
1232                         if (allow_fcf_writes) {
1233                                 LOG_WARNING("Flash Configuration Field erased, DO NOT reset or power off the device");
1234                                 LOG_WARNING("until correct FCF is programmed or MCU gets security lock.");
1235                         } else {
1236                                 uint8_t fcf_buffer[FCF_SIZE];
1237
1238                                 kinetis_fill_fcf(bank, fcf_buffer);
1239                                 result = kinetis_write_inner(bank, fcf_buffer, FCF_ADDRESS, FCF_SIZE);
1240                                 if (result != ERROR_OK)
1241                                         LOG_WARNING("Flash Configuration Field write failed");
1242                                 bank->sectors[i].is_erased = 0;
1243                         }
1244                 }
1245         }
1246
1247         kinetis_invalidate_flash_cache(bank);
1248
1249         return ERROR_OK;
1250 }
1251
1252 static int kinetis_make_ram_ready(struct target *target)
1253 {
1254         int result;
1255         uint8_t ftfx_fcnfg;
1256
1257         /* check if ram ready */
1258         result = target_read_u8(target, FTFx_FCNFG, &ftfx_fcnfg);
1259         if (result != ERROR_OK)
1260                 return result;
1261
1262         if (ftfx_fcnfg & (1 << 1))
1263                 return ERROR_OK;        /* ram ready */
1264
1265         /* make flex ram available */
1266         result = kinetis_ftfx_command(target, FTFx_CMD_SETFLEXRAM, 0x00ff0000,
1267                                  0, 0, 0, 0,  0, 0, 0, 0,  NULL);
1268         if (result != ERROR_OK)
1269                 return ERROR_FLASH_OPERATION_FAILED;
1270
1271         /* check again */
1272         result = target_read_u8(target, FTFx_FCNFG, &ftfx_fcnfg);
1273         if (result != ERROR_OK)
1274                 return result;
1275
1276         if (ftfx_fcnfg & (1 << 1))
1277                 return ERROR_OK;        /* ram ready */
1278
1279         return ERROR_FLASH_OPERATION_FAILED;
1280 }
1281
1282
1283 static int kinetis_write_sections(struct flash_bank *bank, const uint8_t *buffer,
1284                          uint32_t offset, uint32_t count)
1285 {
1286         int result = ERROR_OK;
1287         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1288         uint8_t *buffer_aligned = NULL;
1289         /*
1290          * Kinetis uses different terms for the granularity of
1291          * sector writes, e.g. "phrase" or "128 bits".  We use
1292          * the generic term "chunk". The largest possible
1293          * Kinetis "chunk" is 16 bytes (128 bits).
1294          */
1295         uint32_t prog_section_chunk_bytes = kinfo->sector_size >> 8;
1296         uint32_t prog_size_bytes = kinfo->max_flash_prog_size;
1297
1298         while (count > 0) {
1299                 uint32_t size = prog_size_bytes - offset % prog_size_bytes;
1300                 uint32_t align_begin = offset % prog_section_chunk_bytes;
1301                 uint32_t align_end;
1302                 uint32_t size_aligned;
1303                 uint16_t chunk_count;
1304                 uint8_t ftfx_fstat;
1305
1306                 if (size > count)
1307                         size = count;
1308
1309                 align_end = (align_begin + size) % prog_section_chunk_bytes;
1310                 if (align_end)
1311                         align_end = prog_section_chunk_bytes - align_end;
1312
1313                 size_aligned = align_begin + size + align_end;
1314                 chunk_count = size_aligned / prog_section_chunk_bytes;
1315
1316                 if (size != size_aligned) {
1317                         /* aligned section: the first, the last or the only */
1318                         if (!buffer_aligned)
1319                                 buffer_aligned = malloc(prog_size_bytes);
1320
1321                         memset(buffer_aligned, 0xff, size_aligned);
1322                         memcpy(buffer_aligned + align_begin, buffer, size);
1323
1324                         result = target_write_memory(bank->target, FLEXRAM,
1325                                                 4, size_aligned / 4, buffer_aligned);
1326
1327                         LOG_DEBUG("section @ %08" PRIx32 " aligned begin %" PRIu32 ", end %" PRIu32,
1328                                         bank->base + offset, align_begin, align_end);
1329                 } else
1330                         result = target_write_memory(bank->target, FLEXRAM,
1331                                                 4, size_aligned / 4, buffer);
1332
1333                 LOG_DEBUG("write section @ %08" PRIx32 " with length %" PRIu32 " bytes",
1334                           bank->base + offset, size);
1335
1336                 if (result != ERROR_OK) {
1337                         LOG_ERROR("target_write_memory failed");
1338                         break;
1339                 }
1340
1341                 /* execute section-write command */
1342                 result = kinetis_ftfx_command(bank->target, FTFx_CMD_SECTWRITE,
1343                                 kinfo->prog_base + offset - align_begin,
1344                                 chunk_count>>8, chunk_count, 0, 0,
1345                                 0, 0, 0, 0,  &ftfx_fstat);
1346
1347                 if (result != ERROR_OK) {
1348                         LOG_ERROR("Error writing section at %08" PRIx32, bank->base + offset);
1349                         break;
1350                 }
1351
1352                 if (ftfx_fstat & 0x01)
1353                         LOG_ERROR("Flash write error at %08" PRIx32, bank->base + offset);
1354
1355                 buffer += size;
1356                 offset += size;
1357                 count -= size;
1358         }
1359
1360         free(buffer_aligned);
1361         return result;
1362 }
1363
1364
1365 static int kinetis_write_inner(struct flash_bank *bank, const uint8_t *buffer,
1366                          uint32_t offset, uint32_t count)
1367 {
1368         int result, fallback = 0;
1369         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1370
1371         if (!(kinfo->flash_support & FS_PROGRAM_SECTOR)) {
1372                 /* fallback to longword write */
1373                 fallback = 1;
1374                 LOG_INFO("This device supports Program Longword execution only.");
1375         } else {
1376                 result = kinetis_make_ram_ready(bank->target);
1377                 if (result != ERROR_OK) {
1378                         fallback = 1;
1379                         LOG_WARNING("FlexRAM not ready, fallback to slow longword write.");
1380                 }
1381         }
1382
1383         LOG_DEBUG("flash write @08%" PRIx32, bank->base + offset);
1384
1385         if (fallback == 0) {
1386                 /* program section command */
1387                 kinetis_write_sections(bank, buffer, offset, count);
1388         }
1389         else if (kinfo->flash_support & FS_PROGRAM_LONGWORD) {
1390                 /* program longword command, not supported in FTFE */
1391                 uint8_t *new_buffer = NULL;
1392
1393                 /* check word alignment */
1394                 if (offset & 0x3) {
1395                         LOG_ERROR("offset 0x%" PRIx32 " breaks the required alignment", offset);
1396                         return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
1397                 }
1398
1399                 if (count & 0x3) {
1400                         uint32_t old_count = count;
1401                         count = (old_count | 3) + 1;
1402                         new_buffer = malloc(count);
1403                         if (new_buffer == NULL) {
1404                                 LOG_ERROR("odd number of bytes to write and no memory "
1405                                         "for padding buffer");
1406                                 return ERROR_FAIL;
1407                         }
1408                         LOG_INFO("odd number of bytes to write (%" PRIu32 "), extending to %" PRIu32 " "
1409                                 "and padding with 0xff", old_count, count);
1410                         memset(new_buffer + old_count, 0xff, count - old_count);
1411                         buffer = memcpy(new_buffer, buffer, old_count);
1412                 }
1413
1414                 uint32_t words_remaining = count / 4;
1415
1416                 kinetis_disable_wdog(bank->target, kinfo->sim_sdid);
1417
1418                 /* try using a block write */
1419                 result = kinetis_write_block(bank, buffer, offset, words_remaining);
1420
1421                 if (result == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
1422                         /* if block write failed (no sufficient working area),
1423                          * we use normal (slow) single word accesses */
1424                         LOG_WARNING("couldn't use block writes, falling back to single "
1425                                 "memory accesses");
1426
1427                         while (words_remaining) {
1428                                 uint8_t ftfx_fstat;
1429
1430                                 LOG_DEBUG("write longword @ %08" PRIx32, (uint32_t)(bank->base + offset));
1431
1432                                 result = kinetis_ftfx_command(bank->target, FTFx_CMD_LWORDPROG, kinfo->prog_base + offset,
1433                                                 buffer[3], buffer[2], buffer[1], buffer[0],
1434                                                 0, 0, 0, 0,  &ftfx_fstat);
1435
1436                                 if (result != ERROR_OK) {
1437                                         LOG_ERROR("Error writing longword at %08" PRIx32, bank->base + offset);
1438                                         break;
1439                                 }
1440
1441                                 if (ftfx_fstat & 0x01)
1442                                         LOG_ERROR("Flash write error at %08" PRIx32, bank->base + offset);
1443
1444                                 buffer += 4;
1445                                 offset += 4;
1446                                 words_remaining--;
1447                         }
1448                 }
1449                 free(new_buffer);
1450         } else {
1451                 LOG_ERROR("Flash write strategy not implemented");
1452                 return ERROR_FLASH_OPERATION_FAILED;
1453         }
1454
1455         kinetis_invalidate_flash_cache(bank);
1456         return result;
1457 }
1458
1459
1460 static int kinetis_write(struct flash_bank *bank, const uint8_t *buffer,
1461                          uint32_t offset, uint32_t count)
1462 {
1463         int result;
1464         bool set_fcf = false;
1465         int sect = 0;
1466
1467         result = kinetis_check_run_mode(bank->target);
1468         if (result != ERROR_OK)
1469                 return result;
1470
1471         /* reset error flags */
1472         result = kinetis_ftfx_prepare(bank->target);
1473         if (result != ERROR_OK)
1474                 return result;
1475
1476         if (bank->base == 0 && !allow_fcf_writes) {
1477                 if (bank->sectors[1].offset <= FCF_ADDRESS)
1478                         sect = 1;       /* 1kb sector, FCF in 2nd sector */
1479
1480                 if (offset < bank->sectors[sect].offset + bank->sectors[sect].size
1481                         && offset + count > bank->sectors[sect].offset)
1482                         set_fcf = true; /* write to any part of sector with FCF */
1483         }
1484
1485         if (set_fcf) {
1486                 uint8_t fcf_buffer[FCF_SIZE];
1487                 uint8_t fcf_current[FCF_SIZE];
1488
1489                 kinetis_fill_fcf(bank, fcf_buffer);
1490
1491                 if (offset < FCF_ADDRESS) {
1492                         /* write part preceding FCF */
1493                         result = kinetis_write_inner(bank, buffer, offset, FCF_ADDRESS - offset);
1494                         if (result != ERROR_OK)
1495                                 return result;
1496                 }
1497
1498                 result = target_read_memory(bank->target, FCF_ADDRESS, 4, FCF_SIZE / 4, fcf_current);
1499                 if (result == ERROR_OK && memcmp(fcf_current, fcf_buffer, FCF_SIZE) == 0)
1500                         set_fcf = false;
1501
1502                 if (set_fcf) {
1503                         /* write FCF if differs from flash - eliminate multiple writes */
1504                         result = kinetis_write_inner(bank, fcf_buffer, FCF_ADDRESS, FCF_SIZE);
1505                         if (result != ERROR_OK)
1506                                 return result;
1507                 }
1508
1509                 LOG_WARNING("Flash Configuration Field written.");
1510                 LOG_WARNING("Reset or power off the device to make settings effective.");
1511
1512                 if (offset + count > FCF_ADDRESS + FCF_SIZE) {
1513                         uint32_t delta = FCF_ADDRESS + FCF_SIZE - offset;
1514                         /* write part after FCF */
1515                         result = kinetis_write_inner(bank, buffer + delta, FCF_ADDRESS + FCF_SIZE, count - delta);
1516                 }
1517                 return result;
1518
1519         } else
1520                 /* no FCF fiddling, normal write */
1521                 return kinetis_write_inner(bank, buffer, offset, count);
1522 }
1523
1524
1525 static int kinetis_probe(struct flash_bank *bank)
1526 {
1527         int result, i;
1528         uint8_t fcfg1_nvmsize, fcfg1_pfsize, fcfg1_eesize, fcfg1_depart;
1529         uint8_t fcfg2_maxaddr0, fcfg2_pflsh, fcfg2_maxaddr1;
1530         uint32_t nvm_size = 0, pf_size = 0, df_size = 0, ee_size = 0;
1531         unsigned num_blocks = 0, num_pflash_blocks = 0, num_nvm_blocks = 0, first_nvm_bank = 0,
1532                         pflash_sector_size_bytes = 0, nvm_sector_size_bytes = 0;
1533         struct target *target = bank->target;
1534         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1535
1536         kinfo->probed = false;
1537
1538         result = target_read_u32(target, SIM_SDID, &kinfo->sim_sdid);
1539         if (result != ERROR_OK)
1540                 return result;
1541
1542         if ((kinfo->sim_sdid & (~KINETIS_SDID_K_SERIES_MASK)) == 0) {
1543                 /* older K-series MCU */
1544                 uint32_t mcu_type = kinfo->sim_sdid & KINETIS_K_SDID_TYPE_MASK;
1545
1546                 switch (mcu_type) {
1547                 case KINETIS_K_SDID_K10_M50:
1548                 case KINETIS_K_SDID_K20_M50:
1549                         /* 1kB sectors */
1550                         pflash_sector_size_bytes = 1<<10;
1551                         nvm_sector_size_bytes = 1<<10;
1552                         num_blocks = 2;
1553                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR | FS_INVALIDATE_CACHE_K;
1554                         break;
1555                 case KINETIS_K_SDID_K10_M72:
1556                 case KINETIS_K_SDID_K20_M72:
1557                 case KINETIS_K_SDID_K30_M72:
1558                 case KINETIS_K_SDID_K30_M100:
1559                 case KINETIS_K_SDID_K40_M72:
1560                 case KINETIS_K_SDID_K40_M100:
1561                 case KINETIS_K_SDID_K50_M72:
1562                         /* 2kB sectors, 1kB FlexNVM sectors */
1563                         pflash_sector_size_bytes = 2<<10;
1564                         nvm_sector_size_bytes = 1<<10;
1565                         num_blocks = 2;
1566                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR | FS_INVALIDATE_CACHE_K;
1567                         kinfo->max_flash_prog_size = 1<<10;
1568                         break;
1569                 case KINETIS_K_SDID_K10_M100:
1570                 case KINETIS_K_SDID_K20_M100:
1571                 case KINETIS_K_SDID_K11:
1572                 case KINETIS_K_SDID_K12:
1573                 case KINETIS_K_SDID_K21_M50:
1574                 case KINETIS_K_SDID_K22_M50:
1575                 case KINETIS_K_SDID_K51_M72:
1576                 case KINETIS_K_SDID_K53:
1577                 case KINETIS_K_SDID_K60_M100:
1578                         /* 2kB sectors */
1579                         pflash_sector_size_bytes = 2<<10;
1580                         nvm_sector_size_bytes = 2<<10;
1581                         num_blocks = 2;
1582                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR | FS_INVALIDATE_CACHE_K;
1583                         break;
1584                 case KINETIS_K_SDID_K21_M120:
1585                 case KINETIS_K_SDID_K22_M120:
1586                         /* 4kB sectors (MK21FN1M0, MK21FX512, MK22FN1M0, MK22FX512) */
1587                         pflash_sector_size_bytes = 4<<10;
1588                         kinfo->max_flash_prog_size = 1<<10;
1589                         nvm_sector_size_bytes = 4<<10;
1590                         num_blocks = 2;
1591                         kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR | FS_INVALIDATE_CACHE_K;
1592                         break;
1593                 case KINETIS_K_SDID_K10_M120:
1594                 case KINETIS_K_SDID_K20_M120:
1595                 case KINETIS_K_SDID_K60_M150:
1596                 case KINETIS_K_SDID_K70_M150:
1597                         /* 4kB sectors */
1598                         pflash_sector_size_bytes = 4<<10;
1599                         nvm_sector_size_bytes = 4<<10;
1600                         num_blocks = 4;
1601                         kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR | FS_INVALIDATE_CACHE_K;
1602                         break;
1603                 default:
1604                         LOG_ERROR("Unsupported K-family FAMID");
1605                 }
1606         } else {
1607                 /* Newer K-series or KL series MCU */
1608                 switch (kinfo->sim_sdid & KINETIS_SDID_SERIESID_MASK) {
1609                 case KINETIS_SDID_SERIESID_K:
1610                         switch (kinfo->sim_sdid & (KINETIS_SDID_FAMILYID_MASK | KINETIS_SDID_SUBFAMID_MASK)) {
1611                         case KINETIS_SDID_FAMILYID_K0X | KINETIS_SDID_SUBFAMID_KX2:
1612                                 /* K02FN64, K02FN128: FTFA, 2kB sectors */
1613                                 pflash_sector_size_bytes = 2<<10;
1614                                 num_blocks = 1;
1615                                 kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_INVALIDATE_CACHE_K;
1616                                 break;
1617
1618                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX2: {
1619                                 /* MK24FN1M reports as K22, this should detect it (according to errata note 1N83J) */
1620                                 uint32_t sopt1;
1621                                 result = target_read_u32(target, SIM_SOPT1, &sopt1);
1622                                 if (result != ERROR_OK)
1623                                         return result;
1624
1625                                 if (((kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K24FN1M) &&
1626                                                 ((sopt1 & KINETIS_SOPT1_RAMSIZE_MASK) == KINETIS_SOPT1_RAMSIZE_K24FN1M)) {
1627                                         /* MK24FN1M */
1628                                         pflash_sector_size_bytes = 4<<10;
1629                                         num_blocks = 2;
1630                                         kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR | FS_INVALIDATE_CACHE_K;
1631                                         kinfo->max_flash_prog_size = 1<<10;
1632                                         break;
1633                                 }
1634                                 if ((kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K22FN128
1635                                         || (kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K22FN256
1636                                         || (kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K22FN512) {
1637                                         /* K22 with new-style SDID - smaller pflash with FTFA, 2kB sectors */
1638                                         pflash_sector_size_bytes = 2<<10;
1639                                         /* autodetect 1 or 2 blocks */
1640                                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_INVALIDATE_CACHE_K;
1641                                         break;
1642                                 }
1643                                 LOG_ERROR("Unsupported Kinetis K22 DIEID");
1644                                 break;
1645                         }
1646                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX4:
1647                                 pflash_sector_size_bytes = 4<<10;
1648                                 if ((kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K24FN256) {
1649                                         /* K24FN256 - smaller pflash with FTFA */
1650                                         num_blocks = 1;
1651                                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_INVALIDATE_CACHE_K;
1652                                         break;
1653                                 }
1654                                 /* K24FN1M without errata 7534 */
1655                                 num_blocks = 2;
1656                                 kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR | FS_INVALIDATE_CACHE_K;
1657                                 kinfo->max_flash_prog_size = 1<<10;
1658                                 break;
1659
1660                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX3:
1661                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX1:     /* errata 7534 - should be K63 */
1662                                 /* K63FN1M0 */
1663                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX4:
1664                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX2:     /* errata 7534 - should be K64 */
1665                                 /* K64FN1M0, K64FX512 */
1666                                 pflash_sector_size_bytes = 4<<10;
1667                                 nvm_sector_size_bytes = 4<<10;
1668                                 kinfo->max_flash_prog_size = 1<<10;
1669                                 num_blocks = 2;
1670                                 kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR | FS_INVALIDATE_CACHE_K;
1671                                 break;
1672
1673                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX6:
1674                                 /* K26FN2M0 */
1675                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX6:
1676                                 /* K66FN2M0, K66FX1M0 */
1677                                 pflash_sector_size_bytes = 4<<10;
1678                                 nvm_sector_size_bytes = 4<<10;
1679                                 kinfo->max_flash_prog_size = 1<<10;
1680                                 num_blocks = 4;
1681                                 kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR | FS_INVALIDATE_CACHE_K;
1682                                 break;
1683
1684                         case KINETIS_SDID_FAMILYID_K8X | KINETIS_SDID_SUBFAMID_KX0:
1685                         case KINETIS_SDID_FAMILYID_K8X | KINETIS_SDID_SUBFAMID_KX1:
1686                         case KINETIS_SDID_FAMILYID_K8X | KINETIS_SDID_SUBFAMID_KX2:
1687                                 /* K80FN256, K81FN256, K82FN256 */
1688                                 pflash_sector_size_bytes = 4<<10;
1689                                 num_blocks = 1;
1690                                 kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_INVALIDATE_CACHE_K;
1691                                 break;
1692
1693                         default:
1694                                 LOG_ERROR("Unsupported Kinetis FAMILYID SUBFAMID");
1695                         }
1696                         break;
1697
1698                 case KINETIS_SDID_SERIESID_KL:
1699                         /* KL-series */
1700                         pflash_sector_size_bytes = 1<<10;
1701                         nvm_sector_size_bytes = 1<<10;
1702                         /* autodetect 1 or 2 blocks */
1703                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_INVALIDATE_CACHE_L;
1704                         break;
1705
1706                 case KINETIS_SDID_SERIESID_KV:
1707                         /* KV-series */
1708                         switch (kinfo->sim_sdid & (KINETIS_SDID_FAMILYID_MASK | KINETIS_SDID_SUBFAMID_MASK)) {
1709                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX0:
1710                                 /* KV10: FTFA, 1kB sectors */
1711                                 pflash_sector_size_bytes = 1<<10;
1712                                 num_blocks = 1;
1713                                 kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_INVALIDATE_CACHE_L;
1714                                 break;
1715
1716                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX1:
1717                                 /* KV11: FTFA, 2kB sectors */
1718                                 pflash_sector_size_bytes = 2<<10;
1719                                 num_blocks = 1;
1720                                 kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_INVALIDATE_CACHE_L;
1721                                 break;
1722
1723                         case KINETIS_SDID_FAMILYID_K3X | KINETIS_SDID_SUBFAMID_KX0:
1724                                 /* KV30: FTFA, 2kB sectors, 1 block */
1725                         case KINETIS_SDID_FAMILYID_K3X | KINETIS_SDID_SUBFAMID_KX1:
1726                                 /* KV31: FTFA, 2kB sectors, 2 blocks */
1727                                 pflash_sector_size_bytes = 2<<10;
1728                                 /* autodetect 1 or 2 blocks */
1729                                 kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_INVALIDATE_CACHE_K;
1730                                 break;
1731
1732                         case KINETIS_SDID_FAMILYID_K4X | KINETIS_SDID_SUBFAMID_KX2:
1733                         case KINETIS_SDID_FAMILYID_K4X | KINETIS_SDID_SUBFAMID_KX4:
1734                         case KINETIS_SDID_FAMILYID_K4X | KINETIS_SDID_SUBFAMID_KX6:
1735                                 /* KV4x: FTFA, 4kB sectors */
1736                                 pflash_sector_size_bytes = 4<<10;
1737                                 num_blocks = 1;
1738                                 kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_INVALIDATE_CACHE_K;
1739                                 break;
1740
1741                         default:
1742                                 LOG_ERROR("Unsupported KV FAMILYID SUBFAMID");
1743                         }
1744                         break;
1745
1746                 default:
1747                         LOG_ERROR("Unsupported K-series");
1748                 }
1749         }
1750
1751         if (pflash_sector_size_bytes == 0) {
1752                 LOG_ERROR("MCU is unsupported, SDID 0x%08" PRIx32, kinfo->sim_sdid);
1753                 return ERROR_FLASH_OPER_UNSUPPORTED;
1754         }
1755
1756         result = target_read_u32(target, SIM_FCFG1, &kinfo->sim_fcfg1);
1757         if (result != ERROR_OK)
1758                 return result;
1759
1760         result = target_read_u32(target, SIM_FCFG2, &kinfo->sim_fcfg2);
1761         if (result != ERROR_OK)
1762                 return result;
1763
1764         LOG_DEBUG("SDID: 0x%08" PRIX32 " FCFG1: 0x%08" PRIX32 " FCFG2: 0x%08" PRIX32, kinfo->sim_sdid,
1765                         kinfo->sim_fcfg1, kinfo->sim_fcfg2);
1766
1767         fcfg1_nvmsize = (uint8_t)((kinfo->sim_fcfg1 >> 28) & 0x0f);
1768         fcfg1_pfsize = (uint8_t)((kinfo->sim_fcfg1 >> 24) & 0x0f);
1769         fcfg1_eesize = (uint8_t)((kinfo->sim_fcfg1 >> 16) & 0x0f);
1770         fcfg1_depart = (uint8_t)((kinfo->sim_fcfg1 >> 8) & 0x0f);
1771
1772         fcfg2_pflsh = (uint8_t)((kinfo->sim_fcfg2 >> 23) & 0x01);
1773         fcfg2_maxaddr0 = (uint8_t)((kinfo->sim_fcfg2 >> 24) & 0x7f);
1774         fcfg2_maxaddr1 = (uint8_t)((kinfo->sim_fcfg2 >> 16) & 0x7f);
1775
1776         if (num_blocks == 0)
1777                 num_blocks = fcfg2_maxaddr1 ? 2 : 1;
1778         else if (fcfg2_maxaddr1 == 0 && num_blocks >= 2) {
1779                 num_blocks = 1;
1780                 LOG_WARNING("MAXADDR1 is zero, number of flash banks adjusted to 1");
1781         } else if (fcfg2_maxaddr1 != 0 && num_blocks == 1) {
1782                 num_blocks = 2;
1783                 LOG_WARNING("MAXADDR1 is non zero, number of flash banks adjusted to 2");
1784         }
1785
1786         /* when the PFLSH bit is set, there is no FlexNVM/FlexRAM */
1787         if (!fcfg2_pflsh) {
1788                 switch (fcfg1_nvmsize) {
1789                 case 0x03:
1790                 case 0x05:
1791                 case 0x07:
1792                 case 0x09:
1793                 case 0x0b:
1794                         nvm_size = 1 << (14 + (fcfg1_nvmsize >> 1));
1795                         break;
1796                 case 0x0f:
1797                         if (pflash_sector_size_bytes >= 4<<10)
1798                                 nvm_size = 512<<10;
1799                         else
1800                                 /* K20_100 */
1801                                 nvm_size = 256<<10;
1802                         break;
1803                 default:
1804                         nvm_size = 0;
1805                         break;
1806                 }
1807
1808                 switch (fcfg1_eesize) {
1809                 case 0x00:
1810                 case 0x01:
1811                 case 0x02:
1812                 case 0x03:
1813                 case 0x04:
1814                 case 0x05:
1815                 case 0x06:
1816                 case 0x07:
1817                 case 0x08:
1818                 case 0x09:
1819                         ee_size = (16 << (10 - fcfg1_eesize));
1820                         break;
1821                 default:
1822                         ee_size = 0;
1823                         break;
1824                 }
1825
1826                 switch (fcfg1_depart) {
1827                 case 0x01:
1828                 case 0x02:
1829                 case 0x03:
1830                 case 0x04:
1831                 case 0x05:
1832                 case 0x06:
1833                         df_size = nvm_size - (4096 << fcfg1_depart);
1834                         break;
1835                 case 0x08:
1836                         df_size = 0;
1837                         break;
1838                 case 0x09:
1839                 case 0x0a:
1840                 case 0x0b:
1841                 case 0x0c:
1842                 case 0x0d:
1843                         df_size = 4096 << (fcfg1_depart & 0x7);
1844                         break;
1845                 default:
1846                         df_size = nvm_size;
1847                         break;
1848                 }
1849         }
1850
1851         switch (fcfg1_pfsize) {
1852         case 0x03:
1853         case 0x05:
1854         case 0x07:
1855         case 0x09:
1856         case 0x0b:
1857         case 0x0d:
1858                 pf_size = 1 << (14 + (fcfg1_pfsize >> 1));
1859                 break;
1860         case 0x0f:
1861                 /* a peculiar case: Freescale states different sizes for 0xf
1862                  * K02P64M100SFARM      128 KB ... duplicate of code 0x7
1863                  * K22P121M120SF8RM     256 KB ... duplicate of code 0x9
1864                  * K22P121M120SF7RM     512 KB ... duplicate of code 0xb
1865                  * K22P100M120SF5RM     1024 KB ... duplicate of code 0xd
1866                  * K26P169M180SF5RM     2048 KB ... the only unique value
1867                  * fcfg2_maxaddr0 seems to be the only clue to pf_size
1868                  * Checking fcfg2_maxaddr0 later in this routine is pointless then
1869                  */
1870                 if (fcfg2_pflsh)
1871                         pf_size = ((uint32_t)fcfg2_maxaddr0 << 13) * num_blocks;
1872                 else
1873                         pf_size = ((uint32_t)fcfg2_maxaddr0 << 13) * num_blocks / 2;
1874                 if (pf_size != 2048<<10)
1875                         LOG_WARNING("SIM_FCFG1 PFSIZE = 0xf: please check if pflash is %u KB", pf_size>>10);
1876
1877                 break;
1878         default:
1879                 pf_size = 0;
1880                 break;
1881         }
1882
1883         LOG_DEBUG("FlexNVM: %" PRIu32 " PFlash: %" PRIu32 " FlexRAM: %" PRIu32 " PFLSH: %d",
1884                   nvm_size, pf_size, ee_size, fcfg2_pflsh);
1885
1886         num_pflash_blocks = num_blocks / (2 - fcfg2_pflsh);
1887         first_nvm_bank = num_pflash_blocks;
1888         num_nvm_blocks = num_blocks - num_pflash_blocks;
1889
1890         LOG_DEBUG("%d blocks total: %d PFlash, %d FlexNVM",
1891                         num_blocks, num_pflash_blocks, num_nvm_blocks);
1892
1893         LOG_INFO("Probing flash info for bank %d", bank->bank_number);
1894
1895         if ((unsigned)bank->bank_number < num_pflash_blocks) {
1896                 /* pflash, banks start at address zero */
1897                 kinfo->flash_class = FC_PFLASH;
1898                 bank->size = (pf_size / num_pflash_blocks);
1899                 bank->base = 0x00000000 + bank->size * bank->bank_number;
1900                 kinfo->prog_base = bank->base;
1901                 kinfo->sector_size = pflash_sector_size_bytes;
1902                 /* pflash is divided into 32 protection areas for
1903                  * parts with more than 32K of PFlash. For parts with
1904                  * less the protection unit is set to 1024 bytes */
1905                 kinfo->protection_size = MAX(pf_size / 32, 1024);
1906                 bank->num_prot_blocks = 32 / num_pflash_blocks;
1907                 kinfo->protection_block = bank->num_prot_blocks * bank->bank_number;
1908
1909         } else if ((unsigned)bank->bank_number < num_blocks) {
1910                 /* nvm, banks start at address 0x10000000 */
1911                 unsigned nvm_ord = bank->bank_number - first_nvm_bank;
1912                 uint32_t limit;
1913
1914                 kinfo->flash_class = FC_FLEX_NVM;
1915                 bank->size = (nvm_size / num_nvm_blocks);
1916                 bank->base = 0x10000000 + bank->size * nvm_ord;
1917                 kinfo->prog_base = 0x00800000 + bank->size * nvm_ord;
1918                 kinfo->sector_size = nvm_sector_size_bytes;
1919                 if (df_size == 0) {
1920                         kinfo->protection_size = 0;
1921                 } else {
1922                         for (i = df_size; ~i & 1; i >>= 1)
1923                                 ;
1924                         if (i == 1)
1925                                 kinfo->protection_size = df_size / 8;   /* data flash size = 2^^n */
1926                         else
1927                                 kinfo->protection_size = nvm_size / 8;  /* TODO: verify on SF1, not documented in RM */
1928                 }
1929                 bank->num_prot_blocks = 8 / num_nvm_blocks;
1930                 kinfo->protection_block = bank->num_prot_blocks * nvm_ord;
1931
1932                 /* EEPROM backup part of FlexNVM is not accessible, use df_size as a limit */
1933                 if (df_size > bank->size * nvm_ord)
1934                         limit = df_size - bank->size * nvm_ord;
1935                 else
1936                         limit = 0;
1937
1938                 if (bank->size > limit) {
1939                         bank->size = limit;
1940                         LOG_DEBUG("FlexNVM bank %d limited to 0x%08" PRIx32 " due to active EEPROM backup",
1941                                 bank->bank_number, limit);
1942                 }
1943
1944         } else if ((unsigned)bank->bank_number == num_blocks) {
1945                 LOG_ERROR("FlexRAM support not yet implemented");
1946                 return ERROR_FLASH_OPER_UNSUPPORTED;
1947         } else {
1948                 LOG_ERROR("Cannot determine parameters for bank %d, only %d banks on device",
1949                                 bank->bank_number, num_blocks);
1950                 return ERROR_FLASH_BANK_INVALID;
1951         }
1952
1953         if (bank->bank_number == 0 && ((uint32_t)fcfg2_maxaddr0 << 13) != bank->size)
1954                 LOG_WARNING("MAXADDR0 0x%02" PRIx8 " check failed,"
1955                                 " please report to OpenOCD mailing list", fcfg2_maxaddr0);
1956         if (fcfg2_pflsh) {
1957                 if (bank->bank_number == 1 && ((uint32_t)fcfg2_maxaddr1 << 13) != bank->size)
1958                         LOG_WARNING("MAXADDR1 0x%02" PRIx8 " check failed,"
1959                                 " please report to OpenOCD mailing list", fcfg2_maxaddr1);
1960         } else {
1961                 if ((unsigned)bank->bank_number == first_nvm_bank
1962                                 && ((uint32_t)fcfg2_maxaddr1 << 13) != df_size)
1963                         LOG_WARNING("FlexNVM MAXADDR1 0x%02" PRIx8 " check failed,"
1964                                 " please report to OpenOCD mailing list", fcfg2_maxaddr1);
1965         }
1966
1967         if (bank->sectors) {
1968                 free(bank->sectors);
1969                 bank->sectors = NULL;
1970         }
1971         if (bank->prot_blocks) {
1972                 free(bank->prot_blocks);
1973                 bank->prot_blocks = NULL;
1974         }
1975
1976         if (kinfo->sector_size == 0) {
1977                 LOG_ERROR("Unknown sector size for bank %d", bank->bank_number);
1978                 return ERROR_FLASH_BANK_INVALID;
1979         }
1980
1981         if (kinfo->flash_support & FS_PROGRAM_SECTOR
1982                          && kinfo->max_flash_prog_size == 0) {
1983                 kinfo->max_flash_prog_size = kinfo->sector_size;
1984                 /* Program section size is equal to sector size by default */
1985         }
1986
1987         bank->num_sectors = bank->size / kinfo->sector_size;
1988
1989         if (bank->num_sectors > 0) {
1990                 /* FlexNVM bank can be used for EEPROM backup therefore zero sized */
1991                 bank->sectors = alloc_block_array(0, kinfo->sector_size, bank->num_sectors);
1992                 if (!bank->sectors)
1993                         return ERROR_FAIL;
1994
1995                 bank->prot_blocks = alloc_block_array(0, kinfo->protection_size, bank->num_prot_blocks);
1996                 if (!bank->prot_blocks)
1997                         return ERROR_FAIL;
1998
1999         } else {
2000                 bank->num_prot_blocks = 0;
2001         }
2002
2003         kinfo->probed = true;
2004
2005         return ERROR_OK;
2006 }
2007
2008 static int kinetis_auto_probe(struct flash_bank *bank)
2009 {
2010         struct kinetis_flash_bank *kinfo = bank->driver_priv;
2011
2012         if (kinfo && kinfo->probed)
2013                 return ERROR_OK;
2014
2015         return kinetis_probe(bank);
2016 }
2017
2018 static int kinetis_info(struct flash_bank *bank, char *buf, int buf_size)
2019 {
2020         const char *bank_class_names[] = {
2021                 "(ANY)", "PFlash", "FlexNVM", "FlexRAM"
2022         };
2023
2024         struct kinetis_flash_bank *kinfo = bank->driver_priv;
2025
2026         (void) snprintf(buf, buf_size,
2027                         "%s driver for %s flash bank %s at 0x%8.8" PRIx32 "",
2028                         bank->driver->name, bank_class_names[kinfo->flash_class],
2029                         bank->name, bank->base);
2030
2031         return ERROR_OK;
2032 }
2033
2034 static int kinetis_blank_check(struct flash_bank *bank)
2035 {
2036         struct kinetis_flash_bank *kinfo = bank->driver_priv;
2037         int result;
2038
2039         /* suprisingly blank check does not work in VLPR and HSRUN modes */
2040         result = kinetis_check_run_mode(bank->target);
2041         if (result != ERROR_OK)
2042                 return result;
2043
2044         /* reset error flags */
2045         result = kinetis_ftfx_prepare(bank->target);
2046         if (result != ERROR_OK)
2047                 return result;
2048
2049         if (kinfo->flash_class == FC_PFLASH || kinfo->flash_class == FC_FLEX_NVM) {
2050                 bool block_dirty = false;
2051                 uint8_t ftfx_fstat;
2052
2053                 if (kinfo->flash_class == FC_FLEX_NVM) {
2054                         uint8_t fcfg1_depart = (uint8_t)((kinfo->sim_fcfg1 >> 8) & 0x0f);
2055                         /* block operation cannot be used on FlexNVM when EEPROM backup partition is set */
2056                         if (fcfg1_depart != 0xf && fcfg1_depart != 0)
2057                                 block_dirty = true;
2058                 }
2059
2060                 if (!block_dirty) {
2061                         /* check if whole bank is blank */
2062                         result = kinetis_ftfx_command(bank->target, FTFx_CMD_BLOCKSTAT, kinfo->prog_base,
2063                                                          0, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
2064
2065                         if (result != ERROR_OK || (ftfx_fstat & 0x01))
2066                                 block_dirty = true;
2067                 }
2068
2069                 if (block_dirty) {
2070                         /* the whole bank is not erased, check sector-by-sector */
2071                         int i;
2072                         for (i = 0; i < bank->num_sectors; i++) {
2073                                 /* normal margin */
2074                                 result = kinetis_ftfx_command(bank->target, FTFx_CMD_SECTSTAT,
2075                                                 kinfo->prog_base + bank->sectors[i].offset,
2076                                                 1, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
2077
2078                                 if (result == ERROR_OK) {
2079                                         bank->sectors[i].is_erased = !(ftfx_fstat & 0x01);
2080                                 } else {
2081                                         LOG_DEBUG("Ignoring errored PFlash sector blank-check");
2082                                         bank->sectors[i].is_erased = -1;
2083                                 }
2084                         }
2085                 } else {
2086                         /* the whole bank is erased, update all sectors */
2087                         int i;
2088                         for (i = 0; i < bank->num_sectors; i++)
2089                                 bank->sectors[i].is_erased = 1;
2090                 }
2091         } else {
2092                 LOG_WARNING("kinetis_blank_check not supported yet for FlexRAM");
2093                 return ERROR_FLASH_OPERATION_FAILED;
2094         }
2095
2096         return ERROR_OK;
2097 }
2098
2099
2100 COMMAND_HANDLER(kinetis_nvm_partition)
2101 {
2102         int result, i;
2103         unsigned long par, log2 = 0, ee1 = 0, ee2 = 0;
2104         enum { SHOW_INFO, DF_SIZE, EEBKP_SIZE } sz_type = SHOW_INFO;
2105         bool enable;
2106         uint8_t load_flex_ram = 1;
2107         uint8_t ee_size_code = 0x3f;
2108         uint8_t flex_nvm_partition_code = 0;
2109         uint8_t ee_split = 3;
2110         struct target *target = get_current_target(CMD_CTX);
2111         struct flash_bank *bank;
2112         struct kinetis_flash_bank *kinfo;
2113         uint32_t sim_fcfg1;
2114
2115         if (CMD_ARGC >= 2) {
2116                 if (strcmp(CMD_ARGV[0], "dataflash") == 0)
2117                         sz_type = DF_SIZE;
2118                 else if (strcmp(CMD_ARGV[0], "eebkp") == 0)
2119                         sz_type = EEBKP_SIZE;
2120
2121                 par = strtoul(CMD_ARGV[1], NULL, 10);
2122                 while (par >> (log2 + 3))
2123                         log2++;
2124         }
2125         switch (sz_type) {
2126         case SHOW_INFO:
2127                 result = target_read_u32(target, SIM_FCFG1, &sim_fcfg1);
2128                 if (result != ERROR_OK)
2129                         return result;
2130
2131                 flex_nvm_partition_code = (uint8_t)((sim_fcfg1 >> 8) & 0x0f);
2132                 switch (flex_nvm_partition_code) {
2133                 case 0:
2134                         command_print(CMD_CTX, "No EEPROM backup, data flash only");
2135                         break;
2136                 case 1:
2137                 case 2:
2138                 case 3:
2139                 case 4:
2140                 case 5:
2141                 case 6:
2142                         command_print(CMD_CTX, "EEPROM backup %d KB", 4 << flex_nvm_partition_code);
2143                         break;
2144                 case 8:
2145                         command_print(CMD_CTX, "No data flash, EEPROM backup only");
2146                         break;
2147                 case 0x9:
2148                 case 0xA:
2149                 case 0xB:
2150                 case 0xC:
2151                 case 0xD:
2152                 case 0xE:
2153                         command_print(CMD_CTX, "data flash %d KB", 4 << (flex_nvm_partition_code & 7));
2154                         break;
2155                 case 0xf:
2156                         command_print(CMD_CTX, "No EEPROM backup, data flash only (DEPART not set)");
2157                         break;
2158                 default:
2159                         command_print(CMD_CTX, "Unsupported EEPROM backup size code 0x%02" PRIx8, flex_nvm_partition_code);
2160                 }
2161                 return ERROR_OK;
2162
2163         case DF_SIZE:
2164                 flex_nvm_partition_code = 0x8 | log2;
2165                 break;
2166
2167         case EEBKP_SIZE:
2168                 flex_nvm_partition_code = log2;
2169                 break;
2170         }
2171
2172         if (CMD_ARGC == 3)
2173                 ee1 = ee2 = strtoul(CMD_ARGV[2], NULL, 10) / 2;
2174         else if (CMD_ARGC >= 4) {
2175                 ee1 = strtoul(CMD_ARGV[2], NULL, 10);
2176                 ee2 = strtoul(CMD_ARGV[3], NULL, 10);
2177         }
2178
2179         enable = ee1 + ee2 > 0;
2180         if (enable) {
2181                 for (log2 = 2; ; log2++) {
2182                         if (ee1 + ee2 == (16u << 10) >> log2)
2183                                 break;
2184                         if (ee1 + ee2 > (16u << 10) >> log2 || log2 >= 9) {
2185                                 LOG_ERROR("Unsupported EEPROM size");
2186                                 return ERROR_FLASH_OPERATION_FAILED;
2187                         }
2188                 }
2189
2190                 if (ee1 * 3 == ee2)
2191                         ee_split = 1;
2192                 else if (ee1 * 7 == ee2)
2193                         ee_split = 0;
2194                 else if (ee1 != ee2) {
2195                         LOG_ERROR("Unsupported EEPROM sizes ratio");
2196                         return ERROR_FLASH_OPERATION_FAILED;
2197                 }
2198
2199                 ee_size_code = log2 | ee_split << 4;
2200         }
2201
2202         if (CMD_ARGC >= 5)
2203                 COMMAND_PARSE_ON_OFF(CMD_ARGV[4], enable);
2204         if (enable)
2205                 load_flex_ram = 0;
2206
2207         LOG_INFO("DEPART 0x%" PRIx8 ", EEPROM size code 0x%" PRIx8,
2208                  flex_nvm_partition_code, ee_size_code);
2209
2210         result = kinetis_check_run_mode(target);
2211         if (result != ERROR_OK)
2212                 return result;
2213
2214         /* reset error flags */
2215         result = kinetis_ftfx_prepare(target);
2216         if (result != ERROR_OK)
2217                 return result;
2218
2219         result = kinetis_ftfx_command(target, FTFx_CMD_PGMPART, load_flex_ram,
2220                                       ee_size_code, flex_nvm_partition_code, 0, 0,
2221                                       0, 0, 0, 0,  NULL);
2222         if (result != ERROR_OK)
2223                 return result;
2224
2225         command_print(CMD_CTX, "FlexNVM partition set. Please reset MCU.");
2226
2227         for (i = 1; i < 4; i++) {
2228                 bank = get_flash_bank_by_num_noprobe(i);
2229                 if (bank == NULL)
2230                         break;
2231
2232                 kinfo = bank->driver_priv;
2233                 if (kinfo && kinfo->flash_class == FC_FLEX_NVM)
2234                         kinfo->probed = false;  /* re-probe before next use */
2235         }
2236
2237         command_print(CMD_CTX, "FlexNVM banks will be re-probed to set new data flash size.");
2238         return ERROR_OK;
2239 }
2240
2241 COMMAND_HANDLER(kinetis_fcf_source_handler)
2242 {
2243         if (CMD_ARGC > 1)
2244                 return ERROR_COMMAND_SYNTAX_ERROR;
2245
2246         if (CMD_ARGC == 1) {
2247                 if (strcmp(CMD_ARGV[0], "write") == 0)
2248                         allow_fcf_writes = true;
2249                 else if (strcmp(CMD_ARGV[0], "protection") == 0)
2250                         allow_fcf_writes = false;
2251                 else
2252                         return ERROR_COMMAND_SYNTAX_ERROR;
2253         }
2254
2255         if (allow_fcf_writes) {
2256                 command_print(CMD_CTX, "Arbitrary Flash Configuration Field writes enabled.");
2257                 command_print(CMD_CTX, "Protection info writes to FCF disabled.");
2258                 LOG_WARNING("BEWARE: incorrect flash configuration may permanently lock the device.");
2259         } else {
2260                 command_print(CMD_CTX, "Protection info writes to Flash Configuration Field enabled.");
2261                 command_print(CMD_CTX, "Arbitrary FCF writes disabled. Mode safe from unwanted locking of the device.");
2262         }
2263
2264         return ERROR_OK;
2265 }
2266
2267 COMMAND_HANDLER(kinetis_fopt_handler)
2268 {
2269         if (CMD_ARGC > 1)
2270                 return ERROR_COMMAND_SYNTAX_ERROR;
2271
2272         if (CMD_ARGC == 1)
2273                 fcf_fopt = (uint8_t)strtoul(CMD_ARGV[0], NULL, 0);
2274         else
2275                 command_print(CMD_CTX, "FCF_FOPT 0x%02" PRIx8, fcf_fopt);
2276
2277         return ERROR_OK;
2278 }
2279
2280
2281 static const struct command_registration kinetis_security_command_handlers[] = {
2282         {
2283                 .name = "check_security",
2284                 .mode = COMMAND_EXEC,
2285                 .help = "Check status of device security lock",
2286                 .usage = "",
2287                 .handler = kinetis_check_flash_security_status,
2288         },
2289         {
2290                 .name = "halt",
2291                 .mode = COMMAND_EXEC,
2292                 .help = "Issue a halt via the MDM-AP",
2293                 .usage = "",
2294                 .handler = kinetis_mdm_halt,
2295         },
2296         {
2297                 .name = "mass_erase",
2298                 .mode = COMMAND_EXEC,
2299                 .help = "Issue a complete flash erase via the MDM-AP",
2300                 .usage = "",
2301                 .handler = kinetis_mdm_mass_erase,
2302         },
2303         {       .name = "reset",
2304                 .mode = COMMAND_EXEC,
2305                 .help = "Issue a reset via the MDM-AP",
2306                 .usage = "",
2307                 .handler = kinetis_mdm_reset,
2308         },
2309         COMMAND_REGISTRATION_DONE
2310 };
2311
2312 static const struct command_registration kinetis_exec_command_handlers[] = {
2313         {
2314                 .name = "mdm",
2315                 .mode = COMMAND_ANY,
2316                 .help = "MDM-AP command group",
2317                 .usage = "",
2318                 .chain = kinetis_security_command_handlers,
2319         },
2320         {
2321                 .name = "disable_wdog",
2322                 .mode = COMMAND_EXEC,
2323                 .help = "Disable the watchdog timer",
2324                 .usage = "",
2325                 .handler = kinetis_disable_wdog_handler,
2326         },
2327         {
2328                 .name = "nvm_partition",
2329                 .mode = COMMAND_EXEC,
2330                 .help = "Show/set data flash or EEPROM backup size in kilobytes,"
2331                         " set two EEPROM sizes in bytes and FlexRAM loading during reset",
2332                 .usage = "('info'|'dataflash' size|'eebkp' size) [eesize1 eesize2] ['on'|'off']",
2333                 .handler = kinetis_nvm_partition,
2334         },
2335         {
2336                 .name = "fcf_source",
2337                 .mode = COMMAND_EXEC,
2338                 .help = "Use protection as a source for Flash Configuration Field or allow writing arbitrary values to the FCF"
2339                         " Mode 'protection' is safe from unwanted locking of the device.",
2340                 .usage = "['protection'|'write']",
2341                 .handler = kinetis_fcf_source_handler,
2342         },
2343         {
2344                 .name = "fopt",
2345                 .mode = COMMAND_EXEC,
2346                 .help = "FCF_FOPT value source in 'kinetis fcf_source protection' mode",
2347                 .usage = "[num]",
2348                 .handler = kinetis_fopt_handler,
2349         },
2350         COMMAND_REGISTRATION_DONE
2351 };
2352
2353 static const struct command_registration kinetis_command_handler[] = {
2354         {
2355                 .name = "kinetis",
2356                 .mode = COMMAND_ANY,
2357                 .help = "Kinetis flash controller commands",
2358                 .usage = "",
2359                 .chain = kinetis_exec_command_handlers,
2360         },
2361         COMMAND_REGISTRATION_DONE
2362 };
2363
2364
2365
2366 struct flash_driver kinetis_flash = {
2367         .name = "kinetis",
2368         .commands = kinetis_command_handler,
2369         .flash_bank_command = kinetis_flash_bank_command,
2370         .erase = kinetis_erase,
2371         .protect = kinetis_protect,
2372         .write = kinetis_write,
2373         .read = default_flash_read,
2374         .probe = kinetis_probe,
2375         .auto_probe = kinetis_auto_probe,
2376         .erase_check = kinetis_blank_check,
2377         .protect_check = kinetis_protect_check,
2378         .info = kinetis_info,
2379 };