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