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