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