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