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