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