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