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