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