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