6485bc3fa3171de67d599dbab751903269f8598a
[fw/openocd] / src / flash / nor / kinetis.c
1 /***************************************************************************
2  *   Copyright (C) 2011 by Mathias Kuester                                 *
3  *   kesmtp@freenet.de                                                     *
4  *                                                                         *
5  *   Copyright (C) 2011 sleep(5) ltd                                       *
6  *   tomas@sleepfive.com                                                   *
7  *                                                                         *
8  *   Copyright (C) 2012 by Christopher D. Kilgour                          *
9  *   techie at whiterocker.com                                             *
10  *                                                                         *
11  *   Copyright (C) 2013 Nemui Trinomius                                    *
12  *   nemuisan_kawausogasuki@live.jp                                        *
13  *                                                                         *
14  *   This program is free software; you can redistribute it and/or modify  *
15  *   it under the terms of the GNU General Public License as published by  *
16  *   the Free Software Foundation; either version 2 of the License, or     *
17  *   (at your option) any later version.                                   *
18  *                                                                         *
19  *   This program is distributed in the hope that it will be useful,       *
20  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
21  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
22  *   GNU General Public License for more details.                          *
23  *                                                                         *
24  *   You should have received a copy of the GNU General Public License     *
25  *   along with this program; if not, write to the                         *
26  *   Free Software Foundation, Inc.,                                       *
27  *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.           *
28  ***************************************************************************/
29
30 #ifdef HAVE_CONFIG_H
31 #include "config.h"
32 #endif
33
34 #include "jtag/interface.h"
35 #include "imp.h"
36 #include <helper/binarybuffer.h>
37 #include <target/algorithm.h>
38 #include <target/armv7m.h>
39 #include <target/cortex_m.h>
40
41 /*
42  * Implementation Notes
43  *
44  * The persistent memories in the Kinetis chip families K10 through
45  * K70 are all manipulated with the Flash Memory Module.  Some
46  * variants call this module the FTFE, others call it the FTFL.  To
47  * indicate that both are considered here, we use FTFX.
48  *
49  * Within the module, according to the chip variant, the persistent
50  * memory is divided into what Freescale terms Program Flash, FlexNVM,
51  * and FlexRAM.  All chip variants have Program Flash.  Some chip
52  * variants also have FlexNVM and FlexRAM, which always appear
53  * together.
54  *
55  * A given Kinetis chip may have 1, 2 or 4 blocks of flash.  Here we map
56  * each block to a separate bank.  Each block size varies by chip and
57  * may be determined by the read-only SIM_FCFG1 register.  The sector
58  * size within each bank/block varies by chip, and may be 1, 2 or 4k.
59  * The sector size may be different for flash and FlexNVM.
60  *
61  * The first half of the flash (1 or 2 blocks) is always Program Flash
62  * and always starts at address 0x00000000.  The "PFLSH" flag, bit 23
63  * of the read-only SIM_FCFG2 register, determines whether the second
64  * half of the flash is also Program Flash or FlexNVM+FlexRAM.  When
65  * PFLSH is set, the second from the first half.  When PFLSH is clear,
66  * the second half of flash is FlexNVM and always starts at address
67  * 0x10000000.  FlexRAM, which is also present when PFLSH is clear,
68  * always starts at address 0x14000000.
69  *
70  * The Flash Memory Module provides a register set where flash
71  * commands are loaded to perform flash operations like erase and
72  * program.  Different commands are available depending on whether
73  * Program Flash or FlexNVM/FlexRAM is being manipulated.  Although
74  * the commands used are quite consistent between flash blocks, the
75  * parameters they accept differ according to the flash sector size.
76  *
77  */
78
79 /* Addressess */
80 #define FLEXRAM         0x14000000
81 #define FTFx_FSTAT      0x40020000
82 #define FTFx_FCNFG      0x40020001
83 #define FTFx_FCCOB3     0x40020004
84 #define FTFx_FPROT3     0x40020010
85 #define SIM_SDID        0x40048024
86 #define SIM_SOPT1       0x40047000
87 #define SIM_FCFG1       0x4004804c
88 #define SIM_FCFG2       0x40048050
89
90 /* Commands */
91 #define FTFx_CMD_BLOCKSTAT  0x00
92 #define FTFx_CMD_SECTSTAT   0x01
93 #define FTFx_CMD_LWORDPROG  0x06
94 #define FTFx_CMD_SECTERASE  0x09
95 #define FTFx_CMD_SECTWRITE  0x0b
96 #define FTFx_CMD_SETFLEXRAM 0x81
97 #define FTFx_CMD_MASSERASE  0x44
98
99 /* The older Kinetis K series uses the following SDID layout :
100  * Bit 31-16 : 0
101  * Bit 15-12 : REVID
102  * Bit 11-7  : DIEID
103  * Bit 6-4   : FAMID
104  * Bit 3-0   : PINID
105  *
106  * The newer Kinetis series uses the following SDID layout :
107  * Bit 31-28 : FAMID
108  * Bit 27-24 : SUBFAMID
109  * Bit 23-20 : SERIESID
110  * Bit 19-16 : SRAMSIZE
111  * Bit 15-12 : REVID
112  * Bit 6-4   : Reserved (0)
113  * Bit 3-0   : PINID
114  *
115  * We assume that if bits 31-16 are 0 then it's an older
116  * K-series MCU.
117  */
118
119 #define KINETIS_SOPT1_RAMSIZE_MASK  0x0000F000
120 #define KINETIS_SOPT1_RAMSIZE_K24FN1M 0x0000B000
121
122 #define KINETIS_SDID_K_SERIES_MASK  0x0000FFFF
123
124 #define KINETIS_SDID_DIEID_MASK 0x00000F80
125 #define KINETIS_SDID_DIEID_K_A  0x00000100
126 #define KINETIS_SDID_DIEID_K_B  0x00000200
127 #define KINETIS_SDID_DIEID_KL   0x00000000
128 #define KINETIS_SDID_DIEID_K24FN1M      0x00000300 /* Detect Errata 7534 */
129
130 /* We can't rely solely on the FAMID field to determine the MCU
131  * type since some FAMID values identify multiple MCUs with
132  * different flash sector sizes (K20 and K22 for instance).
133  * Therefore we combine it with the DIEID bits which may possibly
134  * break if Freescale bumps the DIEID for a particular MCU. */
135 #define KINETIS_K_SDID_TYPE_MASK 0x00000FF0
136 #define KINETIS_K_SDID_K10_M50   0x00000000
137 #define KINETIS_K_SDID_K10_M72   0x00000080
138 #define KINETIS_K_SDID_K10_M100  0x00000100
139 #define KINETIS_K_SDID_K10_M120  0x00000180
140 #define KINETIS_K_SDID_K11               0x00000220
141 #define KINETIS_K_SDID_K12               0x00000200
142 #define KINETIS_K_SDID_K20_M50   0x00000010
143 #define KINETIS_K_SDID_K20_M72   0x00000090
144 #define KINETIS_K_SDID_K20_M100  0x00000110
145 #define KINETIS_K_SDID_K20_M120  0x00000190
146 #define KINETIS_K_SDID_K21_M50   0x00000230
147 #define KINETIS_K_SDID_K21_M120  0x00000330
148 #define KINETIS_K_SDID_K22_M50   0x00000210
149 #define KINETIS_K_SDID_K22_M120  0x00000310
150 #define KINETIS_K_SDID_K30_M72   0x000000A0
151 #define KINETIS_K_SDID_K30_M100  0x00000120
152 #define KINETIS_K_SDID_K40_M72   0x000000B0
153 #define KINETIS_K_SDID_K40_M100  0x00000130
154 #define KINETIS_K_SDID_K50_M72   0x000000E0
155 #define KINETIS_K_SDID_K51_M72   0x000000F0
156 #define KINETIS_K_SDID_K53               0x00000170
157 #define KINETIS_K_SDID_K60_M100  0x00000140
158 #define KINETIS_K_SDID_K60_M150  0x000001C0
159 #define KINETIS_K_SDID_K70_M150  0x000001D0
160
161 #define KINETIS_SDID_SERIESID_MASK 0x00F00000
162 #define KINETIS_SDID_SERIESID_K   0x00000000
163 #define KINETIS_SDID_SERIESID_KL   0x00100000
164 #define KINETIS_SDID_SERIESID_KW   0x00500000
165 #define KINETIS_SDID_SERIESID_KV   0x00600000
166
167 #define KINETIS_SDID_SUBFAMID_MASK  0x0F000000
168 #define KINETIS_SDID_SUBFAMID_KX0   0x00000000
169 #define KINETIS_SDID_SUBFAMID_KX1   0x01000000
170 #define KINETIS_SDID_SUBFAMID_KX2   0x02000000
171 #define KINETIS_SDID_SUBFAMID_KX3   0x03000000
172 #define KINETIS_SDID_SUBFAMID_KX4   0x04000000
173 #define KINETIS_SDID_SUBFAMID_KX5   0x05000000
174 #define KINETIS_SDID_SUBFAMID_KX6   0x06000000
175
176 #define KINETIS_SDID_FAMILYID_MASK  0xF0000000
177 #define KINETIS_SDID_FAMILYID_K0X   0x00000000
178 #define KINETIS_SDID_FAMILYID_K1X   0x10000000
179 #define KINETIS_SDID_FAMILYID_K2X   0x20000000
180 #define KINETIS_SDID_FAMILYID_K3X   0x30000000
181 #define KINETIS_SDID_FAMILYID_K4X   0x40000000
182 #define KINETIS_SDID_FAMILYID_K6X   0x60000000
183 #define KINETIS_SDID_FAMILYID_K7X   0x70000000
184
185 struct kinetis_flash_bank {
186         unsigned bank_ordinal;
187         uint32_t sector_size;
188         uint32_t max_flash_prog_size;
189         uint32_t protection_size;
190
191         uint32_t sim_sdid;
192         uint32_t sim_fcfg1;
193         uint32_t sim_fcfg2;
194
195         enum {
196                 FC_AUTO = 0,
197                 FC_PFLASH,
198                 FC_FLEX_NVM,
199                 FC_FLEX_RAM,
200         } flash_class;
201
202         enum {
203                 FS_PROGRAM_SECTOR = 1,
204                 FS_PROGRAM_LONGWORD = 2,
205                 FS_PROGRAM_PHRASE = 4, /* Unsupported */
206         } flash_support;
207 };
208
209 #define MDM_REG_STAT            0x00
210 #define MDM_REG_CTRL            0x04
211 #define MDM_REG_ID              0xfc
212
213 #define MDM_STAT_FMEACK         (1<<0)
214 #define MDM_STAT_FREADY         (1<<1)
215 #define MDM_STAT_SYSSEC         (1<<2)
216 #define MDM_STAT_SYSRES         (1<<3)
217 #define MDM_STAT_FMEEN          (1<<5)
218 #define MDM_STAT_BACKDOOREN     (1<<6)
219 #define MDM_STAT_LPEN           (1<<7)
220 #define MDM_STAT_VLPEN          (1<<8)
221 #define MDM_STAT_LLSMODEXIT     (1<<9)
222 #define MDM_STAT_VLLSXMODEXIT   (1<<10)
223 #define MDM_STAT_CORE_HALTED    (1<<16)
224 #define MDM_STAT_CORE_SLEEPDEEP (1<<17)
225 #define MDM_STAT_CORESLEEPING   (1<<18)
226
227 #define MEM_CTRL_FMEIP          (1<<0)
228 #define MEM_CTRL_DBG_DIS        (1<<1)
229 #define MEM_CTRL_DBG_REQ        (1<<2)
230 #define MEM_CTRL_SYS_RES_REQ    (1<<3)
231 #define MEM_CTRL_CORE_HOLD_RES  (1<<4)
232 #define MEM_CTRL_VLLSX_DBG_REQ  (1<<5)
233 #define MEM_CTRL_VLLSX_DBG_ACK  (1<<6)
234 #define MEM_CTRL_VLLSX_STAT_ACK (1<<7)
235
236 #define MDM_ACCESS_TIMEOUT      3000 /* iterations */
237
238 static int kinetis_mdm_write_register(struct adiv5_dap *dap, unsigned reg, uint32_t value)
239 {
240         int retval;
241         LOG_DEBUG("MDM_REG[0x%02x] <- %08" PRIX32, reg, value);
242
243         retval = dap_queue_ap_write(dap, reg, value);
244         if (retval != ERROR_OK) {
245                 LOG_DEBUG("MDM: failed to queue a write request");
246                 return retval;
247         }
248
249         retval = dap_run(dap);
250         if (retval != ERROR_OK) {
251                 LOG_DEBUG("MDM: dap_run failed");
252                 return retval;
253         }
254
255
256         return ERROR_OK;
257 }
258
259 static int kinetis_mdm_read_register(struct adiv5_dap *dap, unsigned reg, uint32_t *result)
260 {
261         int retval;
262         retval = dap_queue_ap_read(dap, reg, result);
263         if (retval != ERROR_OK) {
264                 LOG_DEBUG("MDM: failed to queue a read request");
265                 return retval;
266         }
267
268         retval = dap_run(dap);
269         if (retval != ERROR_OK) {
270                 LOG_DEBUG("MDM: dap_run failed");
271                 return retval;
272         }
273
274         LOG_DEBUG("MDM_REG[0x%02x]: %08" PRIX32, reg, *result);
275         return ERROR_OK;
276 }
277
278 static int kinetis_mdm_poll_register(struct adiv5_dap *dap, unsigned reg, uint32_t mask, uint32_t value)
279 {
280         uint32_t val;
281         int retval;
282         int timeout = MDM_ACCESS_TIMEOUT;
283
284         do {
285                 retval = kinetis_mdm_read_register(dap, reg, &val);
286                 if (retval != ERROR_OK || (val & mask) == value)
287                         return retval;
288
289                 alive_sleep(1);
290         } while (timeout--);
291
292         LOG_DEBUG("MDM: polling timed out");
293         return ERROR_FAIL;
294 }
295
296 /*
297  * This function implements the procedure to mass erase the flash via
298  * SWD/JTAG on Kinetis K and L series of devices as it is described in
299  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
300  * and L-series MCUs" Section 4.2.1
301  */
302 COMMAND_HANDLER(kinetis_mdm_mass_erase)
303 {
304         struct target *target = get_current_target(CMD_CTX);
305         struct cortex_m_common *cortex_m = target_to_cm(target);
306         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
307
308         if (!dap) {
309                 LOG_ERROR("Cannot perform mass erase with a high-level adapter");
310                 return ERROR_FAIL;
311         }
312
313         int retval;
314         const uint8_t original_ap = dap->ap_current;
315
316         /*
317          * ... Power on the processor, or if power has already been
318          * applied, assert the RESET pin to reset the processor. For
319          * devices that do not have a RESET pin, write the System
320          * Reset Request bit in the MDM-AP control register after
321          * establishing communication...
322          */
323
324         /* assert SRST */
325         if (jtag_get_reset_config() & RESET_HAS_SRST)
326                 adapter_assert_reset();
327         else
328                 LOG_WARNING("Attempting mass erase without hardware reset. This is not reliable; "
329                             "it's recommended you connect SRST and use ``reset_config srst_only''.");
330
331         dap_ap_select(dap, 1);
332
333         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, MEM_CTRL_SYS_RES_REQ);
334         if (retval != ERROR_OK)
335                 return retval;
336
337         /*
338          * ... Read the MDM-AP status register until the Flash Ready bit sets...
339          */
340         retval = kinetis_mdm_poll_register(dap, MDM_REG_STAT,
341                                            MDM_STAT_FREADY | MDM_STAT_SYSRES,
342                                            MDM_STAT_FREADY);
343         if (retval != ERROR_OK) {
344                 LOG_ERROR("MDM : flash ready timeout");
345                 return retval;
346         }
347
348         /*
349          * ... Write the MDM-AP control register to set the Flash Mass
350          * Erase in Progress bit. This will start the mass erase
351          * process...
352          */
353         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL,
354                                             MEM_CTRL_SYS_RES_REQ | MEM_CTRL_FMEIP);
355         if (retval != ERROR_OK)
356                 return retval;
357
358         /* As a sanity check make sure that device started mass erase procedure */
359         retval = kinetis_mdm_poll_register(dap, MDM_REG_STAT,
360                                            MDM_STAT_FMEACK, MDM_STAT_FMEACK);
361         if (retval != ERROR_OK)
362                 return retval;
363
364         /*
365          * ... Read the MDM-AP control register until the Flash Mass
366          * Erase in Progress bit clears...
367          */
368         retval = kinetis_mdm_poll_register(dap, MDM_REG_CTRL,
369                                            MEM_CTRL_FMEIP,
370                                            0);
371         if (retval != ERROR_OK)
372                 return retval;
373
374         /*
375          * ... Negate the RESET signal or clear the System Reset Request
376          * bit in the MDM-AP control register...
377          */
378         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
379         if (retval != ERROR_OK)
380                 return retval;
381
382         if (jtag_get_reset_config() & RESET_HAS_SRST)
383                 adapter_deassert_reset();
384
385         dap_ap_select(dap, original_ap);
386         return ERROR_OK;
387 }
388
389 static const uint32_t kinetis_known_mdm_ids[] = {
390         0x001C0000,     /* Kinetis-K Series */
391         0x001C0020,     /* Kinetis-L/M/V/E Series */
392 };
393
394 /*
395  * This function implements the procedure to connect to
396  * SWD/JTAG on Kinetis K and L series of devices as it is described in
397  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
398  * and L-series MCUs" Section 4.1.1
399  */
400 COMMAND_HANDLER(kinetis_check_flash_security_status)
401 {
402         struct target *target = get_current_target(CMD_CTX);
403         struct cortex_m_common *cortex_m = target_to_cm(target);
404         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
405
406         if (!dap) {
407                 LOG_WARNING("Cannot check flash security status with a high-level adapter");
408                 return ERROR_OK;
409         }
410
411         uint32_t val;
412         int retval;
413         const uint8_t origninal_ap = dap->ap_current;
414
415         dap_ap_select(dap, 1);
416
417
418         /*
419          * ... The MDM-AP ID register can be read to verify that the
420          * connection is working correctly...
421          */
422         retval = kinetis_mdm_read_register(dap, MDM_REG_ID, &val);
423         if (retval != ERROR_OK) {
424                 LOG_ERROR("MDM: failed to read ID register");
425                 goto fail;
426         }
427
428         bool found = false;
429         for (size_t i = 0; i < ARRAY_SIZE(kinetis_known_mdm_ids); i++) {
430                 if (val == kinetis_known_mdm_ids[i]) {
431                         found = true;
432                         break;
433                 }
434         }
435
436         if (!found)
437                 LOG_WARNING("MDM: unknown ID %08" PRIX32, val);
438
439         /*
440          * ... Read the MDM-AP status register until the Flash Ready bit sets...
441          */
442         retval = kinetis_mdm_poll_register(dap, MDM_REG_STAT,
443                                            MDM_STAT_FREADY,
444                                            MDM_STAT_FREADY);
445         if (retval != ERROR_OK) {
446                 LOG_ERROR("MDM: flash ready timeout");
447                 goto fail;
448         }
449
450         /*
451          * ... Read the System Security bit to determine if security is enabled.
452          * If System Security = 0, then proceed. If System Security = 1, then
453          * communication with the internals of the processor, including the
454          * flash, will not be possible without issuing a mass erase command or
455          * unsecuring the part through other means (backdoor key unlock)...
456          */
457         retval = kinetis_mdm_read_register(dap, MDM_REG_STAT, &val);
458         if (retval != ERROR_OK) {
459                 LOG_ERROR("MDM: failed to read MDM_REG_STAT");
460                 goto fail;
461         }
462
463         if (val & MDM_STAT_SYSSEC) {
464                 jtag_poll_set_enabled(false);
465
466                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
467                 LOG_WARNING("****                                                          ****");
468                 LOG_WARNING("**** Your Kinetis MCU is in secured state, which means that,  ****");
469                 LOG_WARNING("**** with exception for very basic communication, JTAG/SWD    ****");
470                 LOG_WARNING("**** interface will NOT work. In order to restore its         ****");
471                 LOG_WARNING("**** functionality please issue 'kinetis mdm mass_erase'      ****");
472                 LOG_WARNING("**** command, power cycle the MCU and restart OpenOCD.        ****");
473                 LOG_WARNING("****                                                          ****");
474                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
475         } else {
476                 LOG_INFO("MDM: Chip is unsecured. Continuing.");
477                 jtag_poll_set_enabled(true);
478         }
479
480         dap_ap_select(dap, origninal_ap);
481
482         return ERROR_OK;
483
484 fail:
485         LOG_ERROR("MDM: Failed to check security status of the MCU. Cannot proceed further");
486         jtag_poll_set_enabled(false);
487         return retval;
488 }
489
490 FLASH_BANK_COMMAND_HANDLER(kinetis_flash_bank_command)
491 {
492         struct kinetis_flash_bank *bank_info;
493
494         if (CMD_ARGC < 6)
495                 return ERROR_COMMAND_SYNTAX_ERROR;
496
497         LOG_INFO("add flash_bank kinetis %s", bank->name);
498
499         bank_info = malloc(sizeof(struct kinetis_flash_bank));
500
501         memset(bank_info, 0, sizeof(struct kinetis_flash_bank));
502
503         bank->driver_priv = bank_info;
504
505         return ERROR_OK;
506 }
507
508 /* Kinetis Program-LongWord Microcodes */
509 static const uint8_t kinetis_flash_write_code[] = {
510         /* Params:
511          * r0 - workarea buffer
512         * r1 - target address
513         * r2 - wordcount
514         * Clobbered:
515         * r4 - tmp
516         * r5 - tmp
517         * r6 - tmp
518         * r7 - tmp
519         */
520
521                                                         /* .L1: */
522                                                 /* for(register uint32_t i=0;i<wcount;i++){ */
523         0x04, 0x1C,                                     /* mov    r4, r0          */
524         0x00, 0x23,                                     /* mov    r3, #0          */
525                                                         /* .L2: */
526         0x0E, 0x1A,                                     /* sub    r6, r1, r0      */
527         0xA6, 0x19,                                     /* add    r6, r4, r6      */
528         0x93, 0x42,                                     /* cmp    r3, r2          */
529         0x16, 0xD0,                                     /* beq    .L9             */
530                                                         /* .L5: */
531                                                 /* while((FTFx_FSTAT&FTFA_FSTAT_CCIF_MASK) != FTFA_FSTAT_CCIF_MASK){}; */
532         0x0B, 0x4D,                                     /* ldr    r5, .L10        */
533         0x2F, 0x78,                                     /* ldrb   r7, [r5]        */
534         0x7F, 0xB2,                                     /* sxtb   r7, r7          */
535         0x00, 0x2F,                                     /* cmp    r7, #0          */
536         0xFA, 0xDA,                                     /* bge    .L5             */
537                                                 /* FTFx_FSTAT = FTFA_FSTAT_ACCERR_MASK|FTFA_FSTAT_FPVIOL_MASK|FTFA_FSTAT_RDCO */
538         0x70, 0x27,                                     /* mov    r7, #112        */
539         0x2F, 0x70,                                     /* strb   r7, [r5]        */
540                                                 /* FTFx_FCCOB3 = faddr; */
541         0x09, 0x4F,                                     /* ldr    r7, .L10+4      */
542         0x3E, 0x60,                                     /* str    r6, [r7]        */
543         0x06, 0x27,                                     /* mov    r7, #6          */
544                                                 /* FTFx_FCCOB0 = 0x06;  */
545         0x08, 0x4E,                                     /* ldr    r6, .L10+8      */
546         0x37, 0x70,                                     /* strb   r7, [r6]        */
547                                                 /* FTFx_FCCOB7 = *pLW;  */
548         0x80, 0xCC,                                     /* ldmia  r4!, {r7}       */
549         0x08, 0x4E,                                     /* ldr    r6, .L10+12     */
550         0x37, 0x60,                                     /* str    r7, [r6]        */
551                                                 /* FTFx_FSTAT = FTFA_FSTAT_CCIF_MASK; */
552         0x80, 0x27,                                     /* mov    r7, #128        */
553         0x2F, 0x70,                                     /* strb   r7, [r5]        */
554                                                         /* .L4: */
555                                                 /* while((FTFx_FSTAT&FTFA_FSTAT_CCIF_MASK) != FTFA_FSTAT_CCIF_MASK){}; */
556         0x2E, 0x78,                                     /* ldrb    r6, [r5]       */
557         0x77, 0xB2,                                     /* sxtb    r7, r6         */
558         0x00, 0x2F,                                     /* cmp     r7, #0         */
559         0xFB, 0xDA,                                     /* bge     .L4            */
560         0x01, 0x33,                                     /* add     r3, r3, #1     */
561         0xE4, 0xE7,                                     /* b       .L2            */
562                                                         /* .L9: */
563         0x00, 0xBE,                                     /* bkpt #0                */
564                                                         /* .L10: */
565         0x00, 0x00, 0x02, 0x40,         /* .word    1073872896    */
566         0x04, 0x00, 0x02, 0x40,         /* .word    1073872900    */
567         0x07, 0x00, 0x02, 0x40,         /* .word    1073872903    */
568         0x08, 0x00, 0x02, 0x40,         /* .word    1073872904    */
569 };
570
571 /* Program LongWord Block Write */
572 static int kinetis_write_block(struct flash_bank *bank, const uint8_t *buffer,
573                 uint32_t offset, uint32_t wcount)
574 {
575         struct target *target = bank->target;
576         uint32_t buffer_size = 2048;            /* Default minimum value */
577         struct working_area *write_algorithm;
578         struct working_area *source;
579         uint32_t address = bank->base + offset;
580         struct reg_param reg_params[3];
581         struct armv7m_algorithm armv7m_info;
582         int retval = ERROR_OK;
583
584         /* Params:
585          * r0 - workarea buffer
586          * r1 - target address
587          * r2 - wordcount
588          * Clobbered:
589          * r4 - tmp
590          * r5 - tmp
591          * r6 - tmp
592          * r7 - tmp
593          */
594
595         /* Increase buffer_size if needed */
596         if (buffer_size < (target->working_area_size/2))
597                 buffer_size = (target->working_area_size/2);
598
599         LOG_INFO("Kinetis: FLASH Write ...");
600
601         /* check code alignment */
602         if (offset & 0x1) {
603                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
604                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
605         }
606
607         /* allocate working area with flash programming code */
608         if (target_alloc_working_area(target, sizeof(kinetis_flash_write_code),
609                         &write_algorithm) != ERROR_OK) {
610                 LOG_WARNING("no working area available, can't do block memory writes");
611                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
612         }
613
614         retval = target_write_buffer(target, write_algorithm->address,
615                 sizeof(kinetis_flash_write_code), kinetis_flash_write_code);
616         if (retval != ERROR_OK)
617                 return retval;
618
619         /* memory buffer */
620         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK) {
621                 buffer_size /= 4;
622                 if (buffer_size <= 256) {
623                         /* free working area, write algorithm already allocated */
624                         target_free_working_area(target, write_algorithm);
625
626                         LOG_WARNING("No large enough working area available, can't do block memory writes");
627                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
628                 }
629         }
630
631         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
632         armv7m_info.core_mode = ARM_MODE_THREAD;
633
634         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT); /* *pLW (*buffer) */
635         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT); /* faddr */
636         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT); /* number of words to program */
637
638         /* write code buffer and use Flash programming code within kinetis       */
639         /* Set breakpoint to 0 with time-out of 1000 ms                          */
640         while (wcount > 0) {
641                 uint32_t thisrun_count = (wcount > (buffer_size / 4)) ? (buffer_size / 4) : wcount;
642
643                 retval = target_write_buffer(target, source->address, thisrun_count * 4, buffer);
644                 if (retval != ERROR_OK)
645                         break;
646
647                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
648                 buf_set_u32(reg_params[1].value, 0, 32, address);
649                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count);
650
651                 retval = target_run_algorithm(target, 0, NULL, 3, reg_params,
652                                 write_algorithm->address, 0, 100000, &armv7m_info);
653                 if (retval != ERROR_OK) {
654                         LOG_ERROR("Error executing kinetis Flash programming algorithm");
655                         retval = ERROR_FLASH_OPERATION_FAILED;
656                         break;
657                 }
658
659                 buffer += thisrun_count * 4;
660                 address += thisrun_count * 4;
661                 wcount -= thisrun_count;
662         }
663
664         target_free_working_area(target, source);
665         target_free_working_area(target, write_algorithm);
666
667         destroy_reg_param(&reg_params[0]);
668         destroy_reg_param(&reg_params[1]);
669         destroy_reg_param(&reg_params[2]);
670
671         return retval;
672 }
673
674 static int kinetis_protect(struct flash_bank *bank, int set, int first, int last)
675 {
676         LOG_WARNING("kinetis_protect not supported yet");
677         /* FIXME: TODO */
678
679         if (bank->target->state != TARGET_HALTED) {
680                 LOG_ERROR("Target not halted");
681                 return ERROR_TARGET_NOT_HALTED;
682         }
683
684         return ERROR_FLASH_BANK_INVALID;
685 }
686
687 static int kinetis_protect_check(struct flash_bank *bank)
688 {
689         struct kinetis_flash_bank *kinfo = bank->driver_priv;
690
691         if (bank->target->state != TARGET_HALTED) {
692                 LOG_ERROR("Target not halted");
693                 return ERROR_TARGET_NOT_HALTED;
694         }
695
696         if (kinfo->flash_class == FC_PFLASH) {
697                 int result;
698                 uint8_t buffer[4];
699                 uint32_t fprot, psec;
700                 int i, b;
701
702                 /* read protection register */
703                 result = target_read_memory(bank->target, FTFx_FPROT3, 1, 4, buffer);
704
705                 if (result != ERROR_OK)
706                         return result;
707
708                 fprot = target_buffer_get_u32(bank->target, buffer);
709
710                 /*
711                  * Every bit protects 1/32 of the full flash (not necessarily
712                  * just this bank), but we enforce the bank ordinals for
713                  * PFlash to start at zero.
714                  */
715                 b = kinfo->bank_ordinal * (bank->size / kinfo->protection_size);
716                 for (psec = 0, i = 0; i < bank->num_sectors; i++) {
717                         if ((fprot >> b) & 1)
718                                 bank->sectors[i].is_protected = 0;
719                         else
720                                 bank->sectors[i].is_protected = 1;
721
722                         psec += bank->sectors[i].size;
723
724                         if (psec >= kinfo->protection_size) {
725                                 psec = 0;
726                                 b++;
727                         }
728                 }
729         } else {
730                 LOG_ERROR("Protection checks for FlexNVM not yet supported");
731                 return ERROR_FLASH_BANK_INVALID;
732         }
733
734         return ERROR_OK;
735 }
736
737 static int kinetis_ftfx_command(struct flash_bank *bank, uint8_t fcmd, uint32_t faddr,
738                                 uint8_t fccob4, uint8_t fccob5, uint8_t fccob6, uint8_t fccob7,
739                                 uint8_t fccob8, uint8_t fccob9, uint8_t fccoba, uint8_t fccobb,
740                                 uint8_t *ftfx_fstat)
741 {
742         uint8_t command[12] = {faddr & 0xff, (faddr >> 8) & 0xff, (faddr >> 16) & 0xff, fcmd,
743                         fccob7, fccob6, fccob5, fccob4,
744                         fccobb, fccoba, fccob9, fccob8};
745         int result, i;
746         uint8_t buffer;
747
748         /* wait for done */
749         for (i = 0; i < 50; i++) {
750                 result =
751                         target_read_memory(bank->target, FTFx_FSTAT, 1, 1, &buffer);
752
753                 if (result != ERROR_OK)
754                         return result;
755
756                 if (buffer & 0x80)
757                         break;
758
759                 buffer = 0x00;
760         }
761
762         if (buffer != 0x80) {
763                 /* reset error flags */
764                 buffer = 0x30;
765                 result =
766                         target_write_memory(bank->target, FTFx_FSTAT, 1, 1, &buffer);
767                 if (result != ERROR_OK)
768                         return result;
769         }
770
771         result = target_write_memory(bank->target, FTFx_FCCOB3, 4, 3, command);
772
773         if (result != ERROR_OK)
774                 return result;
775
776         /* start command */
777         buffer = 0x80;
778         result = target_write_memory(bank->target, FTFx_FSTAT, 1, 1, &buffer);
779         if (result != ERROR_OK)
780                 return result;
781
782         /* wait for done */
783         for (i = 0; i < 240; i++) { /* Need longtime for "Mass Erase" Command Nemui Changed */
784                 result =
785                         target_read_memory(bank->target, FTFx_FSTAT, 1, 1, ftfx_fstat);
786
787                 if (result != ERROR_OK)
788                         return result;
789
790                 if (*ftfx_fstat & 0x80)
791                         break;
792         }
793
794         if ((*ftfx_fstat & 0xf0) != 0x80) {
795                 LOG_ERROR
796                         ("ftfx command failed FSTAT: %02X FCCOB: %02X%02X%02X%02X %02X%02X%02X%02X %02X%02X%02X%02X",
797                          *ftfx_fstat, command[3], command[2], command[1], command[0],
798                          command[7], command[6], command[5], command[4],
799                          command[11], command[10], command[9], command[8]);
800                 return ERROR_FLASH_OPERATION_FAILED;
801         }
802
803         return ERROR_OK;
804 }
805
806 COMMAND_HANDLER(kinetis_securing_test)
807 {
808         int result;
809         uint8_t ftfx_fstat;
810         struct target *target = get_current_target(CMD_CTX);
811         struct flash_bank *bank = NULL;
812
813         result = get_flash_bank_by_addr(target, 0x00000000, true, &bank);
814         if (result != ERROR_OK)
815                 return result;
816
817         assert(bank != NULL);
818
819         if (target->state != TARGET_HALTED) {
820                 LOG_ERROR("Target not halted");
821                 return ERROR_TARGET_NOT_HALTED;
822         }
823
824         return kinetis_ftfx_command(bank, FTFx_CMD_SECTERASE, bank->base + 0x00000400,
825                                       0, 0, 0, 0,  0, 0, 0, 0,  &ftfx_fstat);
826 }
827
828 static int kinetis_erase(struct flash_bank *bank, int first, int last)
829 {
830         int result, i;
831
832         if (bank->target->state != TARGET_HALTED) {
833                 LOG_ERROR("Target not halted");
834                 return ERROR_TARGET_NOT_HALTED;
835         }
836
837         if ((first > bank->num_sectors) || (last > bank->num_sectors))
838                 return ERROR_FLASH_OPERATION_FAILED;
839
840         /*
841          * FIXME: TODO: use the 'Erase Flash Block' command if the
842          * requested erase is PFlash or NVM and encompasses the entire
843          * block.  Should be quicker.
844          */
845         for (i = first; i <= last; i++) {
846                 uint8_t ftfx_fstat;
847                 /* set command and sector address */
848                 result = kinetis_ftfx_command(bank, FTFx_CMD_SECTERASE, bank->base + bank->sectors[i].offset,
849                                 0, 0, 0, 0,  0, 0, 0, 0,  &ftfx_fstat);
850
851                 if (result != ERROR_OK) {
852                         LOG_WARNING("erase sector %d failed", i);
853                         return ERROR_FLASH_OPERATION_FAILED;
854                 }
855
856                 bank->sectors[i].is_erased = 1;
857         }
858
859         if (first == 0) {
860                 LOG_WARNING
861                         ("flash configuration field erased, please reset the device");
862         }
863
864         return ERROR_OK;
865 }
866
867 static int kinetis_write(struct flash_bank *bank, const uint8_t *buffer,
868                          uint32_t offset, uint32_t count)
869 {
870         unsigned int i, result, fallback = 0;
871         uint8_t buf[8];
872         uint32_t wc;
873         struct kinetis_flash_bank *kinfo = bank->driver_priv;
874         uint8_t *new_buffer = NULL;
875
876         if (bank->target->state != TARGET_HALTED) {
877                 LOG_ERROR("Target not halted");
878                 return ERROR_TARGET_NOT_HALTED;
879         }
880
881         if (!(kinfo->flash_support & FS_PROGRAM_SECTOR)) {
882                 /* fallback to longword write */
883                 fallback = 1;
884                 LOG_WARNING("This device supports Program Longword execution only.");
885                 LOG_DEBUG("flash write into PFLASH @08%" PRIX32, offset);
886
887         } else if (kinfo->flash_class == FC_FLEX_NVM) {
888                 uint8_t ftfx_fstat;
889
890                 LOG_DEBUG("flash write into FlexNVM @%08" PRIX32, offset);
891
892                 /* make flex ram available */
893                 result = kinetis_ftfx_command(bank, FTFx_CMD_SETFLEXRAM, 0x00ff0000, 0, 0, 0, 0,  0, 0, 0, 0,  &ftfx_fstat);
894
895                 if (result != ERROR_OK)
896                         return ERROR_FLASH_OPERATION_FAILED;
897
898                 /* check if ram ready */
899                 result = target_read_memory(bank->target, FTFx_FCNFG, 1, 1, buf);
900
901                 if (result != ERROR_OK)
902                         return result;
903
904                 if (!(buf[0] & (1 << 1))) {
905                         /* fallback to longword write */
906                         fallback = 1;
907
908                         LOG_WARNING("ram not ready, fallback to slow longword write (FCNFG: %02X)", buf[0]);
909                 }
910         } else {
911                 LOG_DEBUG("flash write into PFLASH @08%" PRIX32, offset);
912         }
913
914
915         /* program section command */
916         if (fallback == 0) {
917                 /*
918                  * Kinetis uses different terms for the granularity of
919                  * sector writes, e.g. "phrase" or "128 bits".  We use
920                  * the generic term "chunk". The largest possible
921                  * Kinetis "chunk" is 16 bytes (128 bits).
922                  */
923                 unsigned prog_section_chunk_bytes = kinfo->sector_size >> 8;
924                 unsigned prog_size_bytes = kinfo->max_flash_prog_size;
925                 for (i = 0; i < count; i += prog_size_bytes) {
926                         uint8_t residual_buffer[16];
927                         uint8_t ftfx_fstat;
928                         uint32_t section_count = prog_size_bytes / prog_section_chunk_bytes;
929                         uint32_t residual_wc = 0;
930
931                         /*
932                          * Assume the word count covers an entire
933                          * sector.
934                          */
935                         wc = prog_size_bytes / 4;
936
937                         /*
938                          * If bytes to be programmed are less than the
939                          * full sector, then determine the number of
940                          * full-words to program, and put together the
941                          * residual buffer so that a full "section"
942                          * may always be programmed.
943                          */
944                         if ((count - i) < prog_size_bytes) {
945                                 /* number of bytes to program beyond full section */
946                                 unsigned residual_bc = (count-i) % prog_section_chunk_bytes;
947
948                                 /* number of complete words to copy directly from buffer */
949                                 wc = (count - i) / 4;
950
951                                 /* number of total sections to write, including residual */
952                                 section_count = DIV_ROUND_UP((count-i), prog_section_chunk_bytes);
953
954                                 /* any residual bytes delivers a whole residual section */
955                                 residual_wc = (residual_bc ? prog_section_chunk_bytes : 0)/4;
956
957                                 /* clear residual buffer then populate residual bytes */
958                                 (void) memset(residual_buffer, 0xff, prog_section_chunk_bytes);
959                                 (void) memcpy(residual_buffer, &buffer[i+4*wc], residual_bc);
960                         }
961
962                         LOG_DEBUG("write section @ %08" PRIX32 " with length %" PRIu32 " bytes",
963                                   offset + i, (uint32_t)wc*4);
964
965                         /* write data to flexram as whole-words */
966                         result = target_write_memory(bank->target, FLEXRAM, 4, wc,
967                                         buffer + i);
968
969                         if (result != ERROR_OK) {
970                                 LOG_ERROR("target_write_memory failed");
971                                 return result;
972                         }
973
974                         /* write the residual words to the flexram */
975                         if (residual_wc) {
976                                 result = target_write_memory(bank->target,
977                                                 FLEXRAM+4*wc,
978                                                 4, residual_wc,
979                                                 residual_buffer);
980
981                                 if (result != ERROR_OK) {
982                                         LOG_ERROR("target_write_memory failed");
983                                         return result;
984                                 }
985                         }
986
987                         /* execute section-write command */
988                         result = kinetis_ftfx_command(bank, FTFx_CMD_SECTWRITE, bank->base + offset + i,
989                                         section_count>>8, section_count, 0, 0,
990                                         0, 0, 0, 0,  &ftfx_fstat);
991
992                         if (result != ERROR_OK)
993                                 return ERROR_FLASH_OPERATION_FAILED;
994                 }
995         }
996         /* program longword command, not supported in "SF3" devices */
997         else if (kinfo->flash_support & FS_PROGRAM_LONGWORD) {
998                 if (count & 0x3) {
999                         uint32_t old_count = count;
1000                         count = (old_count | 3) + 1;
1001                         new_buffer = malloc(count);
1002                         if (new_buffer == NULL) {
1003                                 LOG_ERROR("odd number of bytes to write and no memory "
1004                                         "for padding buffer");
1005                                 return ERROR_FAIL;
1006                         }
1007                         LOG_INFO("odd number of bytes to write (%" PRIu32 "), extending to %" PRIu32 " "
1008                                 "and padding with 0xff", old_count, count);
1009                         memset(new_buffer, 0xff, count);
1010                         buffer = memcpy(new_buffer, buffer, old_count);
1011                 }
1012
1013                 uint32_t words_remaining = count / 4;
1014
1015                 /* try using a block write */
1016                 int retval = kinetis_write_block(bank, buffer, offset, words_remaining);
1017
1018                 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
1019                         /* if block write failed (no sufficient working area),
1020                          * we use normal (slow) single word accesses */
1021                         LOG_WARNING("couldn't use block writes, falling back to single "
1022                                 "memory accesses");
1023
1024                         for (i = 0; i < count; i += 4) {
1025                                 uint8_t ftfx_fstat;
1026
1027                                 LOG_DEBUG("write longword @ %08" PRIX32, (uint32_t)(offset + i));
1028
1029                                 uint8_t padding[4] = {0xff, 0xff, 0xff, 0xff};
1030                                 memcpy(padding, buffer + i, MIN(4, count-i));
1031
1032                                 result = kinetis_ftfx_command(bank, FTFx_CMD_LWORDPROG, bank->base + offset + i,
1033                                                 padding[3], padding[2], padding[1], padding[0],
1034                                                 0, 0, 0, 0,  &ftfx_fstat);
1035
1036                                 if (result != ERROR_OK)
1037                                         return ERROR_FLASH_OPERATION_FAILED;
1038                         }
1039                 }
1040         } else {
1041                 LOG_ERROR("Flash write strategy not implemented");
1042                 return ERROR_FLASH_OPERATION_FAILED;
1043         }
1044
1045         return ERROR_OK;
1046 }
1047
1048 static int kinetis_read_part_info(struct flash_bank *bank)
1049 {
1050         int result, i;
1051         uint32_t offset = 0;
1052         uint8_t fcfg1_nvmsize, fcfg1_pfsize, fcfg1_eesize, fcfg2_pflsh;
1053         uint32_t nvm_size = 0, pf_size = 0, ee_size = 0;
1054         unsigned num_blocks = 0, num_pflash_blocks = 0, num_nvm_blocks = 0, first_nvm_bank = 0,
1055                         reassign = 0, pflash_sector_size_bytes = 0, nvm_sector_size_bytes = 0;
1056         struct target *target = bank->target;
1057         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1058
1059         result = target_read_u32(target, SIM_SDID, &kinfo->sim_sdid);
1060         if (result != ERROR_OK)
1061                 return result;
1062
1063         if ((kinfo->sim_sdid & (~KINETIS_SDID_K_SERIES_MASK)) == 0) {
1064                 /* older K-series MCU */
1065                 uint32_t mcu_type = kinfo->sim_sdid & KINETIS_K_SDID_TYPE_MASK;
1066
1067                 switch (mcu_type) {
1068                 case KINETIS_K_SDID_K10_M50:
1069                 case KINETIS_K_SDID_K20_M50:
1070                         /* 1kB sectors */
1071                         pflash_sector_size_bytes = 1<<10;
1072                         nvm_sector_size_bytes = 1<<10;
1073                         num_blocks = 2;
1074                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR;
1075                         kinfo->max_flash_prog_size = 1<<10;
1076                         break;
1077                 case KINETIS_K_SDID_K10_M72:
1078                 case KINETIS_K_SDID_K20_M72:
1079                 case KINETIS_K_SDID_K30_M72:
1080                 case KINETIS_K_SDID_K30_M100:
1081                 case KINETIS_K_SDID_K40_M72:
1082                 case KINETIS_K_SDID_K40_M100:
1083                 case KINETIS_K_SDID_K50_M72:
1084                         /* 2kB sectors, 1kB FlexNVM sectors */
1085                         pflash_sector_size_bytes = 2<<10;
1086                         nvm_sector_size_bytes = 1<<10;
1087                         num_blocks = 2;
1088                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR;
1089                         kinfo->max_flash_prog_size = 1<<10;
1090                         break;
1091                 case KINETIS_K_SDID_K10_M100:
1092                 case KINETIS_K_SDID_K20_M100:
1093                 case KINETIS_K_SDID_K11:
1094                 case KINETIS_K_SDID_K12:
1095                 case KINETIS_K_SDID_K21_M50:
1096                 case KINETIS_K_SDID_K22_M50:
1097                 case KINETIS_K_SDID_K51_M72:
1098                 case KINETIS_K_SDID_K53:
1099                 case KINETIS_K_SDID_K60_M100:
1100                         /* 2kB sectors */
1101                         pflash_sector_size_bytes = 2<<10;
1102                         nvm_sector_size_bytes = 2<<10;
1103                         num_blocks = 2;
1104                         kinfo->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR;
1105                         kinfo->max_flash_prog_size = 2<<10;
1106                         break;
1107                 case KINETIS_K_SDID_K10_M120:
1108                 case KINETIS_K_SDID_K20_M120:
1109                 case KINETIS_K_SDID_K21_M120:
1110                 case KINETIS_K_SDID_K22_M120:
1111                 case KINETIS_K_SDID_K60_M150:
1112                 case KINETIS_K_SDID_K70_M150:
1113                         /* 4kB sectors */
1114                         pflash_sector_size_bytes = 4<<10;
1115                         nvm_sector_size_bytes = 4<<10;
1116                         num_blocks = 4;
1117                         kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
1118                         kinfo->max_flash_prog_size = 4<<10;
1119                         break;
1120                 default:
1121                         LOG_ERROR("Unsupported K-family FAMID");
1122                         return ERROR_FLASH_OPER_UNSUPPORTED;
1123                 }
1124         } else {
1125                 /* Newer K-series or KL series MCU */
1126                 switch (kinfo->sim_sdid & KINETIS_SDID_SERIESID_MASK) {
1127                 case KINETIS_SDID_SERIESID_K:
1128                         switch (kinfo->sim_sdid & (KINETIS_SDID_FAMILYID_MASK | KINETIS_SDID_SUBFAMID_MASK)) {
1129                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX2: {
1130                                 /* MK24FN1M reports as K22, this should detect it (according to errata note 1N83J) */
1131                                 uint32_t sopt1;
1132                                 result = target_read_u32(target, SIM_SOPT1, &sopt1);
1133                                 if (result != ERROR_OK)
1134                                         return result;
1135
1136                                 if (((kinfo->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K24FN1M) &&
1137                                                 ((sopt1 & KINETIS_SOPT1_RAMSIZE_MASK) == KINETIS_SOPT1_RAMSIZE_K24FN1M)) {
1138                                         /* MK24FN1M */
1139                                         pflash_sector_size_bytes = 4<<10;
1140                                         num_blocks = 2;
1141                                         kinfo->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
1142                                         kinfo->max_flash_prog_size = 1<<10;
1143                                 } else {
1144                                         /* K22 with new-style SDID? */
1145                                         break;
1146                                 }
1147                                 break;
1148                         }
1149                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX4:
1150                                 /* K24FN256 */
1151                                 pflash_sector_size_bytes = 4<<10;
1152                                 num_blocks = 1;
1153                                 kinfo->flash_support = FS_PROGRAM_LONGWORD;
1154                                 kinfo->max_flash_prog_size = 1<<10;
1155                                 break;
1156                         default:
1157                                 break;
1158                         }
1159                         break;
1160                 case KINETIS_SDID_SERIESID_KL:
1161                         /* KL-series */
1162                         pflash_sector_size_bytes = 1<<10;
1163                         nvm_sector_size_bytes = 1<<10;
1164                         num_blocks = 1;
1165                         kinfo->flash_support = FS_PROGRAM_LONGWORD;
1166                         kinfo->max_flash_prog_size = 1<<10;
1167                         break;
1168                 default:
1169                         break;
1170                 }
1171         }
1172
1173         if (pflash_sector_size_bytes == 0) {
1174                 LOG_ERROR("MCU is unsupported");
1175                 return ERROR_FLASH_OPER_UNSUPPORTED;
1176         }
1177
1178         result = target_read_u32(target, SIM_FCFG1, &kinfo->sim_fcfg1);
1179         if (result != ERROR_OK)
1180                 return result;
1181
1182         result = target_read_u32(target, SIM_FCFG2, &kinfo->sim_fcfg2);
1183         if (result != ERROR_OK)
1184                 return result;
1185         fcfg2_pflsh = (kinfo->sim_fcfg2 >> 23) & 0x01;
1186
1187         LOG_DEBUG("SDID: 0x%08" PRIX32 " FCFG1: 0x%08" PRIX32 " FCFG2: 0x%08" PRIX32, kinfo->sim_sdid,
1188                         kinfo->sim_fcfg1, kinfo->sim_fcfg2);
1189
1190         fcfg1_nvmsize = (uint8_t)((kinfo->sim_fcfg1 >> 28) & 0x0f);
1191         fcfg1_pfsize = (uint8_t)((kinfo->sim_fcfg1 >> 24) & 0x0f);
1192         fcfg1_eesize = (uint8_t)((kinfo->sim_fcfg1 >> 16) & 0x0f);
1193
1194         /* when the PFLSH bit is set, there is no FlexNVM/FlexRAM */
1195         if (!fcfg2_pflsh) {
1196                 switch (fcfg1_nvmsize) {
1197                 case 0x03:
1198                 case 0x07:
1199                 case 0x09:
1200                 case 0x0b:
1201                         nvm_size = 1 << (14 + (fcfg1_nvmsize >> 1));
1202                         break;
1203                 case 0x0f:
1204                         if (pflash_sector_size_bytes >= 4<<10)
1205                                 nvm_size = 512<<10;
1206                         else
1207                                 /* K20_100 */
1208                                 nvm_size = 256<<10;
1209                         break;
1210                 default:
1211                         nvm_size = 0;
1212                         break;
1213                 }
1214
1215                 switch (fcfg1_eesize) {
1216                 case 0x00:
1217                 case 0x01:
1218                 case 0x02:
1219                 case 0x03:
1220                 case 0x04:
1221                 case 0x05:
1222                 case 0x06:
1223                 case 0x07:
1224                 case 0x08:
1225                 case 0x09:
1226                         ee_size = (16 << (10 - fcfg1_eesize));
1227                         break;
1228                 default:
1229                         ee_size = 0;
1230                         break;
1231                 }
1232         }
1233
1234         switch (fcfg1_pfsize) {
1235         case 0x03:
1236         case 0x05:
1237         case 0x07:
1238         case 0x09:
1239         case 0x0b:
1240         case 0x0d:
1241                 pf_size = 1 << (14 + (fcfg1_pfsize >> 1));
1242                 break;
1243         case 0x0f:
1244                 if (pflash_sector_size_bytes >= 4<<10)
1245                         pf_size = 1024<<10;
1246                 else if (fcfg2_pflsh)
1247                         pf_size = 512<<10;
1248                 else
1249                         pf_size = 256<<10;
1250                 break;
1251         default:
1252                 pf_size = 0;
1253                 break;
1254         }
1255
1256         LOG_DEBUG("FlexNVM: %" PRIu32 " PFlash: %" PRIu32 " FlexRAM: %" PRIu32 " PFLSH: %d",
1257                   nvm_size, pf_size, ee_size, fcfg2_pflsh);
1258
1259         num_pflash_blocks = num_blocks / (2 - fcfg2_pflsh);
1260         first_nvm_bank = num_pflash_blocks;
1261         num_nvm_blocks = num_blocks - num_pflash_blocks;
1262
1263         LOG_DEBUG("%d blocks total: %d PFlash, %d FlexNVM",
1264                         num_blocks, num_pflash_blocks, num_nvm_blocks);
1265
1266         /*
1267          * If the flash class is already assigned, verify the
1268          * parameters.
1269          */
1270         if (kinfo->flash_class != FC_AUTO) {
1271                 if (kinfo->bank_ordinal != (unsigned) bank->bank_number) {
1272                         LOG_WARNING("Flash ordinal/bank number mismatch");
1273                         reassign = 1;
1274                 } else {
1275                         switch (kinfo->flash_class) {
1276                         case FC_PFLASH:
1277                                 if (kinfo->bank_ordinal >= first_nvm_bank) {
1278                                         LOG_WARNING("Class mismatch, bank %d is not PFlash", bank->bank_number);
1279                                         reassign = 1;
1280                                 } else if (bank->size != (pf_size / num_pflash_blocks)) {
1281                                         LOG_WARNING("PFlash size mismatch");
1282                                         reassign = 1;
1283                                 } else if (bank->base !=
1284                                          (0x00000000 + bank->size * kinfo->bank_ordinal)) {
1285                                         LOG_WARNING("PFlash address range mismatch");
1286                                         reassign = 1;
1287                                 } else if (kinfo->sector_size != pflash_sector_size_bytes) {
1288                                         LOG_WARNING("PFlash sector size mismatch");
1289                                         reassign = 1;
1290                                 } else {
1291                                         LOG_DEBUG("PFlash bank %d already configured okay",
1292                                                   kinfo->bank_ordinal);
1293                                 }
1294                                 break;
1295                         case FC_FLEX_NVM:
1296                                 if ((kinfo->bank_ordinal >= num_blocks) ||
1297                                                 (kinfo->bank_ordinal < first_nvm_bank)) {
1298                                         LOG_WARNING("Class mismatch, bank %d is not FlexNVM", bank->bank_number);
1299                                         reassign = 1;
1300                                 } else if (bank->size != (nvm_size / num_nvm_blocks)) {
1301                                         LOG_WARNING("FlexNVM size mismatch");
1302                                         reassign = 1;
1303                                 } else if (bank->base !=
1304                                                 (0x10000000 + bank->size * kinfo->bank_ordinal)) {
1305                                         LOG_WARNING("FlexNVM address range mismatch");
1306                                         reassign = 1;
1307                                 } else if (kinfo->sector_size != nvm_sector_size_bytes) {
1308                                         LOG_WARNING("FlexNVM sector size mismatch");
1309                                         reassign = 1;
1310                                 } else {
1311                                         LOG_DEBUG("FlexNVM bank %d already configured okay",
1312                                                   kinfo->bank_ordinal);
1313                                 }
1314                                 break;
1315                         case FC_FLEX_RAM:
1316                                 if (kinfo->bank_ordinal != num_blocks) {
1317                                         LOG_WARNING("Class mismatch, bank %d is not FlexRAM", bank->bank_number);
1318                                         reassign = 1;
1319                                 } else if (bank->size != ee_size) {
1320                                         LOG_WARNING("FlexRAM size mismatch");
1321                                         reassign = 1;
1322                                 } else if (bank->base != FLEXRAM) {
1323                                         LOG_WARNING("FlexRAM address mismatch");
1324                                         reassign = 1;
1325                                 } else if (kinfo->sector_size != nvm_sector_size_bytes) {
1326                                         LOG_WARNING("FlexRAM sector size mismatch");
1327                                         reassign = 1;
1328                                 } else {
1329                                         LOG_DEBUG("FlexRAM bank %d already configured okay", kinfo->bank_ordinal);
1330                                 }
1331                                 break;
1332
1333                         default:
1334                                 LOG_WARNING("Unknown or inconsistent flash class");
1335                                 reassign = 1;
1336                                 break;
1337                         }
1338                 }
1339         } else {
1340                 LOG_INFO("Probing flash info for bank %d", bank->bank_number);
1341                 reassign = 1;
1342         }
1343
1344         if (!reassign)
1345                 return ERROR_OK;
1346
1347         if ((unsigned)bank->bank_number < num_pflash_blocks) {
1348                 /* pflash, banks start at address zero */
1349                 kinfo->flash_class = FC_PFLASH;
1350                 bank->size = (pf_size / num_pflash_blocks);
1351                 bank->base = 0x00000000 + bank->size * bank->bank_number;
1352                 kinfo->sector_size = pflash_sector_size_bytes;
1353                 kinfo->protection_size = pf_size / 32;
1354         } else if ((unsigned)bank->bank_number < num_blocks) {
1355                 /* nvm, banks start at address 0x10000000 */
1356                 kinfo->flash_class = FC_FLEX_NVM;
1357                 bank->size = (nvm_size / num_nvm_blocks);
1358                 bank->base = 0x10000000 + bank->size * (bank->bank_number - first_nvm_bank);
1359                 kinfo->sector_size = nvm_sector_size_bytes;
1360                 kinfo->protection_size = 0; /* FIXME: TODO: depends on DEPART bits, chip */
1361         } else if ((unsigned)bank->bank_number == num_blocks) {
1362                 LOG_ERROR("FlexRAM support not yet implemented");
1363                 return ERROR_FLASH_OPER_UNSUPPORTED;
1364         } else {
1365                 LOG_ERROR("Cannot determine parameters for bank %d, only %d banks on device",
1366                                 bank->bank_number, num_blocks);
1367                 return ERROR_FLASH_BANK_INVALID;
1368         }
1369
1370         if (bank->sectors) {
1371                 free(bank->sectors);
1372                 bank->sectors = NULL;
1373         }
1374
1375         bank->num_sectors = bank->size / kinfo->sector_size;
1376         assert(bank->num_sectors > 0);
1377         bank->sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
1378
1379         for (i = 0; i < bank->num_sectors; i++) {
1380                 bank->sectors[i].offset = offset;
1381                 bank->sectors[i].size = kinfo->sector_size;
1382                 offset += kinfo->sector_size;
1383                 bank->sectors[i].is_erased = -1;
1384                 bank->sectors[i].is_protected = 1;
1385         }
1386
1387         return ERROR_OK;
1388 }
1389
1390 static int kinetis_probe(struct flash_bank *bank)
1391 {
1392         if (bank->target->state != TARGET_HALTED) {
1393                 LOG_WARNING("Cannot communicate... target not halted.");
1394                 return ERROR_TARGET_NOT_HALTED;
1395         }
1396
1397         return kinetis_read_part_info(bank);
1398 }
1399
1400 static int kinetis_auto_probe(struct flash_bank *bank)
1401 {
1402         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1403
1404         if (kinfo->sim_sdid)
1405                 return ERROR_OK;
1406
1407         return kinetis_probe(bank);
1408 }
1409
1410 static int kinetis_info(struct flash_bank *bank, char *buf, int buf_size)
1411 {
1412         const char *bank_class_names[] = {
1413                 "(ANY)", "PFlash", "FlexNVM", "FlexRAM"
1414         };
1415
1416         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1417
1418         (void) snprintf(buf, buf_size,
1419                         "%s driver for %s flash bank %s at 0x%8.8" PRIx32 "",
1420                         bank->driver->name, bank_class_names[kinfo->flash_class],
1421                         bank->name, bank->base);
1422
1423         return ERROR_OK;
1424 }
1425
1426 static int kinetis_blank_check(struct flash_bank *bank)
1427 {
1428         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1429
1430         if (bank->target->state != TARGET_HALTED) {
1431                 LOG_ERROR("Target not halted");
1432                 return ERROR_TARGET_NOT_HALTED;
1433         }
1434
1435         if (kinfo->flash_class == FC_PFLASH) {
1436                 int result;
1437                 uint8_t ftfx_fstat;
1438
1439                 /* check if whole bank is blank */
1440                 result = kinetis_ftfx_command(bank, FTFx_CMD_BLOCKSTAT, bank->base, 0, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
1441
1442                 if (result != ERROR_OK)
1443                         return result;
1444
1445                 if (ftfx_fstat & 0x01) {
1446                         /* the whole bank is not erased, check sector-by-sector */
1447                         int i;
1448                         for (i = 0; i < bank->num_sectors; i++) {
1449                                 /* normal margin */
1450                                 result = kinetis_ftfx_command(bank, FTFx_CMD_SECTSTAT, bank->base + bank->sectors[i].offset,
1451                                                 1, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
1452
1453                                 if (result == ERROR_OK) {
1454                                         bank->sectors[i].is_erased = !(ftfx_fstat & 0x01);
1455                                 } else {
1456                                         LOG_DEBUG("Ignoring errored PFlash sector blank-check");
1457                                         bank->sectors[i].is_erased = -1;
1458                                 }
1459                         }
1460                 } else {
1461                         /* the whole bank is erased, update all sectors */
1462                         int i;
1463                         for (i = 0; i < bank->num_sectors; i++)
1464                                 bank->sectors[i].is_erased = 1;
1465                 }
1466         } else {
1467                 LOG_WARNING("kinetis_blank_check not supported yet for FlexNVM");
1468                 return ERROR_FLASH_OPERATION_FAILED;
1469         }
1470
1471         return ERROR_OK;
1472 }
1473
1474 static const struct command_registration kinetis_securtiy_command_handlers[] = {
1475         {
1476                 .name = "check_security",
1477                 .mode = COMMAND_EXEC,
1478                 .help = "",
1479                 .usage = "",
1480                 .handler = kinetis_check_flash_security_status,
1481         },
1482         {
1483                 .name = "mass_erase",
1484                 .mode = COMMAND_EXEC,
1485                 .help = "",
1486                 .usage = "",
1487                 .handler = kinetis_mdm_mass_erase,
1488         },
1489         {
1490                 .name = "test_securing",
1491                 .mode = COMMAND_EXEC,
1492                 .help = "",
1493                 .usage = "",
1494                 .handler = kinetis_securing_test,
1495         },
1496         COMMAND_REGISTRATION_DONE
1497 };
1498
1499 static const struct command_registration kinetis_exec_command_handlers[] = {
1500         {
1501                 .name = "mdm",
1502                 .mode = COMMAND_ANY,
1503                 .help = "",
1504                 .usage = "",
1505                 .chain = kinetis_securtiy_command_handlers,
1506         },
1507         COMMAND_REGISTRATION_DONE
1508 };
1509
1510 static const struct command_registration kinetis_command_handler[] = {
1511         {
1512                 .name = "kinetis",
1513                 .mode = COMMAND_ANY,
1514                 .help = "kinetis NAND flash controller commands",
1515                 .usage = "",
1516                 .chain = kinetis_exec_command_handlers,
1517         },
1518         COMMAND_REGISTRATION_DONE
1519 };
1520
1521
1522
1523 struct flash_driver kinetis_flash = {
1524         .name = "kinetis",
1525         .commands = kinetis_command_handler,
1526         .flash_bank_command = kinetis_flash_bank_command,
1527         .erase = kinetis_erase,
1528         .protect = kinetis_protect,
1529         .write = kinetis_write,
1530         .read = default_flash_read,
1531         .probe = kinetis_probe,
1532         .auto_probe = kinetis_auto_probe,
1533         .erase_check = kinetis_blank_check,
1534         .protect_check = kinetis_protect_check,
1535         .info = kinetis_info,
1536 };