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