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