kinetis : Add flash sector size detection for K21 MCU.
[fw/openocd] / src / flash / nor / kinetis.c
1 /***************************************************************************
2  *   Copyright (C) 2011 by Mathias Kuester                                 *
3  *   kesmtp@freenet.de                                                     *
4  *                                                                         *
5  *   Copyright (C) 2011 sleep(5) ltd                                       *
6  *   tomas@sleepfive.com                                                   *
7  *                                                                         *
8  *   Copyright (C) 2012 by Christopher D. Kilgour                          *
9  *   techie at whiterocker.com                                             *
10  *                                                                         *
11  *   Copyright (C) 2013 Nemui Trinomius                                    *
12  *   nemuisan_kawausogasuki@live.jp                                        *
13  *                                                                         *
14  *   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
39 /*
40  * Implementation Notes
41  *
42  * The persistent memories in the Kinetis chip families K10 through
43  * K70 are all manipulated with the Flash Memory Module.  Some
44  * variants call this module the FTFE, others call it the FTFL.  To
45  * indicate that both are considered here, we use FTFX.
46  *
47  * Within the module, according to the chip variant, the persistent
48  * memory is divided into what Freescale terms Program Flash, FlexNVM,
49  * and FlexRAM.  All chip variants have Program Flash.  Some chip
50  * variants also have FlexNVM and FlexRAM, which always appear
51  * together.
52  *
53  * A given Kinetis chip may have 2 or 4 blocks of flash.  Here we map
54  * each block to a separate bank.  Each block size varies by chip and
55  * may be determined by the read-only SIM_FCFG1 register.  The sector
56  * size within each bank/block varies by the chip granularity as
57  * described below.
58  *
59  * Kinetis offers four different of flash granularities applicable
60  * across the chip families.  The granularity is apparently reflected
61  * by at least the reference manual suffix.  For example, for chip
62  * MK60FN1M0VLQ12, reference manual K60P144M150SF3RM ends in "SF3RM",
63  * where the "3" indicates there are four flash blocks with 4kiB
64  * sectors.  All possible granularities are indicated below.
65  *
66  * The first half of the flash (1 or 2 blocks, depending on the
67  * granularity) is always Program Flash and always starts at address
68  * 0x00000000.  The "PFLSH" flag, bit 23 of the read-only SIM_FCFG2
69  * register, determines whether the second half of the flash is also
70  * Program Flash or FlexNVM+FlexRAM.  When PFLSH is set, the second
71  * half of flash is Program Flash and is contiguous in the memory map
72  * from the first half.  When PFLSH is clear, the second half of flash
73  * is FlexNVM and always starts at address 0x10000000.  FlexRAM, which
74  * is also present when PFLSH is clear, always starts at address
75  * 0x14000000.
76  *
77  * The Flash Memory Module provides a register set where flash
78  * commands are loaded to perform flash operations like erase and
79  * program.  Different commands are available depending on whether
80  * Program Flash or FlexNVM/FlexRAM is being manipulated.  Although
81  * the commands used are quite consistent between flash blocks, the
82  * parameters they accept differ according to the flash granularity.
83  * Some Kinetis chips have different granularity between Program Flash
84  * and FlexNVM/FlexRAM, so flash command arguments may differ between
85  * blocks in the same chip.
86  *
87  * Although not documented as such by Freescale, it appears that bits
88  * 8:7 of the read-only SIM_SDID register reflect the granularity
89  * settings 0..3, so sector sizes and block counts are applicable
90  * according to the following table.
91  * NB. These undocumented bits does not work for all MCUs.
92  * A more reliable way is to detect the particular MCU model from the
93  * SDID field and pick the correct granularity based on that. See
94  * the handling of K21 in kinetis_read_part_info() for an example.
95  */
96
97 const struct {
98         unsigned pflash_sector_size_bytes;
99         unsigned nvm_sector_size_bytes;
100         unsigned num_blocks;
101 } kinetis_flash_params[4] = {
102         { 1<<10, 1<<10, 2 },
103         { 2<<10, 1<<10, 2 },
104         { 2<<10, 2<<10, 2 },
105         { 4<<10, 4<<10, 4 }
106 };
107
108 /* Addressess */
109 #define FLEXRAM         0x14000000
110 #define FTFx_FSTAT      0x40020000
111 #define FTFx_FCNFG      0x40020001
112 #define FTFx_FCCOB3     0x40020004
113 #define FTFx_FPROT3     0x40020010
114 #define SIM_SDID        0x40048024
115 #define SIM_FCFG1       0x4004804c
116 #define SIM_FCFG2       0x40048050
117
118 /* Commands */
119 #define FTFx_CMD_BLOCKSTAT  0x00
120 #define FTFx_CMD_SECTSTAT   0x01
121 #define FTFx_CMD_LWORDPROG  0x06
122 #define FTFx_CMD_SECTERASE  0x09
123 #define FTFx_CMD_SECTWRITE  0x0b
124 #define FTFx_CMD_SETFLEXRAM 0x81
125 #define FTFx_CMD_MASSERASE  0x44
126
127 #define KINETIS_SDID_FAMID_MASK 0x00000070
128 #define KINETIS_SDID_FAMID_K10  0x00000000
129 #define KINETIS_SDID_FAMID_K12  0x00000000
130 #define KINETIS_SDID_FAMID_K20  0x00000010
131 #define KINETIS_SDID_FAMID_K22  0x00000010
132 #define KINETIS_SDID_FAMID_K30  0x00000020
133 #define KINETIS_SDID_FAMID_K11  0x00000020
134 #define KINETIS_SDID_FAMID_K61  0x00000020
135 #define KINETIS_SDID_FAMID_K40  0x00000030
136 #define KINETIS_SDID_FAMID_K21  0x00000030
137 #define KINETIS_SDID_FAMID_K60  0x00000040
138 #define KINETIS_SDID_FAMID_K62  0x00000040
139 #define KINETIS_SDID_FAMID_K70  0x00000050
140 #define KINETIS_SDID_FAMID_KW24 0x00000060
141
142 struct kinetis_flash_bank {
143         unsigned granularity;
144         unsigned bank_ordinal;
145         uint32_t sector_size;
146         uint32_t protection_size;
147         uint32_t klxx;
148
149         uint32_t sim_sdid;
150         uint32_t sim_fcfg1;
151         uint32_t sim_fcfg2;
152
153         enum {
154                 FC_AUTO = 0,
155                 FC_PFLASH,
156                 FC_FLEX_NVM,
157                 FC_FLEX_RAM,
158         } flash_class;
159 };
160
161 FLASH_BANK_COMMAND_HANDLER(kinetis_flash_bank_command)
162 {
163         struct kinetis_flash_bank *bank_info;
164
165         if (CMD_ARGC < 6)
166                 return ERROR_COMMAND_SYNTAX_ERROR;
167
168         LOG_INFO("add flash_bank kinetis %s", bank->name);
169
170         bank_info = malloc(sizeof(struct kinetis_flash_bank));
171
172         memset(bank_info, 0, sizeof(struct kinetis_flash_bank));
173
174         bank->driver_priv = bank_info;
175
176         return ERROR_OK;
177 }
178
179 /* Kinetis Program-LongWord Microcodes */
180 static const uint8_t kinetis_flash_write_code[] = {
181         /* Params:
182          * r0 - workarea buffer
183         * r1 - target address
184         * r2 - wordcount
185         * Clobbered:
186         * r4 - tmp
187         * r5 - tmp
188         * r6 - tmp
189         * r7 - tmp
190         */
191
192                                                         /* .L1: */
193                                                 /* for(register uint32_t i=0;i<wcount;i++){ */
194         0x04, 0x1C,                                     /* mov    r4, r0          */
195         0x00, 0x23,                                     /* mov    r3, #0          */
196                                                         /* .L2: */
197         0x0E, 0x1A,                                     /* sub    r6, r1, r0      */
198         0xA6, 0x19,                                     /* add    r6, r4, r6      */
199         0x93, 0x42,                                     /* cmp    r3, r2          */
200         0x16, 0xD0,                                     /* beq    .L9             */
201                                                         /* .L5: */
202                                                 /* while((FTFx_FSTAT&FTFA_FSTAT_CCIF_MASK) != FTFA_FSTAT_CCIF_MASK){}; */
203         0x0B, 0x4D,                                     /* ldr    r5, .L10        */
204         0x2F, 0x78,                                     /* ldrb   r7, [r5]        */
205         0x7F, 0xB2,                                     /* sxtb   r7, r7          */
206         0x00, 0x2F,                                     /* cmp    r7, #0          */
207         0xFA, 0xDA,                                     /* bge    .L5             */
208                                                 /* FTFx_FSTAT = FTFA_FSTAT_ACCERR_MASK|FTFA_FSTAT_FPVIOL_MASK|FTFA_FSTAT_RDCO */
209         0x70, 0x27,                                     /* mov    r7, #112        */
210         0x2F, 0x70,                                     /* strb   r7, [r5]        */
211                                                 /* FTFx_FCCOB3 = faddr; */
212         0x09, 0x4F,                                     /* ldr    r7, .L10+4      */
213         0x3E, 0x60,                                     /* str    r6, [r7]        */
214         0x06, 0x27,                                     /* mov    r7, #6          */
215                                                 /* FTFx_FCCOB0 = 0x06;  */
216         0x08, 0x4E,                                     /* ldr    r6, .L10+8      */
217         0x37, 0x70,                                     /* strb   r7, [r6]        */
218                                                 /* FTFx_FCCOB7 = *pLW;  */
219         0x80, 0xCC,                                     /* ldmia  r4!, {r7}       */
220         0x08, 0x4E,                                     /* ldr    r6, .L10+12     */
221         0x37, 0x60,                                     /* str    r7, [r6]        */
222                                                 /* FTFx_FSTAT = FTFA_FSTAT_CCIF_MASK; */
223         0x80, 0x27,                                     /* mov    r7, #128        */
224         0x2F, 0x70,                                     /* strb   r7, [r5]        */
225                                                         /* .L4: */
226                                                 /* while((FTFx_FSTAT&FTFA_FSTAT_CCIF_MASK) != FTFA_FSTAT_CCIF_MASK){}; */
227         0x2E, 0x78,                                     /* ldrb    r6, [r5]       */
228         0x77, 0xB2,                                     /* sxtb    r7, r6         */
229         0x00, 0x2F,                                     /* cmp     r7, #0         */
230         0xFB, 0xDA,                                     /* bge     .L4            */
231         0x01, 0x33,                                     /* add     r3, r3, #1     */
232         0xE4, 0xE7,                                     /* b       .L2            */
233                                                         /* .L9: */
234         0x00, 0xBE,                                     /* bkpt #0                */
235                                                         /* .L10: */
236         0x00, 0x00, 0x02, 0x40,         /* .word    1073872896    */
237         0x04, 0x00, 0x02, 0x40,         /* .word    1073872900    */
238         0x07, 0x00, 0x02, 0x40,         /* .word    1073872903    */
239         0x08, 0x00, 0x02, 0x40,         /* .word    1073872904    */
240 };
241
242 /* Program LongWord Block Write */
243 static int kinetis_write_block(struct flash_bank *bank, uint8_t *buffer,
244                 uint32_t offset, uint32_t wcount)
245 {
246         struct target *target = bank->target;
247         uint32_t buffer_size = 2048;            /* Default minimum value */
248         struct working_area *write_algorithm;
249         struct working_area *source;
250         uint32_t address = bank->base + offset;
251         struct reg_param reg_params[3];
252         struct armv7m_algorithm armv7m_info;
253         int retval = ERROR_OK;
254
255         /* Params:
256          * r0 - workarea buffer
257          * r1 - target address
258          * r2 - wordcount
259          * Clobbered:
260          * r4 - tmp
261          * r5 - tmp
262          * r6 - tmp
263          * r7 - tmp
264          */
265
266         /* Increase buffer_size if needed */
267         if (buffer_size < (target->working_area_size/2))
268                 buffer_size = (target->working_area_size/2);
269
270         LOG_INFO("Kinetis: FLASH Write ...");
271
272         /* check code alignment */
273         if (offset & 0x1) {
274                 LOG_WARNING("offset 0x%" PRIx32 " breaks required 2-byte alignment", offset);
275                 return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
276         }
277
278         /* allocate working area with flash programming code */
279         if (target_alloc_working_area(target, sizeof(kinetis_flash_write_code),
280                         &write_algorithm) != ERROR_OK) {
281                 LOG_WARNING("no working area available, can't do block memory writes");
282                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
283         }
284
285         retval = target_write_buffer(target, write_algorithm->address,
286                 sizeof(kinetis_flash_write_code), kinetis_flash_write_code);
287         if (retval != ERROR_OK)
288                 return retval;
289
290         /* memory buffer */
291         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK) {
292                 buffer_size /= 4;
293                 if (buffer_size <= 256) {
294                         /* free working area, write algorithm already allocated */
295                         target_free_working_area(target, write_algorithm);
296
297                         LOG_WARNING("No large enough working area available, can't do block memory writes");
298                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
299                 }
300         }
301
302         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
303         armv7m_info.core_mode = ARM_MODE_THREAD;
304
305         init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT); /* *pLW (*buffer) */
306         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT); /* faddr */
307         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT); /* number of words to program */
308
309         /* write code buffer and use Flash programming code within kinetis       */
310         /* Set breakpoint to 0 with time-out of 1000 ms                          */
311         while (wcount > 0) {
312                 uint32_t thisrun_count = (wcount > (buffer_size / 4)) ? (buffer_size / 4) : wcount;
313
314                 retval = target_write_buffer(target, write_algorithm->address, 8,
315                                 kinetis_flash_write_code);
316                 if (retval != ERROR_OK)
317                         break;
318
319                 retval = target_write_buffer(target, source->address, thisrun_count * 4, buffer);
320                 if (retval != ERROR_OK)
321                         break;
322
323                 buf_set_u32(reg_params[0].value, 0, 32, source->address);
324                 buf_set_u32(reg_params[1].value, 0, 32, address);
325                 buf_set_u32(reg_params[2].value, 0, 32, thisrun_count);
326
327                 retval = target_run_algorithm(target, 0, NULL, 3, reg_params,
328                                 write_algorithm->address, 0, 100000, &armv7m_info);
329                 if (retval != ERROR_OK) {
330                         LOG_ERROR("Error executing kinetis Flash programming algorithm");
331                         retval = ERROR_FLASH_OPERATION_FAILED;
332                         break;
333                 }
334
335                 buffer += thisrun_count * 4;
336                 address += thisrun_count * 4;
337                 wcount -= thisrun_count;
338         }
339
340         target_free_working_area(target, source);
341         target_free_working_area(target, write_algorithm);
342
343         destroy_reg_param(&reg_params[0]);
344         destroy_reg_param(&reg_params[1]);
345         destroy_reg_param(&reg_params[2]);
346
347         return retval;
348 }
349
350 static int kinetis_protect(struct flash_bank *bank, int set, int first, int last)
351 {
352         LOG_WARNING("kinetis_protect not supported yet");
353         /* FIXME: TODO */
354
355         if (bank->target->state != TARGET_HALTED) {
356                 LOG_ERROR("Target not halted");
357                 return ERROR_TARGET_NOT_HALTED;
358         }
359
360         return ERROR_FLASH_BANK_INVALID;
361 }
362
363 static int kinetis_protect_check(struct flash_bank *bank)
364 {
365         struct kinetis_flash_bank *kinfo = bank->driver_priv;
366
367         if (bank->target->state != TARGET_HALTED) {
368                 LOG_ERROR("Target not halted");
369                 return ERROR_TARGET_NOT_HALTED;
370         }
371
372         if (kinfo->flash_class == FC_PFLASH) {
373                 int result;
374                 uint8_t buffer[4];
375                 uint32_t fprot, psec;
376                 int i, b;
377
378                 /* read protection register */
379                 result = target_read_memory(bank->target, FTFx_FPROT3, 1, 4, buffer);
380
381                 if (result != ERROR_OK)
382                         return result;
383
384                 fprot = target_buffer_get_u32(bank->target, buffer);
385
386                 /*
387                  * Every bit protects 1/32 of the full flash (not necessarily
388                  * just this bank), but we enforce the bank ordinals for
389                  * PFlash to start at zero.
390                  */
391                 b = kinfo->bank_ordinal * (bank->size / kinfo->protection_size);
392                 for (psec = 0, i = 0; i < bank->num_sectors; i++) {
393                         if ((fprot >> b) & 1)
394                                 bank->sectors[i].is_protected = 0;
395                         else
396                                 bank->sectors[i].is_protected = 1;
397
398                         psec += bank->sectors[i].size;
399
400                         if (psec >= kinfo->protection_size) {
401                                 psec = 0;
402                                 b++;
403                         }
404                 }
405         } else {
406                 LOG_ERROR("Protection checks for FlexNVM not yet supported");
407                 return ERROR_FLASH_BANK_INVALID;
408         }
409
410         return ERROR_OK;
411 }
412
413 static int kinetis_ftfx_command(struct flash_bank *bank, uint8_t fcmd, uint32_t faddr,
414                                 uint8_t fccob4, uint8_t fccob5, uint8_t fccob6, uint8_t fccob7,
415                                 uint8_t fccob8, uint8_t fccob9, uint8_t fccoba, uint8_t fccobb,
416                                 uint8_t *ftfx_fstat)
417 {
418         uint8_t command[12] = {faddr & 0xff, (faddr >> 8) & 0xff, (faddr >> 16) & 0xff, fcmd,
419                         fccob7, fccob6, fccob5, fccob4,
420                         fccobb, fccoba, fccob9, fccob8};
421         int result, i;
422         uint8_t buffer;
423
424         /* wait for done */
425         for (i = 0; i < 50; i++) {
426                 result =
427                         target_read_memory(bank->target, FTFx_FSTAT, 1, 1, &buffer);
428
429                 if (result != ERROR_OK)
430                         return result;
431
432                 if (buffer & 0x80)
433                         break;
434
435                 buffer = 0x00;
436         }
437
438         if (buffer != 0x80) {
439                 /* reset error flags */
440                 buffer = 0x30;
441                 result =
442                         target_write_memory(bank->target, FTFx_FSTAT, 1, 1, &buffer);
443                 if (result != ERROR_OK)
444                         return result;
445         }
446
447         result = target_write_memory(bank->target, FTFx_FCCOB3, 4, 3, command);
448
449         if (result != ERROR_OK)
450                 return result;
451
452         /* start command */
453         buffer = 0x80;
454         result = target_write_memory(bank->target, FTFx_FSTAT, 1, 1, &buffer);
455         if (result != ERROR_OK)
456                 return result;
457
458         /* wait for done */
459         for (i = 0; i < 240; i++) { /* Need Entire Erase Nemui Changed */
460                 result =
461                         target_read_memory(bank->target, FTFx_FSTAT, 1, 1, ftfx_fstat);
462
463                 if (result != ERROR_OK)
464                         return result;
465
466                 if (*ftfx_fstat & 0x80)
467                         break;
468         }
469
470         if ((*ftfx_fstat & 0xf0) != 0x80) {
471                 LOG_ERROR
472                         ("ftfx command failed FSTAT: %02X FCCOB: %02X%02X%02X%02X %02X%02X%02X%02X %02X%02X%02X%02X",
473                          *ftfx_fstat, command[3], command[2], command[1], command[0],
474                          command[7], command[6], command[5], command[4],
475                          command[11], command[10], command[9], command[8]);
476                 return ERROR_FLASH_OPERATION_FAILED;
477         }
478
479         return ERROR_OK;
480 }
481
482 static int kinetis_mass_erase(struct flash_bank *bank)
483 {
484         int result;
485         uint8_t ftfx_fstat;
486
487         if (bank->target->state != TARGET_HALTED) {
488                 LOG_ERROR("Target not halted");
489                 return ERROR_TARGET_NOT_HALTED;
490         }
491
492         /* check if whole bank is blank */
493         LOG_INFO("Kinetis L Series Erase All Blocks");
494         /* set command and sector address */
495         result = kinetis_ftfx_command(bank, FTFx_CMD_MASSERASE, 0,
496                         0, 0, 0, 0,  0, 0, 0, 0,  &ftfx_fstat);
497         /* Anyway Result, write unsecure byte */
498         /*      if (result != ERROR_OK)
499                 return result;*/
500
501         /* Write to MCU security status unsecure in Flash security byte(Work around) */
502         LOG_INFO("Write to MCU security status unsecure Anyway!");
503         uint8_t padding[4] = {0xFE, 0xFF, 0xFF, 0xFF}; /* Write 0xFFFFFFFE */
504
505         result = kinetis_ftfx_command(bank, FTFx_CMD_LWORDPROG, (bank->base + 0x0000040C),
506                                 padding[3], padding[2], padding[1], padding[0],
507                                 0, 0, 0, 0,  &ftfx_fstat);
508         if (result != ERROR_OK)
509                 return ERROR_FLASH_OPERATION_FAILED;
510
511         return ERROR_OK;
512 }
513
514 static int kinetis_erase(struct flash_bank *bank, int first, int last)
515 {
516         int result, i;
517         struct kinetis_flash_bank *kinfo = bank->driver_priv;
518
519         if (bank->target->state != TARGET_HALTED) {
520                 LOG_ERROR("Target not halted");
521                 return ERROR_TARGET_NOT_HALTED;
522         }
523
524         if ((first > bank->num_sectors) || (last > bank->num_sectors))
525                 return ERROR_FLASH_OPERATION_FAILED;
526
527         if ((first == 0) && (last == (bank->num_sectors - 1)) && (kinfo->klxx))
528                 return kinetis_mass_erase(bank);
529
530         /*
531          * FIXME: TODO: use the 'Erase Flash Block' command if the
532          * requested erase is PFlash or NVM and encompasses the entire
533          * block.  Should be quicker.
534          */
535         for (i = first; i <= last; i++) {
536                 uint8_t ftfx_fstat;
537                 /* set command and sector address */
538                 result = kinetis_ftfx_command(bank, FTFx_CMD_SECTERASE, bank->base + bank->sectors[i].offset,
539                                 0, 0, 0, 0,  0, 0, 0, 0,  &ftfx_fstat);
540
541                 if (result != ERROR_OK) {
542                         LOG_WARNING("erase sector %d failed", i);
543                         return ERROR_FLASH_OPERATION_FAILED;
544                 }
545
546                 bank->sectors[i].is_erased = 1;
547         }
548
549         if (first == 0) {
550                 LOG_WARNING
551                         ("flash configuration field erased, please reset the device");
552         }
553
554         return ERROR_OK;
555 }
556
557 static int kinetis_write(struct flash_bank *bank, uint8_t *buffer,
558                          uint32_t offset, uint32_t count)
559 {
560         unsigned int i, result, fallback = 0;
561         uint8_t buf[8];
562         uint32_t wc;
563         struct kinetis_flash_bank *kinfo = bank->driver_priv;
564         uint8_t *new_buffer = NULL;
565
566         if (bank->target->state != TARGET_HALTED) {
567                 LOG_ERROR("Target not halted");
568                 return ERROR_TARGET_NOT_HALTED;
569         }
570
571         if (kinfo->klxx) {
572                 /* fallback to longword write */
573                 fallback = 1;
574                 LOG_WARNING("Kinetis L Series supports Program Longword execution only.");
575                 LOG_DEBUG("flash write into PFLASH @08%" PRIX32, offset);
576
577         } else if (kinfo->flash_class == FC_FLEX_NVM) {
578                 uint8_t ftfx_fstat;
579
580                 LOG_DEBUG("flash write into FlexNVM @%08" PRIX32, offset);
581
582                 /* make flex ram available */
583                 result = kinetis_ftfx_command(bank, FTFx_CMD_SETFLEXRAM, 0x00ff0000, 0, 0, 0, 0,  0, 0, 0, 0,  &ftfx_fstat);
584
585                 if (result != ERROR_OK)
586                         return ERROR_FLASH_OPERATION_FAILED;
587
588                 /* check if ram ready */
589                 result = target_read_memory(bank->target, FTFx_FCNFG, 1, 1, buf);
590
591                 if (result != ERROR_OK)
592                         return result;
593
594                 if (!(buf[0] & (1 << 1))) {
595                         /* fallback to longword write */
596                         fallback = 1;
597
598                         LOG_WARNING("ram not ready, fallback to slow longword write (FCNFG: %02X)", buf[0]);
599                 }
600         } else {
601                 LOG_DEBUG("flash write into PFLASH @08%" PRIX32, offset);
602         }
603
604
605         /* program section command */
606         if (fallback == 0) {
607                 /*
608                  * Kinetis uses different terms for the granularity of
609                  * sector writes, e.g. "phrase" or "128 bits".  We use
610                  * the generic term "chunk". The largest possible
611                  * Kinetis "chunk" is 16 bytes (128 bits).
612                  */
613                 unsigned prog_section_chunk_bytes = kinfo->sector_size >> 8;
614                 /* assume the NVM sector size is half the FlexRAM size */
615                 unsigned prog_size_bytes = MIN(kinfo->sector_size,
616                                 kinetis_flash_params[kinfo->granularity].nvm_sector_size_bytes);
617                 for (i = 0; i < count; i += prog_size_bytes) {
618                         uint8_t residual_buffer[16];
619                         uint8_t ftfx_fstat;
620                         uint32_t section_count = prog_size_bytes / prog_section_chunk_bytes;
621                         uint32_t residual_wc = 0;
622
623                         /*
624                          * Assume the word count covers an entire
625                          * sector.
626                          */
627                         wc = prog_size_bytes / 4;
628
629                         /*
630                          * If bytes to be programmed are less than the
631                          * full sector, then determine the number of
632                          * full-words to program, and put together the
633                          * residual buffer so that a full "section"
634                          * may always be programmed.
635                          */
636                         if ((count - i) < prog_size_bytes) {
637                                 /* number of bytes to program beyond full section */
638                                 unsigned residual_bc = (count-i) % prog_section_chunk_bytes;
639
640                                 /* number of complete words to copy directly from buffer */
641                                 wc = (count - i) / 4;
642
643                                 /* number of total sections to write, including residual */
644                                 section_count = DIV_ROUND_UP((count-i), prog_section_chunk_bytes);
645
646                                 /* any residual bytes delivers a whole residual section */
647                                 residual_wc = (residual_bc ? prog_section_chunk_bytes : 0)/4;
648
649                                 /* clear residual buffer then populate residual bytes */
650                                 (void) memset(residual_buffer, 0xff, prog_section_chunk_bytes);
651                                 (void) memcpy(residual_buffer, &buffer[i+4*wc], residual_bc);
652                         }
653
654                         LOG_DEBUG("write section @ %08" PRIX32 " with length %" PRIu32 " bytes",
655                                   offset + i, (uint32_t)wc*4);
656
657                         /* write data to flexram as whole-words */
658                         result = target_write_memory(bank->target, FLEXRAM, 4, wc,
659                                         buffer + i);
660
661                         if (result != ERROR_OK) {
662                                 LOG_ERROR("target_write_memory failed");
663                                 return result;
664                         }
665
666                         /* write the residual words to the flexram */
667                         if (residual_wc) {
668                                 result = target_write_memory(bank->target,
669                                                 FLEXRAM+4*wc,
670                                                 4, residual_wc,
671                                                 residual_buffer);
672
673                                 if (result != ERROR_OK) {
674                                         LOG_ERROR("target_write_memory failed");
675                                         return result;
676                                 }
677                         }
678
679                         /* execute section-write command */
680                         result = kinetis_ftfx_command(bank, FTFx_CMD_SECTWRITE, bank->base + offset + i,
681                                         section_count>>8, section_count, 0, 0,
682                                         0, 0, 0, 0,  &ftfx_fstat);
683
684                         if (result != ERROR_OK)
685                                 return ERROR_FLASH_OPERATION_FAILED;
686                 }
687         }
688         /* program longword command, not supported in "SF3" devices */
689         else if ((kinfo->granularity != 3) || (kinfo->klxx)) {
690
691                 if (count & 0x3) {
692                         uint32_t old_count = count;
693                         count = (old_count | 3) + 1;
694                         new_buffer = malloc(count);
695                         if (new_buffer == NULL) {
696                                 LOG_ERROR("odd number of bytes to write and no memory "
697                                         "for padding buffer");
698                                 return ERROR_FAIL;
699                         }
700                         LOG_INFO("odd number of bytes to write (%" PRIu32 "), extending to %" PRIu32 " "
701                                 "and padding with 0xff", old_count, count);
702                         memset(buffer, 0xff, count);
703                         buffer = memcpy(new_buffer, buffer, old_count);
704                 }
705
706                 uint32_t words_remaining = count / 4;
707
708                 /* try using a block write */
709                 int retval = kinetis_write_block(bank, buffer, offset, words_remaining);
710
711                 if (retval == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
712                         /* if block write failed (no sufficient working area),
713                          * we use normal (slow) single word accesses */
714                         LOG_WARNING("couldn't use block writes, falling back to single "
715                                 "memory accesses");
716
717                         for (i = 0; i < count; i += 4) {
718                                 uint8_t ftfx_fstat;
719
720                                 LOG_DEBUG("write longword @ %08" PRIX32, (uint32_t)(offset + i));
721
722                                 uint8_t padding[4] = {0xff, 0xff, 0xff, 0xff};
723                                 memcpy(padding, buffer + i, MIN(4, count-i));
724
725                                 result = kinetis_ftfx_command(bank, FTFx_CMD_LWORDPROG, bank->base + offset + i,
726                                                 padding[3], padding[2], padding[1], padding[0],
727                                                 0, 0, 0, 0,  &ftfx_fstat);
728
729                                 if (result != ERROR_OK)
730                                         return ERROR_FLASH_OPERATION_FAILED;
731                         }
732                 }
733
734         } else {
735                 LOG_ERROR("Flash write strategy not implemented");
736                 return ERROR_FLASH_OPERATION_FAILED;
737         }
738
739         return ERROR_OK;
740 }
741
742 static int kinetis_read_part_info(struct flash_bank *bank)
743 {
744         int result, i;
745         uint32_t offset = 0;
746         uint8_t fcfg1_nvmsize, fcfg1_pfsize, fcfg1_eesize, fcfg2_pflsh;
747         uint32_t nvm_size = 0, pf_size = 0, ee_size = 0;
748         unsigned granularity, num_blocks = 0, num_pflash_blocks = 0, num_nvm_blocks = 0,
749                 first_nvm_bank = 0, reassign = 0;
750         struct target *target = bank->target;
751         struct kinetis_flash_bank *kinfo = bank->driver_priv;
752
753         result = target_read_u32(target, SIM_SDID, &kinfo->sim_sdid);
754         if (result != ERROR_OK)
755                 return result;
756
757         /* Kinetis L Series SubFamily Check */
758         kinfo->klxx = 0;
759         i = (kinfo->sim_sdid >> 20) & 0x0F;
760         if (i == 1) {
761                 kinfo->klxx = 1;
762                 granularity = 0;
763         } else if ((kinfo->sim_sdid & KINETIS_SDID_FAMID_MASK)
764                 == KINETIS_SDID_FAMID_K21) {
765                 granularity = 2;
766         } else
767                 granularity = (kinfo->sim_sdid >> 7) & 0x03;
768
769         result = target_read_u32(target, SIM_FCFG1, &kinfo->sim_fcfg1);
770         if (result != ERROR_OK)
771                 return result;
772
773         result = target_read_u32(target, SIM_FCFG2, &kinfo->sim_fcfg2);
774         if (result != ERROR_OK)
775                 return result;
776         fcfg2_pflsh = (kinfo->sim_fcfg2 >> 23) & 0x01;
777
778         LOG_DEBUG("SDID: 0x%08" PRIX32 " FCFG1: 0x%08" PRIX32 " FCFG2: 0x%08" PRIX32, kinfo->sim_sdid,
779                         kinfo->sim_fcfg1, kinfo->sim_fcfg2);
780
781         fcfg1_nvmsize = (uint8_t)((kinfo->sim_fcfg1 >> 28) & 0x0f);
782         fcfg1_pfsize = (uint8_t)((kinfo->sim_fcfg1 >> 24) & 0x0f);
783         fcfg1_eesize = (uint8_t)((kinfo->sim_fcfg1 >> 16) & 0x0f);
784
785         /* when the PFLSH bit is set, there is no FlexNVM/FlexRAM */
786         if (!fcfg2_pflsh) {
787                 switch (fcfg1_nvmsize) {
788                 case 0x03:
789                 case 0x07:
790                 case 0x09:
791                 case 0x0b:
792                         nvm_size = 1 << (14 + (fcfg1_nvmsize >> 1));
793                         break;
794                 case 0x0f:
795                         if (granularity == 3)
796                                 nvm_size = 512<<10;
797                         else
798                                 nvm_size = 256<<10;
799                         break;
800                 default:
801                         nvm_size = 0;
802                         break;
803                 }
804
805                 switch (fcfg1_eesize) {
806                 case 0x00:
807                 case 0x01:
808                 case 0x02:
809                 case 0x03:
810                 case 0x04:
811                 case 0x05:
812                 case 0x06:
813                 case 0x07:
814                 case 0x08:
815                 case 0x09:
816                         ee_size = (16 << (10 - fcfg1_eesize));
817                         break;
818                 default:
819                         ee_size = 0;
820                         break;
821                 }
822         }
823
824         switch (fcfg1_pfsize) {
825         case 0x03:
826         case 0x05:
827         case 0x07:
828         case 0x09:
829         case 0x0b:
830         case 0x0d:
831                 pf_size = 1 << (14 + (fcfg1_pfsize >> 1));
832                 break;
833         case 0x0f:
834                 if (granularity == 3)
835                         pf_size = 1024<<10;
836                 else if (fcfg2_pflsh)
837                         pf_size = 512<<10;
838                 else
839                         pf_size = 256<<10;
840                 break;
841         default:
842                 pf_size = 0;
843                 break;
844         }
845
846         LOG_DEBUG("FlexNVM: %" PRIu32 " PFlash: %" PRIu32 " FlexRAM: %" PRIu32 " PFLSH: %d",
847                   nvm_size, pf_size, ee_size, fcfg2_pflsh);
848         if (kinfo->klxx)
849                 num_blocks = 1;
850         else
851                 num_blocks = kinetis_flash_params[granularity].num_blocks;
852
853         num_pflash_blocks = num_blocks / (2 - fcfg2_pflsh);
854         first_nvm_bank = num_pflash_blocks;
855         num_nvm_blocks = num_blocks - num_pflash_blocks;
856
857         LOG_DEBUG("%d blocks total: %d PFlash, %d FlexNVM",
858                         num_blocks, num_pflash_blocks, num_nvm_blocks);
859
860         /*
861          * If the flash class is already assigned, verify the
862          * parameters.
863          */
864         if (kinfo->flash_class != FC_AUTO) {
865                 if (kinfo->bank_ordinal != (unsigned) bank->bank_number) {
866                         LOG_WARNING("Flash ordinal/bank number mismatch");
867                         reassign = 1;
868                 } else if (kinfo->granularity != granularity) {
869                         LOG_WARNING("Flash granularity mismatch");
870                         reassign = 1;
871                 } else {
872                         switch (kinfo->flash_class) {
873                         case FC_PFLASH:
874                                 if (kinfo->bank_ordinal >= first_nvm_bank) {
875                                         LOG_WARNING("Class mismatch, bank %d is not PFlash", bank->bank_number);
876                                         reassign = 1;
877                                 } else if (bank->size != (pf_size / num_pflash_blocks)) {
878                                         LOG_WARNING("PFlash size mismatch");
879                                         reassign = 1;
880                                 } else if (bank->base !=
881                                          (0x00000000 + bank->size * kinfo->bank_ordinal)) {
882                                         LOG_WARNING("PFlash address range mismatch");
883                                         reassign = 1;
884                                 } else if (kinfo->sector_size !=
885                                                 kinetis_flash_params[granularity].pflash_sector_size_bytes) {
886                                         LOG_WARNING("PFlash sector size mismatch");
887                                         reassign = 1;
888                                 } else {
889                                         LOG_DEBUG("PFlash bank %d already configured okay",
890                                                   kinfo->bank_ordinal);
891                                 }
892                                 break;
893                         case FC_FLEX_NVM:
894                                 if ((kinfo->bank_ordinal >= num_blocks) ||
895                                                 (kinfo->bank_ordinal < first_nvm_bank)) {
896                                         LOG_WARNING("Class mismatch, bank %d is not FlexNVM", bank->bank_number);
897                                         reassign = 1;
898                                 } else if (bank->size != (nvm_size / num_nvm_blocks)) {
899                                         LOG_WARNING("FlexNVM size mismatch");
900                                         reassign = 1;
901                                 } else if (bank->base !=
902                                                 (0x10000000 + bank->size * kinfo->bank_ordinal)) {
903                                         LOG_WARNING("FlexNVM address range mismatch");
904                                         reassign = 1;
905                                 } else if (kinfo->sector_size !=
906                                                 kinetis_flash_params[granularity].nvm_sector_size_bytes) {
907                                         LOG_WARNING("FlexNVM sector size mismatch");
908                                         reassign = 1;
909                                 } else {
910                                         LOG_DEBUG("FlexNVM bank %d already configured okay",
911                                                   kinfo->bank_ordinal);
912                                 }
913                                 break;
914                         case FC_FLEX_RAM:
915                                 if (kinfo->bank_ordinal != num_blocks) {
916                                         LOG_WARNING("Class mismatch, bank %d is not FlexRAM", bank->bank_number);
917                                         reassign = 1;
918                                 } else if (bank->size != ee_size) {
919                                         LOG_WARNING("FlexRAM size mismatch");
920                                         reassign = 1;
921                                 } else if (bank->base != FLEXRAM) {
922                                         LOG_WARNING("FlexRAM address mismatch");
923                                         reassign = 1;
924                                 } else if (kinfo->sector_size !=
925                                          kinetis_flash_params[granularity].nvm_sector_size_bytes) {
926                                         LOG_WARNING("FlexRAM sector size mismatch");
927                                         reassign = 1;
928                                 } else {
929                                         LOG_DEBUG("FlexRAM bank %d already configured okay", kinfo->bank_ordinal);
930                                 }
931                                 break;
932
933                         default:
934                                 LOG_WARNING("Unknown or inconsistent flash class");
935                                 reassign = 1;
936                                 break;
937                         }
938                 }
939         } else {
940                 LOG_INFO("Probing flash info for bank %d", bank->bank_number);
941                 reassign = 1;
942         }
943
944         if (!reassign)
945                 return ERROR_OK;
946
947         kinfo->granularity = granularity;
948
949         if ((unsigned)bank->bank_number < num_pflash_blocks) {
950                 /* pflash, banks start at address zero */
951                 kinfo->flash_class = FC_PFLASH;
952                 bank->size = (pf_size / num_pflash_blocks);
953                 bank->base = 0x00000000 + bank->size * bank->bank_number;
954                 kinfo->sector_size = kinetis_flash_params[granularity].pflash_sector_size_bytes;
955                 kinfo->protection_size = pf_size / 32;
956         } else if ((unsigned)bank->bank_number < num_blocks) {
957                 /* nvm, banks start at address 0x10000000 */
958                 kinfo->flash_class = FC_FLEX_NVM;
959                 bank->size = (nvm_size / num_nvm_blocks);
960                 bank->base = 0x10000000 + bank->size * (bank->bank_number - first_nvm_bank);
961                 kinfo->sector_size = kinetis_flash_params[granularity].nvm_sector_size_bytes;
962                 kinfo->protection_size = 0; /* FIXME: TODO: depends on DEPART bits, chip */
963         } else if ((unsigned)bank->bank_number == num_blocks) {
964                 LOG_ERROR("FlexRAM support not yet implemented");
965                 return ERROR_FLASH_OPER_UNSUPPORTED;
966         } else {
967                 LOG_ERROR("Cannot determine parameters for bank %d, only %d banks on device",
968                                 bank->bank_number, num_blocks);
969                 return ERROR_FLASH_BANK_INVALID;
970         }
971
972         if (bank->sectors) {
973                 free(bank->sectors);
974                 bank->sectors = NULL;
975         }
976
977         bank->num_sectors = bank->size / kinfo->sector_size;
978         assert(bank->num_sectors > 0);
979         bank->sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
980
981         for (i = 0; i < bank->num_sectors; i++) {
982                 bank->sectors[i].offset = offset;
983                 bank->sectors[i].size = kinfo->sector_size;
984                 offset += kinfo->sector_size;
985                 bank->sectors[i].is_erased = -1;
986                 bank->sectors[i].is_protected = 1;
987         }
988
989         return ERROR_OK;
990 }
991
992 static int kinetis_probe(struct flash_bank *bank)
993 {
994         if (bank->target->state != TARGET_HALTED) {
995                 LOG_WARNING("Cannot communicate... target not halted.");
996                 return ERROR_TARGET_NOT_HALTED;
997         }
998
999         return kinetis_read_part_info(bank);
1000 }
1001
1002 static int kinetis_auto_probe(struct flash_bank *bank)
1003 {
1004         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1005
1006         if (kinfo->sim_sdid)
1007                 return ERROR_OK;
1008
1009         return kinetis_probe(bank);
1010 }
1011
1012 static int kinetis_info(struct flash_bank *bank, char *buf, int buf_size)
1013 {
1014         const char *bank_class_names[] = {
1015                 "(ANY)", "PFlash", "FlexNVM", "FlexRAM"
1016         };
1017
1018         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1019
1020         (void) snprintf(buf, buf_size,
1021                         "%s driver for %s flash bank %s at 0x%8.8" PRIx32 "",
1022                         bank->driver->name, bank_class_names[kinfo->flash_class],
1023                         bank->name, bank->base);
1024
1025         return ERROR_OK;
1026 }
1027
1028 static int kinetis_blank_check(struct flash_bank *bank)
1029 {
1030         struct kinetis_flash_bank *kinfo = bank->driver_priv;
1031
1032         if (bank->target->state != TARGET_HALTED) {
1033                 LOG_ERROR("Target not halted");
1034                 return ERROR_TARGET_NOT_HALTED;
1035         }
1036
1037         if (kinfo->flash_class == FC_PFLASH) {
1038                 int result;
1039                 uint8_t ftfx_fstat;
1040
1041                 /* check if whole bank is blank */
1042                 result = kinetis_ftfx_command(bank, FTFx_CMD_BLOCKSTAT, bank->base, 0, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
1043
1044                 if (result != ERROR_OK)
1045                         return result;
1046
1047                 if (ftfx_fstat & 0x01) {
1048                         /* the whole bank is not erased, check sector-by-sector */
1049                         int i;
1050                         for (i = 0; i < bank->num_sectors; i++) {
1051                                 /* normal margin */
1052                                 result = kinetis_ftfx_command(bank, FTFx_CMD_SECTSTAT, bank->base + bank->sectors[i].offset,
1053                                                 1, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
1054
1055                                 if (result == ERROR_OK) {
1056                                         bank->sectors[i].is_erased = !(ftfx_fstat & 0x01);
1057                                 } else {
1058                                         LOG_DEBUG("Ignoring errored PFlash sector blank-check");
1059                                         bank->sectors[i].is_erased = -1;
1060                                 }
1061                         }
1062                 } else {
1063                         /* the whole bank is erased, update all sectors */
1064                         int i;
1065                         for (i = 0; i < bank->num_sectors; i++)
1066                                 bank->sectors[i].is_erased = 1;
1067                 }
1068         } else {
1069                 LOG_WARNING("kinetis_blank_check not supported yet for FlexNVM");
1070                 return ERROR_FLASH_OPERATION_FAILED;
1071         }
1072
1073         return ERROR_OK;
1074 }
1075
1076 struct flash_driver kinetis_flash = {
1077         .name = "kinetis",
1078         .flash_bank_command = kinetis_flash_bank_command,
1079         .erase = kinetis_erase,
1080         .protect = kinetis_protect,
1081         .write = kinetis_write,
1082         .read = default_flash_read,
1083         .probe = kinetis_probe,
1084         .auto_probe = kinetis_auto_probe,
1085         .erase_check = kinetis_blank_check,
1086         .protect_check = kinetis_protect_check,
1087         .info = kinetis_info,
1088 };