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