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