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