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