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