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