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