flash/nor/kinetis: fix clang static analyzer warnings
[fw/openocd] / src / flash / nor / kinetis.c
1 /***************************************************************************
2  *   Copyright (C) 2011 by Mathias Kuester                                 *
3  *   kesmtp@freenet.de                                                     *
4  *                                                                         *
5  *   Copyright (C) 2011 sleep(5) ltd                                       *
6  *   tomas@sleepfive.com                                                   *
7  *                                                                         *
8  *   Copyright (C) 2012 by Christopher D. Kilgour                          *
9  *   techie at whiterocker.com                                             *
10  *                                                                         *
11  *   Copyright (C) 2013 Nemui Trinomius                                    *
12  *   nemuisan_kawausogasuki@live.jp                                        *
13  *                                                                         *
14  *   Copyright (C) 2015 Tomas Vanek                                        *
15  *   vanekt@fbl.cz                                                         *
16  *                                                                         *
17  *   This program is free software; you can redistribute it and/or modify  *
18  *   it under the terms of the GNU General Public License as published by  *
19  *   the Free Software Foundation; either version 2 of the License, or     *
20  *   (at your option) any later version.                                   *
21  *                                                                         *
22  *   This program is distributed in the hope that it will be useful,       *
23  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
24  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
25  *   GNU General Public License for more details.                          *
26  *                                                                         *
27  *   You should have received a copy of the GNU General Public License     *
28  *   along with this program.  If not, 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 FCF_ADDRESS     0x00000400
84 #define FCF_FPROT       0x8
85 #define FCF_FSEC        0xc
86 #define FCF_FOPT        0xd
87 #define FCF_FDPROT      0xf
88 #define FCF_SIZE        0x10
89
90 #define FLEXRAM         0x14000000
91
92 #define MSCM_OCMDR0     0x40001400
93 #define FMC_PFB01CR     0x4001f004
94 #define FTFx_FSTAT      0x40020000
95 #define FTFx_FCNFG      0x40020001
96 #define FTFx_FCCOB3     0x40020004
97 #define FTFx_FPROT3     0x40020010
98 #define FTFx_FDPROT     0x40020017
99 #define SIM_BASE        0x40047000
100 #define SIM_BASE_KL28   0x40074000
101 #define SIM_COPC        0x40048100
102         /* SIM_COPC does not exist on devices with changed SIM_BASE */
103 #define WDOG_BASE       0x40052000
104 #define WDOG32_KE1X     0x40052000
105 #define WDOG32_KL28     0x40076000
106 #define SMC_PMCTRL      0x4007E001
107 #define SMC_PMSTAT      0x4007E003
108 #define SMC32_PMCTRL    0x4007E00C
109 #define SMC32_PMSTAT    0x4007E014
110 #define MCM_PLACR       0xF000300C
111
112 /* Offsets */
113 #define SIM_SOPT1_OFFSET    0x0000
114 #define SIM_SDID_OFFSET     0x1024
115 #define SIM_FCFG1_OFFSET    0x104c
116 #define SIM_FCFG2_OFFSET    0x1050
117
118 #define WDOG_STCTRLH_OFFSET      0
119 #define WDOG32_CS_OFFSET         0
120
121 /* Values */
122 #define PM_STAT_RUN             0x01
123 #define PM_STAT_VLPR            0x04
124 #define PM_CTRL_RUNM_RUN        0x00
125
126 /* Commands */
127 #define FTFx_CMD_BLOCKSTAT  0x00
128 #define FTFx_CMD_SECTSTAT   0x01
129 #define FTFx_CMD_LWORDPROG  0x06
130 #define FTFx_CMD_SECTERASE  0x09
131 #define FTFx_CMD_SECTWRITE  0x0b
132 #define FTFx_CMD_MASSERASE  0x44
133 #define FTFx_CMD_PGMPART    0x80
134 #define FTFx_CMD_SETFLEXRAM 0x81
135
136 /* The older Kinetis K series uses the following SDID layout :
137  * Bit 31-16 : 0
138  * Bit 15-12 : REVID
139  * Bit 11-7  : DIEID
140  * Bit 6-4   : FAMID
141  * Bit 3-0   : PINID
142  *
143  * The newer Kinetis series uses the following SDID layout :
144  * Bit 31-28 : FAMID
145  * Bit 27-24 : SUBFAMID
146  * Bit 23-20 : SERIESID
147  * Bit 19-16 : SRAMSIZE
148  * Bit 15-12 : REVID
149  * Bit 6-4   : Reserved (0)
150  * Bit 3-0   : PINID
151  *
152  * We assume that if bits 31-16 are 0 then it's an older
153  * K-series MCU.
154  */
155
156 #define KINETIS_SOPT1_RAMSIZE_MASK  0x0000F000
157 #define KINETIS_SOPT1_RAMSIZE_K24FN1M 0x0000B000
158
159 #define KINETIS_SDID_K_SERIES_MASK  0x0000FFFF
160
161 #define KINETIS_SDID_DIEID_MASK 0x00000F80
162
163 #define KINETIS_SDID_DIEID_K22FN128     0x00000680 /* smaller pflash with FTFA */
164 #define KINETIS_SDID_DIEID_K22FN256     0x00000A80
165 #define KINETIS_SDID_DIEID_K22FN512     0x00000E80
166 #define KINETIS_SDID_DIEID_K24FN256     0x00000700
167
168 #define KINETIS_SDID_DIEID_K24FN1M      0x00000300 /* Detect Errata 7534 */
169
170 /* We can't rely solely on the FAMID field to determine the MCU
171  * type since some FAMID values identify multiple MCUs with
172  * different flash sector sizes (K20 and K22 for instance).
173  * Therefore we combine it with the DIEID bits which may possibly
174  * break if Freescale bumps the DIEID for a particular MCU. */
175 #define KINETIS_K_SDID_TYPE_MASK 0x00000FF0
176 #define KINETIS_K_SDID_K10_M50   0x00000000
177 #define KINETIS_K_SDID_K10_M72   0x00000080
178 #define KINETIS_K_SDID_K10_M100  0x00000100
179 #define KINETIS_K_SDID_K10_M120  0x00000180
180 #define KINETIS_K_SDID_K11               0x00000220
181 #define KINETIS_K_SDID_K12               0x00000200
182 #define KINETIS_K_SDID_K20_M50   0x00000010
183 #define KINETIS_K_SDID_K20_M72   0x00000090
184 #define KINETIS_K_SDID_K20_M100  0x00000110
185 #define KINETIS_K_SDID_K20_M120  0x00000190
186 #define KINETIS_K_SDID_K21_M50   0x00000230
187 #define KINETIS_K_SDID_K21_M120  0x00000330
188 #define KINETIS_K_SDID_K22_M50   0x00000210
189 #define KINETIS_K_SDID_K22_M120  0x00000310
190 #define KINETIS_K_SDID_K30_M72   0x000000A0
191 #define KINETIS_K_SDID_K30_M100  0x00000120
192 #define KINETIS_K_SDID_K40_M72   0x000000B0
193 #define KINETIS_K_SDID_K40_M100  0x00000130
194 #define KINETIS_K_SDID_K50_M72   0x000000E0
195 #define KINETIS_K_SDID_K51_M72   0x000000F0
196 #define KINETIS_K_SDID_K53               0x00000170
197 #define KINETIS_K_SDID_K60_M100  0x00000140
198 #define KINETIS_K_SDID_K60_M150  0x000001C0
199 #define KINETIS_K_SDID_K70_M150  0x000001D0
200
201 #define KINETIS_SDID_SERIESID_MASK 0x00F00000
202 #define KINETIS_SDID_SERIESID_K   0x00000000
203 #define KINETIS_SDID_SERIESID_KL   0x00100000
204 #define KINETIS_SDID_SERIESID_KE   0x00200000
205 #define KINETIS_SDID_SERIESID_KW   0x00500000
206 #define KINETIS_SDID_SERIESID_KV   0x00600000
207
208 #define KINETIS_SDID_SUBFAMID_SHIFT 24
209 #define KINETIS_SDID_SUBFAMID_MASK  0x0F000000
210 #define KINETIS_SDID_SUBFAMID_KX0   0x00000000
211 #define KINETIS_SDID_SUBFAMID_KX1   0x01000000
212 #define KINETIS_SDID_SUBFAMID_KX2   0x02000000
213 #define KINETIS_SDID_SUBFAMID_KX3   0x03000000
214 #define KINETIS_SDID_SUBFAMID_KX4   0x04000000
215 #define KINETIS_SDID_SUBFAMID_KX5   0x05000000
216 #define KINETIS_SDID_SUBFAMID_KX6   0x06000000
217 #define KINETIS_SDID_SUBFAMID_KX7   0x07000000
218 #define KINETIS_SDID_SUBFAMID_KX8   0x08000000
219
220 #define KINETIS_SDID_FAMILYID_SHIFT 28
221 #define KINETIS_SDID_FAMILYID_MASK  0xF0000000
222 #define KINETIS_SDID_FAMILYID_K0X   0x00000000
223 #define KINETIS_SDID_FAMILYID_K1X   0x10000000
224 #define KINETIS_SDID_FAMILYID_K2X   0x20000000
225 #define KINETIS_SDID_FAMILYID_K3X   0x30000000
226 #define KINETIS_SDID_FAMILYID_K4X   0x40000000
227 #define KINETIS_SDID_FAMILYID_K5X   0x50000000
228 #define KINETIS_SDID_FAMILYID_K6X   0x60000000
229 #define KINETIS_SDID_FAMILYID_K7X   0x70000000
230 #define KINETIS_SDID_FAMILYID_K8X   0x80000000
231 #define KINETIS_SDID_FAMILYID_KL8X  0x90000000
232
233 /* The field originally named DIEID has new name/meaning on KE1x */
234 #define KINETIS_SDID_PROJECTID_MASK  KINETIS_SDID_DIEID_MASK
235 #define KINETIS_SDID_PROJECTID_KE1xF 0x00000080
236 #define KINETIS_SDID_PROJECTID_KE1xZ 0x00000100
237
238 struct kinetis_flash_bank {
239         struct kinetis_chip *k_chip;
240         bool probed;
241         unsigned bank_number;           /* bank number in particular chip */
242         struct flash_bank *bank;
243
244         uint32_t sector_size;
245         uint32_t protection_size;
246         uint32_t prog_base;             /* base address for FTFx operations */
247                                         /* usually same as bank->base for pflash, differs for FlexNVM */
248         uint32_t protection_block;      /* number of first protection block in this bank */
249
250         enum {
251                 FC_AUTO = 0,
252                 FC_PFLASH,
253                 FC_FLEX_NVM,
254                 FC_FLEX_RAM,
255         } flash_class;
256 };
257
258 #define KINETIS_MAX_BANKS 4u
259
260 struct kinetis_chip {
261         struct target *target;
262         bool probed;
263
264         uint32_t sim_sdid;
265         uint32_t sim_fcfg1;
266         uint32_t sim_fcfg2;
267         uint32_t fcfg2_maxaddr0_shifted;
268         uint32_t fcfg2_maxaddr1_shifted;
269
270         unsigned num_pflash_blocks, num_nvm_blocks;
271         unsigned pflash_sector_size, nvm_sector_size;
272         unsigned max_flash_prog_size;
273
274         uint32_t pflash_base;
275         uint32_t pflash_size;
276         uint32_t nvm_base;
277         uint32_t nvm_size;              /* whole FlexNVM */
278         uint32_t dflash_size;           /* accessible rest of FlexNVM if EEPROM backup uses part of FlexNVM */
279
280         uint32_t progr_accel_ram;
281         uint32_t sim_base;
282
283         enum {
284                 FS_PROGRAM_SECTOR = 1,
285                 FS_PROGRAM_LONGWORD = 2,
286                 FS_PROGRAM_PHRASE = 4,          /* Unsupported */
287
288                 FS_NO_CMD_BLOCKSTAT = 0x40,
289                 FS_WIDTH_256BIT = 0x80,
290                 FS_ECC = 0x100,
291         } flash_support;
292
293         enum {
294                 KINETIS_CACHE_NONE,
295                 KINETIS_CACHE_K,        /* invalidate using FMC->PFB0CR/PFB01CR */
296                 KINETIS_CACHE_L,        /* invalidate using MCM->PLACR */
297                 KINETIS_CACHE_MSCM,     /* devices like KE1xF, invalidate MSCM->OCMDR0 */
298         } cache_type;
299
300         enum {
301                 KINETIS_WDOG_NONE,
302                 KINETIS_WDOG_K,
303                 KINETIS_WDOG_COP,
304                 KINETIS_WDOG32_KE1X,
305                 KINETIS_WDOG32_KL28,
306         } watchdog_type;
307
308         enum {
309                 KINETIS_SMC,
310                 KINETIS_SMC32,
311         } sysmodectrlr_type;
312
313         char name[40];
314
315         unsigned num_banks;
316         struct kinetis_flash_bank banks[KINETIS_MAX_BANKS];
317 };
318
319 struct kinetis_type {
320         uint32_t sdid;
321         char *name;
322 };
323
324 static const struct kinetis_type kinetis_types_old[] = {
325         { KINETIS_K_SDID_K10_M50,  "MK10D%s5" },
326         { KINETIS_K_SDID_K10_M72,  "MK10D%s7" },
327         { KINETIS_K_SDID_K10_M100, "MK10D%s10" },
328         { KINETIS_K_SDID_K10_M120, "MK10F%s12" },
329         { KINETIS_K_SDID_K11,      "MK11D%s5" },
330         { KINETIS_K_SDID_K12,      "MK12D%s5" },
331
332         { KINETIS_K_SDID_K20_M50,  "MK20D%s5" },
333         { KINETIS_K_SDID_K20_M72,  "MK20D%s7" },
334         { KINETIS_K_SDID_K20_M100, "MK20D%s10" },
335         { KINETIS_K_SDID_K20_M120, "MK20F%s12" },
336         { KINETIS_K_SDID_K21_M50,  "MK21D%s5" },
337         { KINETIS_K_SDID_K21_M120, "MK21F%s12" },
338         { KINETIS_K_SDID_K22_M50,  "MK22D%s5" },
339         { KINETIS_K_SDID_K22_M120, "MK22F%s12" },
340
341         { KINETIS_K_SDID_K30_M72,  "MK30D%s7" },
342         { KINETIS_K_SDID_K30_M100, "MK30D%s10" },
343
344         { KINETIS_K_SDID_K40_M72,  "MK40D%s7" },
345         { KINETIS_K_SDID_K40_M100, "MK40D%s10" },
346
347         { KINETIS_K_SDID_K50_M72,  "MK50D%s7" },
348         { KINETIS_K_SDID_K51_M72,  "MK51D%s7" },
349         { KINETIS_K_SDID_K53,      "MK53D%s10" },
350
351         { KINETIS_K_SDID_K60_M100, "MK60D%s10" },
352         { KINETIS_K_SDID_K60_M150, "MK60F%s15" },
353
354         { KINETIS_K_SDID_K70_M150, "MK70F%s15" },
355 };
356
357
358 #define MDM_AP                  1
359
360 #define MDM_REG_STAT            0x00
361 #define MDM_REG_CTRL            0x04
362 #define MDM_REG_ID              0xfc
363
364 #define MDM_STAT_FMEACK         (1<<0)
365 #define MDM_STAT_FREADY         (1<<1)
366 #define MDM_STAT_SYSSEC         (1<<2)
367 #define MDM_STAT_SYSRES         (1<<3)
368 #define MDM_STAT_FMEEN          (1<<5)
369 #define MDM_STAT_BACKDOOREN     (1<<6)
370 #define MDM_STAT_LPEN           (1<<7)
371 #define MDM_STAT_VLPEN          (1<<8)
372 #define MDM_STAT_LLSMODEXIT     (1<<9)
373 #define MDM_STAT_VLLSXMODEXIT   (1<<10)
374 #define MDM_STAT_CORE_HALTED    (1<<16)
375 #define MDM_STAT_CORE_SLEEPDEEP (1<<17)
376 #define MDM_STAT_CORESLEEPING   (1<<18)
377
378 #define MDM_CTRL_FMEIP          (1<<0)
379 #define MDM_CTRL_DBG_DIS        (1<<1)
380 #define MDM_CTRL_DBG_REQ        (1<<2)
381 #define MDM_CTRL_SYS_RES_REQ    (1<<3)
382 #define MDM_CTRL_CORE_HOLD_RES  (1<<4)
383 #define MDM_CTRL_VLLSX_DBG_REQ  (1<<5)
384 #define MDM_CTRL_VLLSX_DBG_ACK  (1<<6)
385 #define MDM_CTRL_VLLSX_STAT_ACK (1<<7)
386
387 #define MDM_ACCESS_TIMEOUT      500 /* msec */
388
389
390 static bool allow_fcf_writes;
391 static uint8_t fcf_fopt = 0xff;
392 static bool fcf_fopt_configured;
393 static bool create_banks;
394
395
396 const struct flash_driver kinetis_flash;
397 static int kinetis_write_inner(struct flash_bank *bank, const uint8_t *buffer,
398                         uint32_t offset, uint32_t count);
399 static int kinetis_probe_chip(struct kinetis_chip *k_chip);
400 static int kinetis_auto_probe(struct flash_bank *bank);
401
402
403 static int kinetis_mdm_write_register(struct adiv5_dap *dap, unsigned reg, uint32_t value)
404 {
405         int retval;
406         LOG_DEBUG("MDM_REG[0x%02x] <- %08" PRIX32, reg, value);
407
408         retval = dap_queue_ap_write(dap_ap(dap, MDM_AP), reg, value);
409         if (retval != ERROR_OK) {
410                 LOG_DEBUG("MDM: failed to queue a write request");
411                 return retval;
412         }
413
414         retval = dap_run(dap);
415         if (retval != ERROR_OK) {
416                 LOG_DEBUG("MDM: dap_run failed");
417                 return retval;
418         }
419
420
421         return ERROR_OK;
422 }
423
424 static int kinetis_mdm_read_register(struct adiv5_dap *dap, unsigned reg, uint32_t *result)
425 {
426         int retval;
427
428         retval = dap_queue_ap_read(dap_ap(dap, MDM_AP), reg, result);
429         if (retval != ERROR_OK) {
430                 LOG_DEBUG("MDM: failed to queue a read request");
431                 return retval;
432         }
433
434         retval = dap_run(dap);
435         if (retval != ERROR_OK) {
436                 LOG_DEBUG("MDM: dap_run failed");
437                 return retval;
438         }
439
440         LOG_DEBUG("MDM_REG[0x%02x]: %08" PRIX32, reg, *result);
441         return ERROR_OK;
442 }
443
444 static int kinetis_mdm_poll_register(struct adiv5_dap *dap, unsigned reg,
445                         uint32_t mask, uint32_t value, uint32_t timeout_ms)
446 {
447         uint32_t val;
448         int retval;
449         int64_t ms_timeout = timeval_ms() + timeout_ms;
450
451         do {
452                 retval = kinetis_mdm_read_register(dap, reg, &val);
453                 if (retval != ERROR_OK || (val & mask) == value)
454                         return retval;
455
456                 alive_sleep(1);
457         } while (timeval_ms() < ms_timeout);
458
459         LOG_DEBUG("MDM: polling timed out");
460         return ERROR_FAIL;
461 }
462
463 /*
464  * This command can be used to break a watchdog reset loop when
465  * connecting to an unsecured target. Unlike other commands, halt will
466  * automatically retry as it does not know how far into the boot process
467  * it is when the command is called.
468  */
469 COMMAND_HANDLER(kinetis_mdm_halt)
470 {
471         struct target *target = get_current_target(CMD_CTX);
472         struct cortex_m_common *cortex_m = target_to_cm(target);
473         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
474         int retval;
475         int tries = 0;
476         uint32_t stat;
477         int64_t ms_timeout = timeval_ms() + MDM_ACCESS_TIMEOUT;
478
479         if (!dap) {
480                 LOG_ERROR("Cannot perform halt with a high-level adapter");
481                 return ERROR_FAIL;
482         }
483
484         while (true) {
485                 tries++;
486
487                 kinetis_mdm_write_register(dap, MDM_REG_CTRL, MDM_CTRL_CORE_HOLD_RES);
488
489                 alive_sleep(1);
490
491                 retval = kinetis_mdm_read_register(dap, MDM_REG_STAT, &stat);
492                 if (retval != ERROR_OK) {
493                         LOG_DEBUG("MDM: failed to read MDM_REG_STAT");
494                         continue;
495                 }
496
497                 /* Repeat setting MDM_CTRL_CORE_HOLD_RES until system is out of
498                  * reset with flash ready and without security
499                  */
500                 if ((stat & (MDM_STAT_FREADY | MDM_STAT_SYSSEC | MDM_STAT_SYSRES))
501                                 == (MDM_STAT_FREADY | MDM_STAT_SYSRES))
502                         break;
503
504                 if (timeval_ms() >= ms_timeout) {
505                         LOG_ERROR("MDM: halt timed out");
506                         return ERROR_FAIL;
507                 }
508         }
509
510         LOG_DEBUG("MDM: halt succeded after %d attempts.", tries);
511
512         target_poll(target);
513         /* enable polling in case kinetis_check_flash_security_status disabled it */
514         jtag_poll_set_enabled(true);
515
516         alive_sleep(100);
517
518         target->reset_halt = true;
519         target->type->assert_reset(target);
520
521         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
522         if (retval != ERROR_OK) {
523                 LOG_ERROR("MDM: failed to clear MDM_REG_CTRL");
524                 return retval;
525         }
526
527         target->type->deassert_reset(target);
528
529         return ERROR_OK;
530 }
531
532 COMMAND_HANDLER(kinetis_mdm_reset)
533 {
534         struct target *target = get_current_target(CMD_CTX);
535         struct cortex_m_common *cortex_m = target_to_cm(target);
536         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
537         int retval;
538
539         if (!dap) {
540                 LOG_ERROR("Cannot perform reset with a high-level adapter");
541                 return ERROR_FAIL;
542         }
543
544         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, MDM_CTRL_SYS_RES_REQ);
545         if (retval != ERROR_OK) {
546                 LOG_ERROR("MDM: failed to write MDM_REG_CTRL");
547                 return retval;
548         }
549
550         retval = kinetis_mdm_poll_register(dap, MDM_REG_STAT, MDM_STAT_SYSRES, 0, 500);
551         if (retval != ERROR_OK) {
552                 LOG_ERROR("MDM: failed to assert reset");
553                 return retval;
554         }
555
556         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
557         if (retval != ERROR_OK) {
558                 LOG_ERROR("MDM: failed to clear MDM_REG_CTRL");
559                 return retval;
560         }
561
562         return ERROR_OK;
563 }
564
565 /*
566  * This function implements the procedure to mass erase the flash via
567  * SWD/JTAG on Kinetis K and L series of devices as it is described in
568  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
569  * and L-series MCUs" Section 4.2.1. To prevent a watchdog reset loop,
570  * the core remains halted after this function completes as suggested
571  * by the application note.
572  */
573 COMMAND_HANDLER(kinetis_mdm_mass_erase)
574 {
575         struct target *target = get_current_target(CMD_CTX);
576         struct cortex_m_common *cortex_m = target_to_cm(target);
577         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
578
579         if (!dap) {
580                 LOG_ERROR("Cannot perform mass erase with a high-level adapter");
581                 return ERROR_FAIL;
582         }
583
584         int retval;
585
586         /*
587          * ... Power on the processor, or if power has already been
588          * applied, assert the RESET pin to reset the processor. For
589          * devices that do not have a RESET pin, write the System
590          * Reset Request bit in the MDM-AP control register after
591          * establishing communication...
592          */
593
594         /* assert SRST if configured */
595         bool has_srst = jtag_get_reset_config() & RESET_HAS_SRST;
596         if (has_srst)
597                 adapter_assert_reset();
598
599         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, MDM_CTRL_SYS_RES_REQ);
600         if (retval != ERROR_OK && !has_srst) {
601                 LOG_ERROR("MDM: failed to assert reset");
602                 goto deassert_reset_and_exit;
603         }
604
605         /*
606          * ... Read the MDM-AP status register repeatedly and wait for
607          * stable conditions suitable for mass erase:
608          * - mass erase is enabled
609          * - flash is ready
610          * - reset is finished
611          *
612          * Mass erase is started as soon as all conditions are met in 32
613          * subsequent status reads.
614          *
615          * In case of not stable conditions (RESET/WDOG loop in secured device)
616          * the user is asked for manual pressing of RESET button
617          * as a last resort.
618          */
619         int cnt_mass_erase_disabled = 0;
620         int cnt_ready = 0;
621         int64_t ms_start = timeval_ms();
622         bool man_reset_requested = false;
623
624         do {
625                 uint32_t stat = 0;
626                 int64_t ms_elapsed = timeval_ms() - ms_start;
627
628                 if (!man_reset_requested && ms_elapsed > 100) {
629                         LOG_INFO("MDM: Press RESET button now if possible.");
630                         man_reset_requested = true;
631                 }
632
633                 if (ms_elapsed > 3000) {
634                         LOG_ERROR("MDM: waiting for mass erase conditions timed out.");
635                         LOG_INFO("Mass erase of a secured MCU is not possible without hardware reset.");
636                         LOG_INFO("Connect SRST, use 'reset_config srst_only' and retry.");
637                         goto deassert_reset_and_exit;
638                 }
639                 retval = kinetis_mdm_read_register(dap, MDM_REG_STAT, &stat);
640                 if (retval != ERROR_OK) {
641                         cnt_ready = 0;
642                         continue;
643                 }
644
645                 if (!(stat & MDM_STAT_FMEEN)) {
646                         cnt_ready = 0;
647                         cnt_mass_erase_disabled++;
648                         if (cnt_mass_erase_disabled > 10) {
649                                 LOG_ERROR("MDM: mass erase is disabled");
650                                 goto deassert_reset_and_exit;
651                         }
652                         continue;
653                 }
654
655                 if ((stat & (MDM_STAT_FREADY | MDM_STAT_SYSRES)) == MDM_STAT_FREADY)
656                         cnt_ready++;
657                 else
658                         cnt_ready = 0;
659
660         } while (cnt_ready < 32);
661
662         /*
663          * ... Write the MDM-AP control register to set the Flash Mass
664          * Erase in Progress bit. This will start the mass erase
665          * process...
666          */
667         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, MDM_CTRL_SYS_RES_REQ | MDM_CTRL_FMEIP);
668         if (retval != ERROR_OK) {
669                 LOG_ERROR("MDM: failed to start mass erase");
670                 goto deassert_reset_and_exit;
671         }
672
673         /*
674          * ... Read the MDM-AP control register until the Flash Mass
675          * Erase in Progress bit clears...
676          * Data sheed defines erase time <3.6 sec/512kB flash block.
677          * The biggest device has 4 pflash blocks => timeout 16 sec.
678          */
679         retval = kinetis_mdm_poll_register(dap, MDM_REG_CTRL, MDM_CTRL_FMEIP, 0, 16000);
680         if (retval != ERROR_OK) {
681                 LOG_ERROR("MDM: mass erase timeout");
682                 goto deassert_reset_and_exit;
683         }
684
685         target_poll(target);
686         /* enable polling in case kinetis_check_flash_security_status disabled it */
687         jtag_poll_set_enabled(true);
688
689         alive_sleep(100);
690
691         target->reset_halt = true;
692         target->type->assert_reset(target);
693
694         /*
695          * ... Negate the RESET signal or clear the System Reset Request
696          * bit in the MDM-AP control register.
697          */
698         retval = kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
699         if (retval != ERROR_OK)
700                 LOG_ERROR("MDM: failed to clear MDM_REG_CTRL");
701
702         target->type->deassert_reset(target);
703
704         return retval;
705
706 deassert_reset_and_exit:
707         kinetis_mdm_write_register(dap, MDM_REG_CTRL, 0);
708         if (has_srst)
709                 adapter_deassert_reset();
710         return retval;
711 }
712
713 static const uint32_t kinetis_known_mdm_ids[] = {
714         0x001C0000,     /* Kinetis-K Series */
715         0x001C0020,     /* Kinetis-L/M/V/E Series */
716         0x001C0030,     /* Kinetis with a Cortex-M7, in time of writing KV58 */
717 };
718
719 /*
720  * This function implements the procedure to connect to
721  * SWD/JTAG on Kinetis K and L series of devices as it is described in
722  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
723  * and L-series MCUs" Section 4.1.1
724  */
725 COMMAND_HANDLER(kinetis_check_flash_security_status)
726 {
727         struct target *target = get_current_target(CMD_CTX);
728         struct cortex_m_common *cortex_m = target_to_cm(target);
729         struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
730
731         if (!dap) {
732                 LOG_WARNING("Cannot check flash security status with a high-level adapter");
733                 return ERROR_OK;
734         }
735
736         if (!dap->ops)
737                 return ERROR_OK;        /* too early to check, in JTAG mode ops may not be initialised */
738
739         uint32_t val;
740         int retval;
741
742         /*
743          * ... The MDM-AP ID register can be read to verify that the
744          * connection is working correctly...
745          */
746         retval = kinetis_mdm_read_register(dap, MDM_REG_ID, &val);
747         if (retval != ERROR_OK) {
748                 LOG_ERROR("MDM: failed to read ID register");
749                 return ERROR_OK;
750         }
751
752         if (val == 0)
753                 return ERROR_OK;        /* dap not yet initialised */
754
755         bool found = false;
756         for (size_t i = 0; i < ARRAY_SIZE(kinetis_known_mdm_ids); i++) {
757                 if (val == kinetis_known_mdm_ids[i]) {
758                         found = true;
759                         break;
760                 }
761         }
762
763         if (!found)
764                 LOG_WARNING("MDM: unknown ID %08" PRIX32, val);
765
766         /*
767          * ... Read the System Security bit to determine if security is enabled.
768          * If System Security = 0, then proceed. If System Security = 1, then
769          * communication with the internals of the processor, including the
770          * flash, will not be possible without issuing a mass erase command or
771          * unsecuring the part through other means (backdoor key unlock)...
772          */
773         retval = kinetis_mdm_read_register(dap, MDM_REG_STAT, &val);
774         if (retval != ERROR_OK) {
775                 LOG_ERROR("MDM: failed to read MDM_REG_STAT");
776                 return ERROR_OK;
777         }
778
779         /*
780          * System Security bit is also active for short time during reset.
781          * If a MCU has blank flash and runs in RESET/WDOG loop,
782          * System Security bit is active most of time!
783          * We should observe Flash Ready bit and read status several times
784          * to avoid false detection of secured MCU
785          */
786         int secured_score = 0, flash_not_ready_score = 0;
787
788         if ((val & (MDM_STAT_SYSSEC | MDM_STAT_FREADY)) != MDM_STAT_FREADY) {
789                 uint32_t stats[32];
790                 int i;
791
792                 for (i = 0; i < 32; i++) {
793                         stats[i] = MDM_STAT_FREADY;
794                         dap_queue_ap_read(dap_ap(dap, MDM_AP), MDM_REG_STAT, &stats[i]);
795                 }
796                 retval = dap_run(dap);
797                 if (retval != ERROR_OK) {
798                         LOG_DEBUG("MDM: dap_run failed when validating secured state");
799                         return ERROR_OK;
800                 }
801                 for (i = 0; i < 32; i++) {
802                         if (stats[i] & MDM_STAT_SYSSEC)
803                                 secured_score++;
804                         if (!(stats[i] & MDM_STAT_FREADY))
805                                 flash_not_ready_score++;
806                 }
807         }
808
809         if (flash_not_ready_score <= 8 && secured_score > 24) {
810                 jtag_poll_set_enabled(false);
811
812                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
813                 LOG_WARNING("****                                                          ****");
814                 LOG_WARNING("**** Your Kinetis MCU is in secured state, which means that,  ****");
815                 LOG_WARNING("**** with exception for very basic communication, JTAG/SWD    ****");
816                 LOG_WARNING("**** interface will NOT work. In order to restore its         ****");
817                 LOG_WARNING("**** functionality please issue 'kinetis mdm mass_erase'      ****");
818                 LOG_WARNING("**** command, power cycle the MCU and restart OpenOCD.        ****");
819                 LOG_WARNING("****                                                          ****");
820                 LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
821
822         } else if (flash_not_ready_score > 24) {
823                 jtag_poll_set_enabled(false);
824                 LOG_WARNING("**** Your Kinetis MCU is probably locked-up in RESET/WDOG loop. ****");
825                 LOG_WARNING("**** Common reason is a blank flash (at least a reset vector).  ****");
826                 LOG_WARNING("**** Issue 'kinetis mdm halt' command or if SRST is connected   ****");
827                 LOG_WARNING("**** and configured, use 'reset halt'                           ****");
828                 LOG_WARNING("**** If MCU cannot be halted, it is likely secured and running  ****");
829                 LOG_WARNING("**** in RESET/WDOG loop. Issue 'kinetis mdm mass_erase'         ****");
830
831         } else {
832                 LOG_INFO("MDM: Chip is unsecured. Continuing.");
833                 jtag_poll_set_enabled(true);
834         }
835
836         return ERROR_OK;
837 }
838
839
840 static struct kinetis_chip *kinetis_get_chip(struct target *target)
841 {
842         struct flash_bank *bank_iter;
843         struct kinetis_flash_bank *k_bank;
844
845         /* iterate over all kinetis banks */
846         for (bank_iter = flash_bank_list(); bank_iter; bank_iter = bank_iter->next) {
847                 if (bank_iter->driver != &kinetis_flash
848                     || bank_iter->target != target)
849                         continue;
850
851                 k_bank = bank_iter->driver_priv;
852                 if (!k_bank)
853                         continue;
854
855                 if (k_bank->k_chip)
856                         return k_bank->k_chip;
857         }
858         return NULL;
859 }
860
861 static int kinetis_chip_options(struct kinetis_chip *k_chip, int argc, const char *argv[])
862 {
863         int i;
864         for (i = 0; i < argc; i++) {
865                 if (strcmp(argv[i], "-sim-base") == 0) {
866                         if (i + 1 < argc)
867                                 k_chip->sim_base = strtoul(argv[++i], NULL, 0);
868                 } else
869                         LOG_ERROR("Unsupported flash bank option %s", argv[i]);
870         }
871         return ERROR_OK;
872 }
873
874 FLASH_BANK_COMMAND_HANDLER(kinetis_flash_bank_command)
875 {
876         struct target *target = bank->target;
877         struct kinetis_chip *k_chip;
878         struct kinetis_flash_bank *k_bank;
879         int retval;
880
881         if (CMD_ARGC < 6)
882                 return ERROR_COMMAND_SYNTAX_ERROR;
883
884         LOG_INFO("add flash_bank kinetis %s", bank->name);
885
886         k_chip = kinetis_get_chip(target);
887
888         if (k_chip == NULL) {
889                 k_chip = calloc(sizeof(struct kinetis_chip), 1);
890                 if (k_chip == NULL) {
891                         LOG_ERROR("No memory");
892                         return ERROR_FAIL;
893                 }
894
895                 k_chip->target = target;
896
897                 /* only the first defined bank can define chip options */
898                 retval = kinetis_chip_options(k_chip, CMD_ARGC - 6, CMD_ARGV + 6);
899                 if (retval != ERROR_OK)
900                         return retval;
901         }
902
903         if (k_chip->num_banks >= KINETIS_MAX_BANKS) {
904                 LOG_ERROR("Only %u Kinetis flash banks are supported", KINETIS_MAX_BANKS);
905                 return ERROR_FAIL;
906         }
907
908         bank->driver_priv = k_bank = &(k_chip->banks[k_chip->num_banks]);
909         k_bank->k_chip = k_chip;
910         k_bank->bank_number = k_chip->num_banks;
911         k_bank->bank = bank;
912         k_chip->num_banks++;
913
914         return ERROR_OK;
915 }
916
917
918 static void kinetis_free_driver_priv(struct flash_bank *bank)
919 {
920         struct kinetis_flash_bank *k_bank = bank->driver_priv;
921         if (k_bank == NULL)
922                 return;
923
924         struct kinetis_chip *k_chip = k_bank->k_chip;
925         if (k_chip == NULL)
926                 return;
927
928         k_chip->num_banks--;
929         if (k_chip->num_banks == 0)
930                 free(k_chip);
931 }
932
933
934 static int kinetis_create_missing_banks(struct kinetis_chip *k_chip)
935 {
936         unsigned bank_idx;
937         unsigned num_blocks;
938         struct kinetis_flash_bank *k_bank;
939         struct flash_bank *bank;
940         char base_name[69], name[80], num[4];
941         char *class, *p;
942
943         num_blocks = k_chip->num_pflash_blocks + k_chip->num_nvm_blocks;
944         if (num_blocks > KINETIS_MAX_BANKS) {
945                 LOG_ERROR("Only %u Kinetis flash banks are supported", KINETIS_MAX_BANKS);
946                 return ERROR_FAIL;
947         }
948
949         bank = k_chip->banks[0].bank;
950         if (bank && bank->name) {
951                 strncpy(base_name, bank->name, sizeof(base_name) - 1);
952                 base_name[sizeof(base_name) - 1] = '\0';
953                 p = strstr(base_name, ".pflash");
954                 if (p) {
955                         *p = '\0';
956                         if (k_chip->num_pflash_blocks > 1) {
957                                 /* rename first bank if numbering is needed */
958                                 snprintf(name, sizeof(name), "%s.pflash0", base_name);
959                                 free(bank->name);
960                                 bank->name = strdup(name);
961                         }
962                 }
963         } else {
964                 strncpy(base_name, target_name(k_chip->target), sizeof(base_name) - 1);
965                 base_name[sizeof(base_name) - 1] = '\0';
966                 p = strstr(base_name, ".cpu");
967                 if (p)
968                         *p = '\0';
969         }
970
971         for (bank_idx = 1; bank_idx < num_blocks; bank_idx++) {
972                 k_bank = &(k_chip->banks[bank_idx]);
973                 bank = k_bank->bank;
974
975                 if (bank)
976                         continue;
977
978                 num[0] = '\0';
979
980                 if (bank_idx < k_chip->num_pflash_blocks) {
981                         class = "pflash";
982                         if (k_chip->num_pflash_blocks > 1)
983                                 snprintf(num, sizeof(num), "%u", bank_idx);
984                 } else {
985                         class = "flexnvm";
986                         if (k_chip->num_nvm_blocks > 1)
987                                 snprintf(num, sizeof(num), "%u",
988                                          bank_idx - k_chip->num_pflash_blocks);
989                 }
990
991                 bank = calloc(sizeof(struct flash_bank), 1);
992                 if (bank == NULL)
993                         return ERROR_FAIL;
994
995                 bank->target = k_chip->target;
996                 bank->driver = &kinetis_flash;
997                 bank->default_padded_value = bank->erased_value = 0xff;
998
999                 snprintf(name, sizeof(name), "%s.%s%s",
1000                          base_name, class, num);
1001                 bank->name = strdup(name);
1002
1003                 bank->driver_priv = k_bank = &(k_chip->banks[k_chip->num_banks]);
1004                 k_bank->k_chip = k_chip;
1005                 k_bank->bank_number = bank_idx;
1006                 k_bank->bank = bank;
1007                 if (k_chip->num_banks <= bank_idx)
1008                         k_chip->num_banks = bank_idx + 1;
1009
1010                 flash_bank_add(bank);
1011         }
1012         return ERROR_OK;
1013 }
1014
1015
1016 static int kinetis_disable_wdog_algo(struct target *target, size_t code_size, const uint8_t *code, uint32_t wdog_base)
1017 {
1018         struct working_area *wdog_algorithm;
1019         struct armv7m_algorithm armv7m_info;
1020         struct reg_param reg_params[1];
1021         int retval;
1022
1023         if (target->state != TARGET_HALTED) {
1024                 LOG_ERROR("Target not halted");
1025                 return ERROR_TARGET_NOT_HALTED;
1026         }
1027
1028         retval = target_alloc_working_area(target, code_size, &wdog_algorithm);
1029         if (retval != ERROR_OK)
1030                 return retval;
1031
1032         retval = target_write_buffer(target, wdog_algorithm->address,
1033                         code_size, code);
1034         if (retval == ERROR_OK) {
1035                 armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
1036                 armv7m_info.core_mode = ARM_MODE_THREAD;
1037
1038                 init_reg_param(&reg_params[0], "r0", 32, PARAM_OUT);
1039                 buf_set_u32(reg_params[0].value, 0, 32, wdog_base);
1040
1041                 retval = target_run_algorithm(target, 0, NULL, 1, reg_params,
1042                         wdog_algorithm->address,
1043                         wdog_algorithm->address + code_size - 2,
1044                         500, &armv7m_info);
1045
1046                 destroy_reg_param(&reg_params[0]);
1047
1048                 if (retval != ERROR_OK)
1049                         LOG_ERROR("Error executing Kinetis WDOG unlock algorithm");
1050         }
1051
1052         target_free_working_area(target, wdog_algorithm);
1053
1054         return retval;
1055 }
1056
1057 /* Disable the watchdog on Kinetis devices
1058  * Standard Kx WDOG peripheral checks timing and therefore requires to run algo.
1059  */
1060 static int kinetis_disable_wdog_kx(struct target *target)
1061 {
1062         const uint32_t wdog_base = WDOG_BASE;
1063         uint16_t wdog;
1064         int retval;
1065
1066         static const uint8_t kinetis_unlock_wdog_code[] = {
1067 #include "../../../contrib/loaders/watchdog/armv7m_kinetis_wdog.inc"
1068         };
1069
1070         retval = target_read_u16(target, wdog_base + WDOG_STCTRLH_OFFSET, &wdog);
1071         if (retval != ERROR_OK)
1072                 return retval;
1073
1074         if ((wdog & 0x1) == 0) {
1075                 /* watchdog already disabled */
1076                 return ERROR_OK;
1077         }
1078         LOG_INFO("Disabling Kinetis watchdog (initial WDOG_STCTRLH = 0x%04" PRIx16 ")", wdog);
1079
1080         retval = kinetis_disable_wdog_algo(target, sizeof(kinetis_unlock_wdog_code), kinetis_unlock_wdog_code, wdog_base);
1081         if (retval != ERROR_OK)
1082                 return retval;
1083
1084         retval = target_read_u16(target, wdog_base + WDOG_STCTRLH_OFFSET, &wdog);
1085         if (retval != ERROR_OK)
1086                 return retval;
1087
1088         LOG_INFO("WDOG_STCTRLH = 0x%04" PRIx16, wdog);
1089         return (wdog & 0x1) ? ERROR_FAIL : ERROR_OK;
1090 }
1091
1092 static int kinetis_disable_wdog32(struct target *target, uint32_t wdog_base)
1093 {
1094         uint32_t wdog_cs;
1095         int retval;
1096
1097         static const uint8_t kinetis_unlock_wdog_code[] = {
1098 #include "../../../contrib/loaders/watchdog/armv7m_kinetis_wdog32.inc"
1099         };
1100
1101         retval = target_read_u32(target, wdog_base + WDOG32_CS_OFFSET, &wdog_cs);
1102         if (retval != ERROR_OK)
1103                 return retval;
1104
1105         if ((wdog_cs & 0x80) == 0)
1106                 return ERROR_OK; /* watchdog already disabled */
1107
1108         LOG_INFO("Disabling Kinetis watchdog (initial WDOG_CS 0x%08" PRIx32 ")", wdog_cs);
1109
1110         retval = kinetis_disable_wdog_algo(target, sizeof(kinetis_unlock_wdog_code), kinetis_unlock_wdog_code, wdog_base);
1111         if (retval != ERROR_OK)
1112                 return retval;
1113
1114         retval = target_read_u32(target, wdog_base + WDOG32_CS_OFFSET, &wdog_cs);
1115         if (retval != ERROR_OK)
1116                 return retval;
1117
1118         if ((wdog_cs & 0x80) == 0)
1119                 return ERROR_OK; /* watchdog disabled successfully */
1120
1121         LOG_ERROR("Cannot disable Kinetis watchdog (WDOG_CS 0x%08" PRIx32 "), issue 'reset init'", wdog_cs);
1122         return ERROR_FAIL;
1123 }
1124
1125 static int kinetis_disable_wdog(struct kinetis_chip *k_chip)
1126 {
1127         struct target *target = k_chip->target;
1128         uint8_t sim_copc;
1129         int retval;
1130
1131         if (!k_chip->probed) {
1132                 retval = kinetis_probe_chip(k_chip);
1133                 if (retval != ERROR_OK)
1134                         return retval;
1135         }
1136
1137         switch (k_chip->watchdog_type) {
1138         case KINETIS_WDOG_K:
1139                 return kinetis_disable_wdog_kx(target);
1140
1141         case KINETIS_WDOG_COP:
1142                 retval = target_read_u8(target, SIM_COPC, &sim_copc);
1143                 if (retval != ERROR_OK)
1144                         return retval;
1145
1146                 if ((sim_copc & 0xc) == 0)
1147                         return ERROR_OK; /* watchdog already disabled */
1148
1149                 LOG_INFO("Disabling Kinetis watchdog (initial SIM_COPC 0x%02" PRIx8 ")", sim_copc);
1150                 retval = target_write_u8(target, SIM_COPC, sim_copc & ~0xc);
1151                 if (retval != ERROR_OK)
1152                         return retval;
1153
1154                 retval = target_read_u8(target, SIM_COPC, &sim_copc);
1155                 if (retval != ERROR_OK)
1156                         return retval;
1157
1158                 if ((sim_copc & 0xc) == 0)
1159                         return ERROR_OK; /* watchdog disabled successfully */
1160
1161                 LOG_ERROR("Cannot disable Kinetis watchdog (SIM_COPC 0x%02" PRIx8 "), issue 'reset init'", sim_copc);
1162                 return ERROR_FAIL;
1163
1164         case KINETIS_WDOG32_KE1X:
1165                 return kinetis_disable_wdog32(target, WDOG32_KE1X);
1166
1167         case KINETIS_WDOG32_KL28:
1168                 return kinetis_disable_wdog32(target, WDOG32_KL28);
1169
1170         default:
1171                 return ERROR_OK;
1172         }
1173 }
1174
1175 COMMAND_HANDLER(kinetis_disable_wdog_handler)
1176 {
1177         int result;
1178         struct target *target = get_current_target(CMD_CTX);
1179         struct kinetis_chip *k_chip = kinetis_get_chip(target);
1180
1181         if (k_chip == NULL)
1182                 return ERROR_FAIL;
1183
1184         if (CMD_ARGC > 0)
1185                 return ERROR_COMMAND_SYNTAX_ERROR;
1186
1187         result = kinetis_disable_wdog(k_chip);
1188         return result;
1189 }
1190
1191
1192 static int kinetis_ftfx_decode_error(uint8_t fstat)
1193 {
1194         if (fstat & 0x20) {
1195                 LOG_ERROR("Flash operation failed, illegal command");
1196                 return ERROR_FLASH_OPER_UNSUPPORTED;
1197
1198         } else if (fstat & 0x10)
1199                 LOG_ERROR("Flash operation failed, protection violated");
1200
1201         else if (fstat & 0x40)
1202                 LOG_ERROR("Flash operation failed, read collision");
1203
1204         else if (fstat & 0x80)
1205                 return ERROR_OK;
1206
1207         else
1208                 LOG_ERROR("Flash operation timed out");
1209
1210         return ERROR_FLASH_OPERATION_FAILED;
1211 }
1212
1213 static int kinetis_ftfx_clear_error(struct target *target)
1214 {
1215         /* reset error flags */
1216         return target_write_u8(target, FTFx_FSTAT, 0x70);
1217 }
1218
1219
1220 static int kinetis_ftfx_prepare(struct target *target)
1221 {
1222         int result, i;
1223         uint8_t fstat;
1224
1225         /* wait until busy */
1226         for (i = 0; i < 50; i++) {
1227                 result = target_read_u8(target, FTFx_FSTAT, &fstat);
1228                 if (result != ERROR_OK)
1229                         return result;
1230
1231                 if (fstat & 0x80)
1232                         break;
1233         }
1234
1235         if ((fstat & 0x80) == 0) {
1236                 LOG_ERROR("Flash controller is busy");
1237                 return ERROR_FLASH_OPERATION_FAILED;
1238         }
1239         if (fstat != 0x80) {
1240                 /* reset error flags */
1241                 result = kinetis_ftfx_clear_error(target);
1242         }
1243         return result;
1244 }
1245
1246 /* Kinetis Program-LongWord Microcodes */
1247 static const uint8_t kinetis_flash_write_code[] = {
1248 #include "../../../contrib/loaders/flash/kinetis/kinetis_flash.inc"
1249 };
1250
1251 /* Program LongWord Block Write */
1252 static int kinetis_write_block(struct flash_bank *bank, const uint8_t *buffer,
1253                 uint32_t offset, uint32_t wcount)
1254 {
1255         struct target *target = bank->target;
1256         uint32_t buffer_size = 2048;            /* Default minimum value */
1257         struct working_area *write_algorithm;
1258         struct working_area *source;
1259         struct kinetis_flash_bank *k_bank = bank->driver_priv;
1260         uint32_t address = k_bank->prog_base + offset;
1261         uint32_t end_address;
1262         struct reg_param reg_params[5];
1263         struct armv7m_algorithm armv7m_info;
1264         int retval;
1265         uint8_t fstat;
1266
1267         /* Increase buffer_size if needed */
1268         if (buffer_size < (target->working_area_size/2))
1269                 buffer_size = (target->working_area_size/2);
1270
1271         /* allocate working area with flash programming code */
1272         if (target_alloc_working_area(target, sizeof(kinetis_flash_write_code),
1273                         &write_algorithm) != ERROR_OK) {
1274                 LOG_WARNING("no working area available, can't do block memory writes");
1275                 return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1276         }
1277
1278         retval = target_write_buffer(target, write_algorithm->address,
1279                 sizeof(kinetis_flash_write_code), kinetis_flash_write_code);
1280         if (retval != ERROR_OK)
1281                 return retval;
1282
1283         /* memory buffer */
1284         while (target_alloc_working_area(target, buffer_size, &source) != ERROR_OK) {
1285                 buffer_size /= 4;
1286                 if (buffer_size <= 256) {
1287                         /* free working area, write algorithm already allocated */
1288                         target_free_working_area(target, write_algorithm);
1289
1290                         LOG_WARNING("No large enough working area available, can't do block memory writes");
1291                         return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
1292                 }
1293         }
1294
1295         armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
1296         armv7m_info.core_mode = ARM_MODE_THREAD;
1297
1298         init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT); /* address */
1299         init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT); /* word count */
1300         init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
1301         init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
1302         init_reg_param(&reg_params[4], "r4", 32, PARAM_OUT);
1303
1304         buf_set_u32(reg_params[0].value, 0, 32, address);
1305         buf_set_u32(reg_params[1].value, 0, 32, wcount);
1306         buf_set_u32(reg_params[2].value, 0, 32, source->address);
1307         buf_set_u32(reg_params[3].value, 0, 32, source->address + source->size);
1308         buf_set_u32(reg_params[4].value, 0, 32, FTFx_FSTAT);
1309
1310         retval = target_run_flash_async_algorithm(target, buffer, wcount, 4,
1311                                                 0, NULL,
1312                                                 5, reg_params,
1313                                                 source->address, source->size,
1314                                                 write_algorithm->address, 0,
1315                                                 &armv7m_info);
1316
1317         if (retval == ERROR_FLASH_OPERATION_FAILED) {
1318                 end_address = buf_get_u32(reg_params[0].value, 0, 32);
1319
1320                 LOG_ERROR("Error writing flash at %08" PRIx32, end_address);
1321
1322                 retval = target_read_u8(target, FTFx_FSTAT, &fstat);
1323                 if (retval == ERROR_OK) {
1324                         retval = kinetis_ftfx_decode_error(fstat);
1325
1326                         /* reset error flags */
1327                         target_write_u8(target, FTFx_FSTAT, 0x70);
1328                 }
1329         } else if (retval != ERROR_OK)
1330                 LOG_ERROR("Error executing kinetis Flash programming algorithm");
1331
1332         target_free_working_area(target, source);
1333         target_free_working_area(target, write_algorithm);
1334
1335         destroy_reg_param(&reg_params[0]);
1336         destroy_reg_param(&reg_params[1]);
1337         destroy_reg_param(&reg_params[2]);
1338         destroy_reg_param(&reg_params[3]);
1339         destroy_reg_param(&reg_params[4]);
1340
1341         return retval;
1342 }
1343
1344 static int kinetis_protect(struct flash_bank *bank, int set, int first, int last)
1345 {
1346         int i;
1347
1348         if (allow_fcf_writes) {
1349                 LOG_ERROR("Protection setting is possible with 'kinetis fcf_source protection' only!");
1350                 return ERROR_FAIL;
1351         }
1352
1353         if (!bank->prot_blocks || bank->num_prot_blocks == 0) {
1354                 LOG_ERROR("No protection possible for current bank!");
1355                 return ERROR_FLASH_BANK_INVALID;
1356         }
1357
1358         for (i = first; i < bank->num_prot_blocks && i <= last; i++)
1359                 bank->prot_blocks[i].is_protected = set;
1360
1361         LOG_INFO("Protection bits will be written at the next FCF sector erase or write.");
1362         LOG_INFO("Do not issue 'flash info' command until protection is written,");
1363         LOG_INFO("doing so would re-read protection status from MCU.");
1364
1365         return ERROR_OK;
1366 }
1367
1368 static int kinetis_protect_check(struct flash_bank *bank)
1369 {
1370         struct kinetis_flash_bank *k_bank = bank->driver_priv;
1371         int result;
1372         int i, b;
1373         uint32_t fprot;
1374
1375         if (k_bank->flash_class == FC_PFLASH) {
1376
1377                 /* read protection register */
1378                 result = target_read_u32(bank->target, FTFx_FPROT3, &fprot);
1379                 if (result != ERROR_OK)
1380                         return result;
1381
1382                 /* Every bit protects 1/32 of the full flash (not necessarily just this bank) */
1383
1384         } else if (k_bank->flash_class == FC_FLEX_NVM) {
1385                 uint8_t fdprot;
1386
1387                 /* read protection register */
1388                 result = target_read_u8(bank->target, FTFx_FDPROT, &fdprot);
1389                 if (result != ERROR_OK)
1390                         return result;
1391
1392                 fprot = fdprot;
1393
1394         } else {
1395                 LOG_ERROR("Protection checks for FlexRAM not supported");
1396                 return ERROR_FLASH_BANK_INVALID;
1397         }
1398
1399         b = k_bank->protection_block;
1400         for (i = 0; i < bank->num_prot_blocks; i++) {
1401                 if ((fprot >> b) & 1)
1402                         bank->prot_blocks[i].is_protected = 0;
1403                 else
1404                         bank->prot_blocks[i].is_protected = 1;
1405
1406                 b++;
1407         }
1408
1409         return ERROR_OK;
1410 }
1411
1412
1413 static int kinetis_fill_fcf(struct flash_bank *bank, uint8_t *fcf)
1414 {
1415         uint32_t fprot = 0xffffffff;
1416         uint8_t fsec = 0xfe;             /* set MCU unsecure */
1417         uint8_t fdprot = 0xff;
1418         int i;
1419         unsigned bank_idx;
1420         unsigned num_blocks;
1421         uint32_t pflash_bit;
1422         uint8_t dflash_bit;
1423         struct flash_bank *bank_iter;
1424         struct kinetis_flash_bank *k_bank = bank->driver_priv;
1425         struct kinetis_chip *k_chip = k_bank->k_chip;
1426
1427         memset(fcf, 0xff, FCF_SIZE);
1428
1429         pflash_bit = 1;
1430         dflash_bit = 1;
1431
1432         /* iterate over all kinetis banks */
1433         /* current bank is bank 0, it contains FCF */
1434         num_blocks = k_chip->num_pflash_blocks + k_chip->num_nvm_blocks;
1435         for (bank_idx = 0; bank_idx < num_blocks; bank_idx++) {
1436                 k_bank = &(k_chip->banks[bank_idx]);
1437                 bank_iter = k_bank->bank;
1438
1439                 if (bank_iter == NULL) {
1440                         LOG_WARNING("Missing bank %u configuration, FCF protection flags may be incomplette", bank_idx);
1441                         continue;
1442                 }
1443
1444                 kinetis_auto_probe(bank_iter);
1445
1446                 assert(bank_iter->prot_blocks);
1447
1448                 if (k_bank->flash_class == FC_PFLASH) {
1449                         for (i = 0; i < bank_iter->num_prot_blocks; i++) {
1450                                 if (bank_iter->prot_blocks[i].is_protected == 1)
1451                                         fprot &= ~pflash_bit;
1452
1453                                 pflash_bit <<= 1;
1454                         }
1455
1456                 } else if (k_bank->flash_class == FC_FLEX_NVM) {
1457                         for (i = 0; i < bank_iter->num_prot_blocks; i++) {
1458                                 if (bank_iter->prot_blocks[i].is_protected == 1)
1459                                         fdprot &= ~dflash_bit;
1460
1461                                 dflash_bit <<= 1;
1462                         }
1463
1464                 }
1465         }
1466
1467         target_buffer_set_u32(bank->target, fcf + FCF_FPROT, fprot);
1468         fcf[FCF_FSEC] = fsec;
1469         fcf[FCF_FOPT] = fcf_fopt;
1470         fcf[FCF_FDPROT] = fdprot;
1471         return ERROR_OK;
1472 }
1473
1474 static int kinetis_ftfx_command(struct target *target, uint8_t fcmd, uint32_t faddr,
1475                                 uint8_t fccob4, uint8_t fccob5, uint8_t fccob6, uint8_t fccob7,
1476                                 uint8_t fccob8, uint8_t fccob9, uint8_t fccoba, uint8_t fccobb,
1477                                 uint8_t *ftfx_fstat)
1478 {
1479         uint8_t command[12] = {faddr & 0xff, (faddr >> 8) & 0xff, (faddr >> 16) & 0xff, fcmd,
1480                         fccob7, fccob6, fccob5, fccob4,
1481                         fccobb, fccoba, fccob9, fccob8};
1482         int result;
1483         uint8_t fstat;
1484         int64_t ms_timeout = timeval_ms() + 250;
1485
1486         result = target_write_memory(target, FTFx_FCCOB3, 4, 3, command);
1487         if (result != ERROR_OK)
1488                 return result;
1489
1490         /* start command */
1491         result = target_write_u8(target, FTFx_FSTAT, 0x80);
1492         if (result != ERROR_OK)
1493                 return result;
1494
1495         /* wait for done */
1496         do {
1497                 result = target_read_u8(target, FTFx_FSTAT, &fstat);
1498
1499                 if (result != ERROR_OK)
1500                         return result;
1501
1502                 if (fstat & 0x80)
1503                         break;
1504
1505         } while (timeval_ms() < ms_timeout);
1506
1507         if (ftfx_fstat)
1508                 *ftfx_fstat = fstat;
1509
1510         if ((fstat & 0xf0) != 0x80) {
1511                 LOG_DEBUG("ftfx command failed FSTAT: %02X FCCOB: %02X%02X%02X%02X %02X%02X%02X%02X %02X%02X%02X%02X",
1512                          fstat, command[3], command[2], command[1], command[0],
1513                          command[7], command[6], command[5], command[4],
1514                          command[11], command[10], command[9], command[8]);
1515
1516                 return kinetis_ftfx_decode_error(fstat);
1517         }
1518
1519         return ERROR_OK;
1520 }
1521
1522
1523 static int kinetis_read_pmstat(struct kinetis_chip *k_chip, uint8_t *pmstat)
1524 {
1525         int result;
1526         uint32_t stat32;
1527         struct target *target = k_chip->target;
1528
1529         switch (k_chip->sysmodectrlr_type) {
1530         case KINETIS_SMC:
1531                 result = target_read_u8(target, SMC_PMSTAT, pmstat);
1532                 return result;
1533
1534         case KINETIS_SMC32:
1535                 result = target_read_u32(target, SMC32_PMSTAT, &stat32);
1536                 if (result == ERROR_OK)
1537                         *pmstat = stat32 & 0xff;
1538                 return result;
1539         }
1540         return ERROR_FAIL;
1541 }
1542
1543 static int kinetis_check_run_mode(struct kinetis_chip *k_chip)
1544 {
1545         int result, i;
1546         uint8_t pmstat;
1547         struct target *target;
1548
1549         if (k_chip == NULL) {
1550                 LOG_ERROR("Chip not probed.");
1551                 return ERROR_FAIL;
1552         }
1553         target = k_chip->target;
1554
1555         if (target->state != TARGET_HALTED) {
1556                 LOG_ERROR("Target not halted");
1557                 return ERROR_TARGET_NOT_HALTED;
1558         }
1559
1560         result = kinetis_read_pmstat(k_chip, &pmstat);
1561         if (result != ERROR_OK)
1562                 return result;
1563
1564         if (pmstat == PM_STAT_RUN)
1565                 return ERROR_OK;
1566
1567         if (pmstat == PM_STAT_VLPR) {
1568                 /* It is safe to switch from VLPR to RUN mode without changing clock */
1569                 LOG_INFO("Switching from VLPR to RUN mode.");
1570
1571                 switch (k_chip->sysmodectrlr_type) {
1572                 case KINETIS_SMC:
1573                         result = target_write_u8(target, SMC_PMCTRL, PM_CTRL_RUNM_RUN);
1574                         break;
1575
1576                 case KINETIS_SMC32:
1577                         result = target_write_u32(target, SMC32_PMCTRL, PM_CTRL_RUNM_RUN);
1578                         break;
1579                 }
1580                 if (result != ERROR_OK)
1581                         return result;
1582
1583                 for (i = 100; i; i--) {
1584                         result = kinetis_read_pmstat(k_chip, &pmstat);
1585                         if (result != ERROR_OK)
1586                                 return result;
1587
1588                         if (pmstat == PM_STAT_RUN)
1589                                 return ERROR_OK;
1590                 }
1591         }
1592
1593         LOG_ERROR("Flash operation not possible in current run mode: SMC_PMSTAT: 0x%x", pmstat);
1594         LOG_ERROR("Issue a 'reset init' command.");
1595         return ERROR_TARGET_NOT_HALTED;
1596 }
1597
1598
1599 static void kinetis_invalidate_flash_cache(struct kinetis_chip *k_chip)
1600 {
1601         struct target *target = k_chip->target;
1602
1603         switch (k_chip->cache_type) {
1604         case KINETIS_CACHE_K:
1605                 target_write_u8(target, FMC_PFB01CR + 2, 0xf0);
1606                 /* Set CINV_WAY bits - request invalidate of all cache ways */
1607                 /* FMC_PFB0CR has same address and CINV_WAY bits as FMC_PFB01CR */
1608                 break;
1609
1610         case KINETIS_CACHE_L:
1611                 target_write_u8(target, MCM_PLACR + 1, 0x04);
1612                 /* set bit CFCC - Clear Flash Controller Cache */
1613                 break;
1614
1615         case KINETIS_CACHE_MSCM:
1616                 target_write_u32(target, MSCM_OCMDR0, 0x30);
1617                 /* disable data prefetch and flash speculate */
1618                 break;
1619
1620         default:
1621                 break;
1622         }
1623 }
1624
1625
1626 static int kinetis_erase(struct flash_bank *bank, int first, int last)
1627 {
1628         int result, i;
1629         struct kinetis_flash_bank *k_bank = bank->driver_priv;
1630         struct kinetis_chip *k_chip = k_bank->k_chip;
1631
1632         result = kinetis_check_run_mode(k_chip);
1633         if (result != ERROR_OK)
1634                 return result;
1635
1636         /* reset error flags */
1637         result = kinetis_ftfx_prepare(bank->target);
1638         if (result != ERROR_OK)
1639                 return result;
1640
1641         if ((first > bank->num_sectors) || (last > bank->num_sectors))
1642                 return ERROR_FLASH_OPERATION_FAILED;
1643
1644         /*
1645          * FIXME: TODO: use the 'Erase Flash Block' command if the
1646          * requested erase is PFlash or NVM and encompasses the entire
1647          * block.  Should be quicker.
1648          */
1649         for (i = first; i <= last; i++) {
1650                 /* set command and sector address */
1651                 result = kinetis_ftfx_command(bank->target, FTFx_CMD_SECTERASE, k_bank->prog_base + bank->sectors[i].offset,
1652                                 0, 0, 0, 0,  0, 0, 0, 0,  NULL);
1653
1654                 if (result != ERROR_OK) {
1655                         LOG_WARNING("erase sector %d failed", i);
1656                         return ERROR_FLASH_OPERATION_FAILED;
1657                 }
1658
1659                 bank->sectors[i].is_erased = 1;
1660
1661                 if (k_bank->prog_base == 0
1662                         && bank->sectors[i].offset <= FCF_ADDRESS
1663                         && bank->sectors[i].offset + bank->sectors[i].size > FCF_ADDRESS + FCF_SIZE) {
1664                         if (allow_fcf_writes) {
1665                                 LOG_WARNING("Flash Configuration Field erased, DO NOT reset or power off the device");
1666                                 LOG_WARNING("until correct FCF is programmed or MCU gets security lock.");
1667                         } else {
1668                                 uint8_t fcf_buffer[FCF_SIZE];
1669
1670                                 kinetis_fill_fcf(bank, fcf_buffer);
1671                                 result = kinetis_write_inner(bank, fcf_buffer, FCF_ADDRESS, FCF_SIZE);
1672                                 if (result != ERROR_OK)
1673                                         LOG_WARNING("Flash Configuration Field write failed");
1674                                 bank->sectors[i].is_erased = 0;
1675                         }
1676                 }
1677         }
1678
1679         kinetis_invalidate_flash_cache(k_bank->k_chip);
1680
1681         return ERROR_OK;
1682 }
1683
1684 static int kinetis_make_ram_ready(struct target *target)
1685 {
1686         int result;
1687         uint8_t ftfx_fcnfg;
1688
1689         /* check if ram ready */
1690         result = target_read_u8(target, FTFx_FCNFG, &ftfx_fcnfg);
1691         if (result != ERROR_OK)
1692                 return result;
1693
1694         if (ftfx_fcnfg & (1 << 1))
1695                 return ERROR_OK;        /* ram ready */
1696
1697         /* make flex ram available */
1698         result = kinetis_ftfx_command(target, FTFx_CMD_SETFLEXRAM, 0x00ff0000,
1699                                  0, 0, 0, 0,  0, 0, 0, 0,  NULL);
1700         if (result != ERROR_OK)
1701                 return ERROR_FLASH_OPERATION_FAILED;
1702
1703         /* check again */
1704         result = target_read_u8(target, FTFx_FCNFG, &ftfx_fcnfg);
1705         if (result != ERROR_OK)
1706                 return result;
1707
1708         if (ftfx_fcnfg & (1 << 1))
1709                 return ERROR_OK;        /* ram ready */
1710
1711         return ERROR_FLASH_OPERATION_FAILED;
1712 }
1713
1714
1715 static int kinetis_write_sections(struct flash_bank *bank, const uint8_t *buffer,
1716                          uint32_t offset, uint32_t count)
1717 {
1718         int result = ERROR_OK;
1719         struct kinetis_flash_bank *k_bank = bank->driver_priv;
1720         struct kinetis_chip *k_chip = k_bank->k_chip;
1721         uint8_t *buffer_aligned = NULL;
1722         /*
1723          * Kinetis uses different terms for the granularity of
1724          * sector writes, e.g. "phrase" or "128 bits".  We use
1725          * the generic term "chunk". The largest possible
1726          * Kinetis "chunk" is 16 bytes (128 bits).
1727          */
1728         uint32_t prog_section_chunk_bytes = k_bank->sector_size >> 8;
1729         uint32_t prog_size_bytes = k_chip->max_flash_prog_size;
1730
1731         while (count > 0) {
1732                 uint32_t size = prog_size_bytes - offset % prog_size_bytes;
1733                 uint32_t align_begin = offset % prog_section_chunk_bytes;
1734                 uint32_t align_end;
1735                 uint32_t size_aligned;
1736                 uint16_t chunk_count;
1737                 uint8_t ftfx_fstat;
1738
1739                 if (size > count)
1740                         size = count;
1741
1742                 align_end = (align_begin + size) % prog_section_chunk_bytes;
1743                 if (align_end)
1744                         align_end = prog_section_chunk_bytes - align_end;
1745
1746                 size_aligned = align_begin + size + align_end;
1747                 chunk_count = size_aligned / prog_section_chunk_bytes;
1748
1749                 if (size != size_aligned) {
1750                         /* aligned section: the first, the last or the only */
1751                         if (!buffer_aligned)
1752                                 buffer_aligned = malloc(prog_size_bytes);
1753
1754                         memset(buffer_aligned, 0xff, size_aligned);
1755                         memcpy(buffer_aligned + align_begin, buffer, size);
1756
1757                         result = target_write_memory(bank->target, k_chip->progr_accel_ram,
1758                                                 4, size_aligned / 4, buffer_aligned);
1759
1760                         LOG_DEBUG("section @ " TARGET_ADDR_FMT " aligned begin %" PRIu32
1761                                         ", end %" PRIu32,
1762                                         bank->base + offset, align_begin, align_end);
1763                 } else
1764                         result = target_write_memory(bank->target, k_chip->progr_accel_ram,
1765                                                 4, size_aligned / 4, buffer);
1766
1767                 LOG_DEBUG("write section @ " TARGET_ADDR_FMT " with length %" PRIu32
1768                                 " bytes",
1769                           bank->base + offset, size);
1770
1771                 if (result != ERROR_OK) {
1772                         LOG_ERROR("target_write_memory failed");
1773                         break;
1774                 }
1775
1776                 /* execute section-write command */
1777                 result = kinetis_ftfx_command(bank->target, FTFx_CMD_SECTWRITE,
1778                                 k_bank->prog_base + offset - align_begin,
1779                                 chunk_count>>8, chunk_count, 0, 0,
1780                                 0, 0, 0, 0,  &ftfx_fstat);
1781
1782                 if (result != ERROR_OK) {
1783                         LOG_ERROR("Error writing section at " TARGET_ADDR_FMT,
1784                                         bank->base + offset);
1785                         break;
1786                 }
1787
1788                 if (ftfx_fstat & 0x01) {
1789                         LOG_ERROR("Flash write error at " TARGET_ADDR_FMT,
1790                                         bank->base + offset);
1791                         if (k_bank->prog_base == 0 && offset == FCF_ADDRESS + FCF_SIZE
1792                                         && (k_chip->flash_support & FS_WIDTH_256BIT)) {
1793                                 LOG_ERROR("Flash write immediately after the end of Flash Config Field shows error");
1794                                 LOG_ERROR("because the flash memory is 256 bits wide (data were written correctly).");
1795                                 LOG_ERROR("Either change the linker script to add a gap of 16 bytes after FCF");
1796                                 LOG_ERROR("or set 'kinetis fcf_source write'");
1797                         }
1798                 }
1799
1800                 buffer += size;
1801                 offset += size;
1802                 count -= size;
1803         }
1804
1805         free(buffer_aligned);
1806         return result;
1807 }
1808
1809
1810 static int kinetis_write_inner(struct flash_bank *bank, const uint8_t *buffer,
1811                          uint32_t offset, uint32_t count)
1812 {
1813         int result, fallback = 0;
1814         struct kinetis_flash_bank *k_bank = bank->driver_priv;
1815         struct kinetis_chip *k_chip = k_bank->k_chip;
1816
1817         if (!(k_chip->flash_support & FS_PROGRAM_SECTOR)) {
1818                 /* fallback to longword write */
1819                 fallback = 1;
1820                 LOG_INFO("This device supports Program Longword execution only.");
1821         } else {
1822                 result = kinetis_make_ram_ready(bank->target);
1823                 if (result != ERROR_OK) {
1824                         fallback = 1;
1825                         LOG_WARNING("FlexRAM not ready, fallback to slow longword write.");
1826                 }
1827         }
1828
1829         LOG_DEBUG("flash write @ " TARGET_ADDR_FMT, bank->base + offset);
1830
1831         if (fallback == 0) {
1832                 /* program section command */
1833                 kinetis_write_sections(bank, buffer, offset, count);
1834         } else if (k_chip->flash_support & FS_PROGRAM_LONGWORD) {
1835                 /* program longword command, not supported in FTFE */
1836                 uint8_t *new_buffer = NULL;
1837
1838                 /* check word alignment */
1839                 if (offset & 0x3) {
1840                         LOG_ERROR("offset 0x%" PRIx32 " breaks the required alignment", offset);
1841                         return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
1842                 }
1843
1844                 if (count & 0x3) {
1845                         uint32_t old_count = count;
1846                         count = (old_count | 3) + 1;
1847                         new_buffer = malloc(count);
1848                         if (new_buffer == NULL) {
1849                                 LOG_ERROR("odd number of bytes to write and no memory "
1850                                         "for padding buffer");
1851                                 return ERROR_FAIL;
1852                         }
1853                         LOG_INFO("odd number of bytes to write (%" PRIu32 "), extending to %" PRIu32 " "
1854                                 "and padding with 0xff", old_count, count);
1855                         memset(new_buffer + old_count, 0xff, count - old_count);
1856                         buffer = memcpy(new_buffer, buffer, old_count);
1857                 }
1858
1859                 uint32_t words_remaining = count / 4;
1860
1861                 kinetis_disable_wdog(k_chip);
1862
1863                 /* try using a block write */
1864                 result = kinetis_write_block(bank, buffer, offset, words_remaining);
1865
1866                 if (result == ERROR_TARGET_RESOURCE_NOT_AVAILABLE) {
1867                         /* if block write failed (no sufficient working area),
1868                          * we use normal (slow) single word accesses */
1869                         LOG_WARNING("couldn't use block writes, falling back to single "
1870                                 "memory accesses");
1871
1872                         while (words_remaining) {
1873                                 uint8_t ftfx_fstat;
1874
1875                                 LOG_DEBUG("write longword @ %08" PRIx32, (uint32_t)(bank->base + offset));
1876
1877                                 result = kinetis_ftfx_command(bank->target, FTFx_CMD_LWORDPROG, k_bank->prog_base + offset,
1878                                                 buffer[3], buffer[2], buffer[1], buffer[0],
1879                                                 0, 0, 0, 0,  &ftfx_fstat);
1880
1881                                 if (result != ERROR_OK) {
1882                                         LOG_ERROR("Error writing longword at " TARGET_ADDR_FMT,
1883                                                         bank->base + offset);
1884                                         break;
1885                                 }
1886
1887                                 if (ftfx_fstat & 0x01)
1888                                         LOG_ERROR("Flash write error at " TARGET_ADDR_FMT,
1889                                                         bank->base + offset);
1890
1891                                 buffer += 4;
1892                                 offset += 4;
1893                                 words_remaining--;
1894                         }
1895                 }
1896                 free(new_buffer);
1897         } else {
1898                 LOG_ERROR("Flash write strategy not implemented");
1899                 return ERROR_FLASH_OPERATION_FAILED;
1900         }
1901
1902         kinetis_invalidate_flash_cache(k_chip);
1903         return result;
1904 }
1905
1906
1907 static int kinetis_write(struct flash_bank *bank, const uint8_t *buffer,
1908                          uint32_t offset, uint32_t count)
1909 {
1910         int result;
1911         bool set_fcf = false;
1912         bool fcf_in_data_valid = false;
1913         int sect = 0;
1914         struct kinetis_flash_bank *k_bank = bank->driver_priv;
1915         struct kinetis_chip *k_chip = k_bank->k_chip;
1916         uint8_t fcf_buffer[FCF_SIZE];
1917         uint8_t fcf_current[FCF_SIZE];
1918         uint8_t fcf_in_data[FCF_SIZE];
1919
1920         result = kinetis_check_run_mode(k_chip);
1921         if (result != ERROR_OK)
1922                 return result;
1923
1924         /* reset error flags */
1925         result = kinetis_ftfx_prepare(bank->target);
1926         if (result != ERROR_OK)
1927                 return result;
1928
1929         if (k_bank->prog_base == 0 && !allow_fcf_writes) {
1930                 if (bank->sectors[1].offset <= FCF_ADDRESS)
1931                         sect = 1;       /* 1kb sector, FCF in 2nd sector */
1932
1933                 if (offset < bank->sectors[sect].offset + bank->sectors[sect].size
1934                         && offset + count > bank->sectors[sect].offset)
1935                         set_fcf = true; /* write to any part of sector with FCF */
1936         }
1937
1938         if (set_fcf) {
1939                 kinetis_fill_fcf(bank, fcf_buffer);
1940
1941                 fcf_in_data_valid = offset <= FCF_ADDRESS
1942                                          && offset + count >= FCF_ADDRESS + FCF_SIZE;
1943                 if (fcf_in_data_valid) {
1944                         memcpy(fcf_in_data, buffer + FCF_ADDRESS - offset, FCF_SIZE);
1945                         if (memcmp(fcf_in_data + FCF_FPROT, fcf_buffer, 4)) {
1946                                 fcf_in_data_valid = false;
1947                                 LOG_INFO("Flash protection requested in programmed file differs from current setting.");
1948                         }
1949                         if (fcf_in_data[FCF_FDPROT] != fcf_buffer[FCF_FDPROT]) {
1950                                 fcf_in_data_valid = false;
1951                                 LOG_INFO("Data flash protection requested in programmed file differs from current setting.");
1952                         }
1953                         if ((fcf_in_data[FCF_FSEC] & 3) != 2) {
1954                                 fcf_in_data_valid = false;
1955                                 LOG_INFO("Device security requested in programmed file!");
1956                         } else if (k_chip->flash_support & FS_ECC
1957                             && fcf_in_data[FCF_FSEC] != fcf_buffer[FCF_FSEC]) {
1958                                 fcf_in_data_valid = false;
1959                                 LOG_INFO("Strange unsecure mode 0x%02" PRIx8
1960                                          "requested in programmed file!",
1961                                          fcf_in_data[FCF_FSEC]);
1962                         }
1963                         if ((k_chip->flash_support & FS_ECC || fcf_fopt_configured)
1964                             && fcf_in_data[FCF_FOPT] != fcf_fopt) {
1965                                 fcf_in_data_valid = false;
1966                                 LOG_INFO("FOPT requested in programmed file differs from current setting.");
1967                         }
1968                         if (!fcf_in_data_valid)
1969                                 LOG_INFO("Expect verify errors at FCF (0x408-0x40f).");
1970                 }
1971         }
1972
1973         if (set_fcf && !fcf_in_data_valid) {
1974                 if (offset < FCF_ADDRESS) {
1975                         /* write part preceding FCF */
1976                         result = kinetis_write_inner(bank, buffer, offset, FCF_ADDRESS - offset);
1977                         if (result != ERROR_OK)
1978                                 return result;
1979                 }
1980
1981                 result = target_read_memory(bank->target, bank->base + FCF_ADDRESS, 4, FCF_SIZE / 4, fcf_current);
1982                 if (result == ERROR_OK && memcmp(fcf_current, fcf_buffer, FCF_SIZE) == 0)
1983                         set_fcf = false;
1984
1985                 if (set_fcf) {
1986                         /* write FCF if differs from flash - eliminate multiple writes */
1987                         result = kinetis_write_inner(bank, fcf_buffer, FCF_ADDRESS, FCF_SIZE);
1988                         if (result != ERROR_OK)
1989                                 return result;
1990                 }
1991
1992                 LOG_WARNING("Flash Configuration Field written.");
1993                 LOG_WARNING("Reset or power off the device to make settings effective.");
1994
1995                 if (offset + count > FCF_ADDRESS + FCF_SIZE) {
1996                         uint32_t delta = FCF_ADDRESS + FCF_SIZE - offset;
1997                         /* write part after FCF */
1998                         result = kinetis_write_inner(bank, buffer + delta, FCF_ADDRESS + FCF_SIZE, count - delta);
1999                 }
2000                 return result;
2001
2002         } else {
2003                 /* no FCF fiddling, normal write */
2004                 return kinetis_write_inner(bank, buffer, offset, count);
2005         }
2006 }
2007
2008
2009 static int kinetis_probe_chip(struct kinetis_chip *k_chip)
2010 {
2011         int result;
2012         uint8_t fcfg1_nvmsize, fcfg1_pfsize, fcfg1_eesize, fcfg1_depart;
2013         uint8_t fcfg2_pflsh;
2014         uint32_t ee_size = 0;
2015         uint32_t pflash_size_k, nvm_size_k, dflash_size_k;
2016         uint32_t pflash_size_m;
2017         unsigned num_blocks = 0;
2018         unsigned maxaddr_shift = 13;
2019         struct target *target = k_chip->target;
2020
2021         unsigned familyid = 0, subfamid = 0;
2022         unsigned cpu_mhz = 120;
2023         unsigned idx;
2024         bool use_nvm_marking = false;
2025         char flash_marking[12], nvm_marking[2];
2026         char name[40];
2027
2028         k_chip->probed = false;
2029         k_chip->pflash_sector_size = 0;
2030         k_chip->pflash_base = 0;
2031         k_chip->nvm_base = 0x10000000;
2032         k_chip->progr_accel_ram = FLEXRAM;
2033
2034         name[0] = '\0';
2035
2036         if (k_chip->sim_base)
2037                 result = target_read_u32(target, k_chip->sim_base + SIM_SDID_OFFSET, &k_chip->sim_sdid);
2038         else {
2039                 result = target_read_u32(target, SIM_BASE + SIM_SDID_OFFSET, &k_chip->sim_sdid);
2040                 if (result == ERROR_OK)
2041                         k_chip->sim_base = SIM_BASE;
2042                 else {
2043                         result = target_read_u32(target, SIM_BASE_KL28 + SIM_SDID_OFFSET, &k_chip->sim_sdid);
2044                         if (result == ERROR_OK)
2045                                 k_chip->sim_base = SIM_BASE_KL28;
2046                 }
2047         }
2048         if (result != ERROR_OK)
2049                 return result;
2050
2051         if ((k_chip->sim_sdid & (~KINETIS_SDID_K_SERIES_MASK)) == 0) {
2052                 /* older K-series MCU */
2053                 uint32_t mcu_type = k_chip->sim_sdid & KINETIS_K_SDID_TYPE_MASK;
2054                 k_chip->cache_type = KINETIS_CACHE_K;
2055                 k_chip->watchdog_type = KINETIS_WDOG_K;
2056
2057                 switch (mcu_type) {
2058                 case KINETIS_K_SDID_K10_M50:
2059                 case KINETIS_K_SDID_K20_M50:
2060                         /* 1kB sectors */
2061                         k_chip->pflash_sector_size = 1<<10;
2062                         k_chip->nvm_sector_size = 1<<10;
2063                         num_blocks = 2;
2064                         k_chip->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR;
2065                         break;
2066                 case KINETIS_K_SDID_K10_M72:
2067                 case KINETIS_K_SDID_K20_M72:
2068                 case KINETIS_K_SDID_K30_M72:
2069                 case KINETIS_K_SDID_K30_M100:
2070                 case KINETIS_K_SDID_K40_M72:
2071                 case KINETIS_K_SDID_K40_M100:
2072                 case KINETIS_K_SDID_K50_M72:
2073                         /* 2kB sectors, 1kB FlexNVM sectors */
2074                         k_chip->pflash_sector_size = 2<<10;
2075                         k_chip->nvm_sector_size = 1<<10;
2076                         num_blocks = 2;
2077                         k_chip->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR;
2078                         k_chip->max_flash_prog_size = 1<<10;
2079                         break;
2080                 case KINETIS_K_SDID_K10_M100:
2081                 case KINETIS_K_SDID_K20_M100:
2082                 case KINETIS_K_SDID_K11:
2083                 case KINETIS_K_SDID_K12:
2084                 case KINETIS_K_SDID_K21_M50:
2085                 case KINETIS_K_SDID_K22_M50:
2086                 case KINETIS_K_SDID_K51_M72:
2087                 case KINETIS_K_SDID_K53:
2088                 case KINETIS_K_SDID_K60_M100:
2089                         /* 2kB sectors */
2090                         k_chip->pflash_sector_size = 2<<10;
2091                         k_chip->nvm_sector_size = 2<<10;
2092                         num_blocks = 2;
2093                         k_chip->flash_support = FS_PROGRAM_LONGWORD | FS_PROGRAM_SECTOR;
2094                         break;
2095                 case KINETIS_K_SDID_K21_M120:
2096                 case KINETIS_K_SDID_K22_M120:
2097                         /* 4kB sectors (MK21FN1M0, MK21FX512, MK22FN1M0, MK22FX512) */
2098                         k_chip->pflash_sector_size = 4<<10;
2099                         k_chip->max_flash_prog_size = 1<<10;
2100                         k_chip->nvm_sector_size = 4<<10;
2101                         num_blocks = 2;
2102                         k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
2103                         break;
2104                 case KINETIS_K_SDID_K10_M120:
2105                 case KINETIS_K_SDID_K20_M120:
2106                 case KINETIS_K_SDID_K60_M150:
2107                 case KINETIS_K_SDID_K70_M150:
2108                         /* 4kB sectors */
2109                         k_chip->pflash_sector_size = 4<<10;
2110                         k_chip->nvm_sector_size = 4<<10;
2111                         num_blocks = 4;
2112                         k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
2113                         break;
2114                 default:
2115                         LOG_ERROR("Unsupported K-family FAMID");
2116                 }
2117
2118                 for (idx = 0; idx < ARRAY_SIZE(kinetis_types_old); idx++) {
2119                         if (kinetis_types_old[idx].sdid == mcu_type) {
2120                                 strcpy(name, kinetis_types_old[idx].name);
2121                                 use_nvm_marking = true;
2122                                 break;
2123                         }
2124                 }
2125
2126         } else {
2127                 /* Newer K-series or KL series MCU */
2128                 familyid = (k_chip->sim_sdid & KINETIS_SDID_FAMILYID_MASK) >> KINETIS_SDID_FAMILYID_SHIFT;
2129                 subfamid = (k_chip->sim_sdid & KINETIS_SDID_SUBFAMID_MASK) >> KINETIS_SDID_SUBFAMID_SHIFT;
2130
2131                 switch (k_chip->sim_sdid & KINETIS_SDID_SERIESID_MASK) {
2132                 case KINETIS_SDID_SERIESID_K:
2133                         use_nvm_marking = true;
2134                         k_chip->cache_type = KINETIS_CACHE_K;
2135                         k_chip->watchdog_type = KINETIS_WDOG_K;
2136
2137                         switch (k_chip->sim_sdid & (KINETIS_SDID_FAMILYID_MASK | KINETIS_SDID_SUBFAMID_MASK)) {
2138                         case KINETIS_SDID_FAMILYID_K0X | KINETIS_SDID_SUBFAMID_KX2:
2139                                 /* K02FN64, K02FN128: FTFA, 2kB sectors */
2140                                 k_chip->pflash_sector_size = 2<<10;
2141                                 num_blocks = 1;
2142                                 k_chip->flash_support = FS_PROGRAM_LONGWORD;
2143                                 cpu_mhz = 100;
2144                                 break;
2145
2146                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX2: {
2147                                 /* MK24FN1M reports as K22, this should detect it (according to errata note 1N83J) */
2148                                 uint32_t sopt1;
2149                                 result = target_read_u32(target, k_chip->sim_base + SIM_SOPT1_OFFSET, &sopt1);
2150                                 if (result != ERROR_OK)
2151                                         return result;
2152
2153                                 if (((k_chip->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K24FN1M) &&
2154                                                 ((sopt1 & KINETIS_SOPT1_RAMSIZE_MASK) == KINETIS_SOPT1_RAMSIZE_K24FN1M)) {
2155                                         /* MK24FN1M */
2156                                         k_chip->pflash_sector_size = 4<<10;
2157                                         num_blocks = 2;
2158                                         k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
2159                                         k_chip->max_flash_prog_size = 1<<10;
2160                                         subfamid = 4; /* errata 1N83J fix */
2161                                         break;
2162                                 }
2163                                 if ((k_chip->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K22FN128
2164                                         || (k_chip->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K22FN256
2165                                         || (k_chip->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K22FN512) {
2166                                         /* K22 with new-style SDID - smaller pflash with FTFA, 2kB sectors */
2167                                         k_chip->pflash_sector_size = 2<<10;
2168                                         /* autodetect 1 or 2 blocks */
2169                                         k_chip->flash_support = FS_PROGRAM_LONGWORD;
2170                                         break;
2171                                 }
2172                                 LOG_ERROR("Unsupported Kinetis K22 DIEID");
2173                                 break;
2174                         }
2175                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX4:
2176                                 k_chip->pflash_sector_size = 4<<10;
2177                                 if ((k_chip->sim_sdid & (KINETIS_SDID_DIEID_MASK)) == KINETIS_SDID_DIEID_K24FN256) {
2178                                         /* K24FN256 - smaller pflash with FTFA */
2179                                         num_blocks = 1;
2180                                         k_chip->flash_support = FS_PROGRAM_LONGWORD;
2181                                         break;
2182                                 }
2183                                 /* K24FN1M without errata 7534 */
2184                                 num_blocks = 2;
2185                                 k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
2186                                 k_chip->max_flash_prog_size = 1<<10;
2187                                 break;
2188
2189                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX1:     /* errata 7534 - should be K63 */
2190                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX2:     /* errata 7534 - should be K64 */
2191                                 subfamid += 2; /* errata 7534 fix */
2192                                 /* fallthrough */
2193                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX3:
2194                                 /* K63FN1M0 */
2195                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX4:
2196                                 /* K64FN1M0, K64FX512 */
2197                                 k_chip->pflash_sector_size = 4<<10;
2198                                 k_chip->nvm_sector_size = 4<<10;
2199                                 k_chip->max_flash_prog_size = 1<<10;
2200                                 num_blocks = 2;
2201                                 k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
2202                                 break;
2203
2204                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX6:
2205                                 /* K26FN2M0 */
2206                         case KINETIS_SDID_FAMILYID_K6X | KINETIS_SDID_SUBFAMID_KX6:
2207                                 /* K66FN2M0, K66FX1M0 */
2208                                 k_chip->pflash_sector_size = 4<<10;
2209                                 k_chip->nvm_sector_size = 4<<10;
2210                                 k_chip->max_flash_prog_size = 1<<10;
2211                                 num_blocks = 4;
2212                                 k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR | FS_ECC;
2213                                 cpu_mhz = 180;
2214                                 break;
2215
2216                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX7:
2217                                 /* K27FN2M0 */
2218                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX8:
2219                                 /* K28FN2M0 */
2220                                 k_chip->pflash_sector_size = 4<<10;
2221                                 k_chip->max_flash_prog_size = 1<<10;
2222                                 num_blocks = 4;
2223                                 k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR | FS_ECC;
2224                                 cpu_mhz = 150;
2225                                 break;
2226
2227                         case KINETIS_SDID_FAMILYID_K8X | KINETIS_SDID_SUBFAMID_KX0:
2228                         case KINETIS_SDID_FAMILYID_K8X | KINETIS_SDID_SUBFAMID_KX1:
2229                         case KINETIS_SDID_FAMILYID_K8X | KINETIS_SDID_SUBFAMID_KX2:
2230                                 /* K80FN256, K81FN256, K82FN256 */
2231                                 k_chip->pflash_sector_size = 4<<10;
2232                                 num_blocks = 1;
2233                                 k_chip->flash_support = FS_PROGRAM_LONGWORD | FS_NO_CMD_BLOCKSTAT;
2234                                 cpu_mhz = 150;
2235                                 break;
2236
2237                         case KINETIS_SDID_FAMILYID_KL8X | KINETIS_SDID_SUBFAMID_KX1:
2238                         case KINETIS_SDID_FAMILYID_KL8X | KINETIS_SDID_SUBFAMID_KX2:
2239                                 /* KL81Z128, KL82Z128 */
2240                                 k_chip->pflash_sector_size = 2<<10;
2241                                 num_blocks = 1;
2242                                 k_chip->flash_support = FS_PROGRAM_LONGWORD | FS_NO_CMD_BLOCKSTAT;
2243                                 k_chip->cache_type = KINETIS_CACHE_L;
2244
2245                                 use_nvm_marking = false;
2246                                 snprintf(name, sizeof(name), "MKL8%uZ%%s7",
2247                                          subfamid);
2248                                 break;
2249
2250                         default:
2251                                 LOG_ERROR("Unsupported Kinetis FAMILYID SUBFAMID");
2252                         }
2253
2254                         if (name[0] == '\0')
2255                                 snprintf(name, sizeof(name), "MK%u%uF%%s%u",
2256                                          familyid, subfamid, cpu_mhz / 10);
2257                         break;
2258
2259                 case KINETIS_SDID_SERIESID_KL:
2260                         /* KL-series */
2261                         k_chip->pflash_sector_size = 1<<10;
2262                         k_chip->nvm_sector_size = 1<<10;
2263                         /* autodetect 1 or 2 blocks */
2264                         k_chip->flash_support = FS_PROGRAM_LONGWORD;
2265                         k_chip->cache_type = KINETIS_CACHE_L;
2266                         k_chip->watchdog_type = KINETIS_WDOG_COP;
2267
2268                         cpu_mhz = 48;
2269                         switch (k_chip->sim_sdid & (KINETIS_SDID_FAMILYID_MASK | KINETIS_SDID_SUBFAMID_MASK)) {
2270                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX3:
2271                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX3:
2272                                 subfamid = 7;
2273                                 break;
2274
2275                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX8:
2276                                 cpu_mhz = 72;
2277                                 k_chip->pflash_sector_size = 2<<10;
2278                                 num_blocks = 2;
2279                                 k_chip->watchdog_type = KINETIS_WDOG32_KL28;
2280                                 k_chip->sysmodectrlr_type = KINETIS_SMC32;
2281                                 break;
2282                         }
2283
2284                         snprintf(name, sizeof(name), "MKL%u%uZ%%s%u",
2285                                  familyid, subfamid, cpu_mhz / 10);
2286                         break;
2287
2288                 case KINETIS_SDID_SERIESID_KW:
2289                         /* Newer KW-series (all KW series except KW2xD, KW01Z) */
2290                         cpu_mhz = 48;
2291                         switch (k_chip->sim_sdid & (KINETIS_SDID_FAMILYID_MASK | KINETIS_SDID_SUBFAMID_MASK)) {
2292                         case KINETIS_SDID_FAMILYID_K4X | KINETIS_SDID_SUBFAMID_KX0:
2293                                 /* KW40Z */
2294                         case KINETIS_SDID_FAMILYID_K3X | KINETIS_SDID_SUBFAMID_KX0:
2295                                 /* KW30Z */
2296                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX0:
2297                                 /* KW20Z */
2298                                 /* FTFA, 1kB sectors */
2299                                 k_chip->pflash_sector_size = 1<<10;
2300                                 k_chip->nvm_sector_size = 1<<10;
2301                                 /* autodetect 1 or 2 blocks */
2302                                 k_chip->flash_support = FS_PROGRAM_LONGWORD;
2303                                 k_chip->cache_type = KINETIS_CACHE_L;
2304                                 k_chip->watchdog_type = KINETIS_WDOG_COP;
2305                                 break;
2306                         case KINETIS_SDID_FAMILYID_K4X | KINETIS_SDID_SUBFAMID_KX1:
2307                                 /* KW41Z */
2308                         case KINETIS_SDID_FAMILYID_K3X | KINETIS_SDID_SUBFAMID_KX1:
2309                                 /* KW31Z */
2310                         case KINETIS_SDID_FAMILYID_K2X | KINETIS_SDID_SUBFAMID_KX1:
2311                                 /* KW21Z */
2312                                 /* FTFA, 2kB sectors */
2313                                 k_chip->pflash_sector_size = 2<<10;
2314                                 k_chip->nvm_sector_size = 2<<10;
2315                                 /* autodetect 1 or 2 blocks */
2316                                 k_chip->flash_support = FS_PROGRAM_LONGWORD;
2317                                 k_chip->cache_type = KINETIS_CACHE_L;
2318                                 k_chip->watchdog_type = KINETIS_WDOG_COP;
2319                                 break;
2320                         default:
2321                                 LOG_ERROR("Unsupported KW FAMILYID SUBFAMID");
2322                         }
2323                         snprintf(name, sizeof(name), "MKW%u%uZ%%s%u",
2324                                          familyid, subfamid, cpu_mhz / 10);
2325                         break;
2326
2327                 case KINETIS_SDID_SERIESID_KV:
2328                         /* KV-series */
2329                         k_chip->watchdog_type = KINETIS_WDOG_K;
2330                         switch (k_chip->sim_sdid & (KINETIS_SDID_FAMILYID_MASK | KINETIS_SDID_SUBFAMID_MASK)) {
2331                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX0:
2332                                 /* KV10: FTFA, 1kB sectors */
2333                                 k_chip->pflash_sector_size = 1<<10;
2334                                 num_blocks = 1;
2335                                 k_chip->flash_support = FS_PROGRAM_LONGWORD;
2336                                 k_chip->cache_type = KINETIS_CACHE_L;
2337                                 strcpy(name, "MKV10Z%s7");
2338                                 break;
2339
2340                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX1:
2341                                 /* KV11: FTFA, 2kB sectors */
2342                                 k_chip->pflash_sector_size = 2<<10;
2343                                 num_blocks = 1;
2344                                 k_chip->flash_support = FS_PROGRAM_LONGWORD;
2345                                 k_chip->cache_type = KINETIS_CACHE_L;
2346                                 strcpy(name, "MKV11Z%s7");
2347                                 break;
2348
2349                         case KINETIS_SDID_FAMILYID_K3X | KINETIS_SDID_SUBFAMID_KX0:
2350                                 /* KV30: FTFA, 2kB sectors, 1 block */
2351                         case KINETIS_SDID_FAMILYID_K3X | KINETIS_SDID_SUBFAMID_KX1:
2352                                 /* KV31: FTFA, 2kB sectors, 2 blocks */
2353                                 k_chip->pflash_sector_size = 2<<10;
2354                                 /* autodetect 1 or 2 blocks */
2355                                 k_chip->flash_support = FS_PROGRAM_LONGWORD;
2356                                 k_chip->cache_type = KINETIS_CACHE_K;
2357                                 break;
2358
2359                         case KINETIS_SDID_FAMILYID_K4X | KINETIS_SDID_SUBFAMID_KX2:
2360                         case KINETIS_SDID_FAMILYID_K4X | KINETIS_SDID_SUBFAMID_KX4:
2361                         case KINETIS_SDID_FAMILYID_K4X | KINETIS_SDID_SUBFAMID_KX6:
2362                                 /* KV4x: FTFA, 4kB sectors */
2363                                 k_chip->pflash_sector_size = 4<<10;
2364                                 num_blocks = 1;
2365                                 k_chip->flash_support = FS_PROGRAM_LONGWORD;
2366                                 k_chip->cache_type = KINETIS_CACHE_K;
2367                                 cpu_mhz = 168;
2368                                 break;
2369
2370                         case KINETIS_SDID_FAMILYID_K5X | KINETIS_SDID_SUBFAMID_KX6:
2371                         case KINETIS_SDID_FAMILYID_K5X | KINETIS_SDID_SUBFAMID_KX8:
2372                                 /* KV5x: FTFE, 8kB sectors */
2373                                 k_chip->pflash_sector_size = 8<<10;
2374                                 k_chip->max_flash_prog_size = 1<<10;
2375                                 num_blocks = 1;
2376                                 maxaddr_shift = 14;
2377                                 k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR | FS_WIDTH_256BIT | FS_ECC;
2378                                 k_chip->pflash_base = 0x10000000;
2379                                 k_chip->progr_accel_ram = 0x18000000;
2380                                 cpu_mhz = 240;
2381                                 break;
2382
2383                         default:
2384                                 LOG_ERROR("Unsupported KV FAMILYID SUBFAMID");
2385                         }
2386
2387                         if (name[0] == '\0')
2388                                 snprintf(name, sizeof(name), "MKV%u%uF%%s%u",
2389                                          familyid, subfamid, cpu_mhz / 10);
2390                         break;
2391
2392                 case KINETIS_SDID_SERIESID_KE:
2393                         /* KE1x-series */
2394                         k_chip->watchdog_type = KINETIS_WDOG32_KE1X;
2395                         switch (k_chip->sim_sdid &
2396                                 (KINETIS_SDID_FAMILYID_MASK | KINETIS_SDID_SUBFAMID_MASK | KINETIS_SDID_PROJECTID_MASK)) {
2397                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX4 | KINETIS_SDID_PROJECTID_KE1xZ:
2398                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX5 | KINETIS_SDID_PROJECTID_KE1xZ:
2399                                 /* KE1xZ: FTFE, 2kB sectors */
2400                                 k_chip->pflash_sector_size = 2<<10;
2401                                 k_chip->nvm_sector_size = 2<<10;
2402                                 k_chip->max_flash_prog_size = 1<<9;
2403                                 num_blocks = 2;
2404                                 k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
2405                                 k_chip->cache_type = KINETIS_CACHE_L;
2406
2407                                 cpu_mhz = 72;
2408                                 snprintf(name, sizeof(name), "MKE%u%uZ%%s%u",
2409                                          familyid, subfamid, cpu_mhz / 10);
2410                                 break;
2411
2412                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX4 | KINETIS_SDID_PROJECTID_KE1xF:
2413                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX6 | KINETIS_SDID_PROJECTID_KE1xF:
2414                         case KINETIS_SDID_FAMILYID_K1X | KINETIS_SDID_SUBFAMID_KX8 | KINETIS_SDID_PROJECTID_KE1xF:
2415                                 /* KE1xF: FTFE, 4kB sectors */
2416                                 k_chip->pflash_sector_size = 4<<10;
2417                                 k_chip->nvm_sector_size = 2<<10;
2418                                 k_chip->max_flash_prog_size = 1<<10;
2419                                 num_blocks = 2;
2420                                 k_chip->flash_support = FS_PROGRAM_PHRASE | FS_PROGRAM_SECTOR;
2421                                 k_chip->cache_type = KINETIS_CACHE_MSCM;
2422
2423                                 cpu_mhz = 168;
2424                                 snprintf(name, sizeof(name), "MKE%u%uF%%s%u",
2425                                          familyid, subfamid, cpu_mhz / 10);
2426                                 break;
2427
2428                         default:
2429                                 LOG_ERROR("Unsupported KE FAMILYID SUBFAMID");
2430                         }
2431                         break;
2432
2433                 default:
2434                         LOG_ERROR("Unsupported K-series");
2435                 }
2436         }
2437
2438         if (k_chip->pflash_sector_size == 0) {
2439                 LOG_ERROR("MCU is unsupported, SDID 0x%08" PRIx32, k_chip->sim_sdid);
2440                 return ERROR_FLASH_OPER_UNSUPPORTED;
2441         }
2442
2443         result = target_read_u32(target, k_chip->sim_base + SIM_FCFG1_OFFSET, &k_chip->sim_fcfg1);
2444         if (result != ERROR_OK)
2445                 return result;
2446
2447         result = target_read_u32(target, k_chip->sim_base + SIM_FCFG2_OFFSET, &k_chip->sim_fcfg2);
2448         if (result != ERROR_OK)
2449                 return result;
2450
2451         LOG_DEBUG("SDID: 0x%08" PRIX32 " FCFG1: 0x%08" PRIX32 " FCFG2: 0x%08" PRIX32, k_chip->sim_sdid,
2452                         k_chip->sim_fcfg1, k_chip->sim_fcfg2);
2453
2454         fcfg1_nvmsize = (uint8_t)((k_chip->sim_fcfg1 >> 28) & 0x0f);
2455         fcfg1_pfsize = (uint8_t)((k_chip->sim_fcfg1 >> 24) & 0x0f);
2456         fcfg1_eesize = (uint8_t)((k_chip->sim_fcfg1 >> 16) & 0x0f);
2457         fcfg1_depart = (uint8_t)((k_chip->sim_fcfg1 >> 8) & 0x0f);
2458
2459         fcfg2_pflsh = (uint8_t)((k_chip->sim_fcfg2 >> 23) & 0x01);
2460         k_chip->fcfg2_maxaddr0_shifted = ((k_chip->sim_fcfg2 >> 24) & 0x7f) << maxaddr_shift;
2461         k_chip->fcfg2_maxaddr1_shifted = ((k_chip->sim_fcfg2 >> 16) & 0x7f) << maxaddr_shift;
2462
2463         if (num_blocks == 0)
2464                 num_blocks = k_chip->fcfg2_maxaddr1_shifted ? 2 : 1;
2465         else if (k_chip->fcfg2_maxaddr1_shifted == 0 && num_blocks >= 2 && fcfg2_pflsh) {
2466                 /* fcfg2_maxaddr1 may be zero due to partitioning whole NVM as EEPROM backup
2467                  * Do not adjust block count in this case! */
2468                 num_blocks = 1;
2469                 LOG_WARNING("MAXADDR1 is zero, number of flash banks adjusted to 1");
2470         } else if (k_chip->fcfg2_maxaddr1_shifted != 0 && num_blocks == 1) {
2471                 num_blocks = 2;
2472                 LOG_WARNING("MAXADDR1 is non zero, number of flash banks adjusted to 2");
2473         }
2474
2475         /* when the PFLSH bit is set, there is no FlexNVM/FlexRAM */
2476         if (!fcfg2_pflsh) {
2477                 switch (fcfg1_nvmsize) {
2478                 case 0x03:
2479                 case 0x05:
2480                 case 0x07:
2481                 case 0x09:
2482                 case 0x0b:
2483                         k_chip->nvm_size = 1 << (14 + (fcfg1_nvmsize >> 1));
2484                         break;
2485                 case 0x0f:
2486                         if (k_chip->pflash_sector_size >= 4<<10)
2487                                 k_chip->nvm_size = 512<<10;
2488                         else
2489                                 /* K20_100 */
2490                                 k_chip->nvm_size = 256<<10;
2491                         break;
2492                 default:
2493                         k_chip->nvm_size = 0;
2494                         break;
2495                 }
2496
2497                 switch (fcfg1_eesize) {
2498                 case 0x00:
2499                 case 0x01:
2500                 case 0x02:
2501                 case 0x03:
2502                 case 0x04:
2503                 case 0x05:
2504                 case 0x06:
2505                 case 0x07:
2506                 case 0x08:
2507                 case 0x09:
2508                         ee_size = (16 << (10 - fcfg1_eesize));
2509                         break;
2510                 default:
2511                         ee_size = 0;
2512                         break;
2513                 }
2514
2515                 switch (fcfg1_depart) {
2516                 case 0x01:
2517                 case 0x02:
2518                 case 0x03:
2519                 case 0x04:
2520                 case 0x05:
2521                 case 0x06:
2522                         k_chip->dflash_size = k_chip->nvm_size - (4096 << fcfg1_depart);
2523                         break;
2524                 case 0x07:
2525                 case 0x08:
2526                         k_chip->dflash_size = 0;
2527                         break;
2528                 case 0x09:
2529                 case 0x0a:
2530                 case 0x0b:
2531                 case 0x0c:
2532                 case 0x0d:
2533                         k_chip->dflash_size = 4096 << (fcfg1_depart & 0x7);
2534                         break;
2535                 default:
2536                         k_chip->dflash_size = k_chip->nvm_size;
2537                         break;
2538                 }
2539         }
2540
2541         switch (fcfg1_pfsize) {
2542         case 0x00:
2543                 k_chip->pflash_size = 8192;
2544                 break;
2545         case 0x01:
2546         case 0x03:
2547         case 0x05:
2548         case 0x07:
2549         case 0x09:
2550         case 0x0b:
2551         case 0x0d:
2552                 k_chip->pflash_size = 1 << (14 + (fcfg1_pfsize >> 1));
2553                 break;
2554         case 0x0f:
2555                 /* a peculiar case: Freescale states different sizes for 0xf
2556                  * KL03P24M48SF0RM      32 KB .... duplicate of code 0x3
2557                  * K02P64M100SFARM      128 KB ... duplicate of code 0x7
2558                  * K22P121M120SF8RM     256 KB ... duplicate of code 0x9
2559                  * K22P121M120SF7RM     512 KB ... duplicate of code 0xb
2560                  * K22P100M120SF5RM     1024 KB ... duplicate of code 0xd
2561                  * K26P169M180SF5RM     2048 KB ... the only unique value
2562                  * fcfg2_maxaddr0 seems to be the only clue to pflash_size
2563                  * Checking fcfg2_maxaddr0 in bank probe is pointless then
2564                  */
2565                 if (fcfg2_pflsh)
2566                         k_chip->pflash_size = k_chip->fcfg2_maxaddr0_shifted * num_blocks;
2567                 else
2568                         k_chip->pflash_size = k_chip->fcfg2_maxaddr0_shifted * num_blocks / 2;
2569                 if (k_chip->pflash_size != 2048<<10)
2570                         LOG_WARNING("SIM_FCFG1 PFSIZE = 0xf: please check if pflash is %u KB", k_chip->pflash_size>>10);
2571
2572                 break;
2573         default:
2574                 k_chip->pflash_size = 0;
2575                 break;
2576         }
2577
2578         if (k_chip->flash_support & FS_PROGRAM_SECTOR && k_chip->max_flash_prog_size == 0) {
2579                 k_chip->max_flash_prog_size = k_chip->pflash_sector_size;
2580                 /* Program section size is equal to sector size by default */
2581         }
2582
2583         if (fcfg2_pflsh) {
2584                 k_chip->num_pflash_blocks = num_blocks;
2585                 k_chip->num_nvm_blocks = 0;
2586         } else {
2587                 k_chip->num_pflash_blocks = (num_blocks + 1) / 2;
2588                 k_chip->num_nvm_blocks = num_blocks - k_chip->num_pflash_blocks;
2589         }
2590
2591         if (use_nvm_marking) {
2592                 nvm_marking[0] = k_chip->num_nvm_blocks ? 'X' : 'N';
2593                 nvm_marking[1] = '\0';
2594         } else
2595                 nvm_marking[0] = '\0';
2596
2597         pflash_size_k = k_chip->pflash_size / 1024;
2598         pflash_size_m = pflash_size_k / 1024;
2599         if (pflash_size_m)
2600                 snprintf(flash_marking, sizeof(flash_marking), "%s%" PRIu32 "M0xxx", nvm_marking, pflash_size_m);
2601         else
2602                 snprintf(flash_marking, sizeof(flash_marking), "%s%" PRIu32 "xxx", nvm_marking, pflash_size_k);
2603
2604         snprintf(k_chip->name, sizeof(k_chip->name), name, flash_marking);
2605         LOG_INFO("Kinetis %s detected: %u flash blocks", k_chip->name, num_blocks);
2606         LOG_INFO("%u PFlash banks: %" PRIu32 "k total", k_chip->num_pflash_blocks, pflash_size_k);
2607         if (k_chip->num_nvm_blocks) {
2608                 nvm_size_k = k_chip->nvm_size / 1024;
2609                 dflash_size_k = k_chip->dflash_size / 1024;
2610                 LOG_INFO("%u FlexNVM banks: %" PRIu32 "k total, %" PRIu32 "k available as data flash, %" PRIu32 "bytes FlexRAM",
2611                          k_chip->num_nvm_blocks, nvm_size_k, dflash_size_k, ee_size);
2612         }
2613
2614         k_chip->probed = true;
2615
2616         if (create_banks)
2617                 kinetis_create_missing_banks(k_chip);
2618
2619         return ERROR_OK;
2620 }
2621
2622 static int kinetis_probe(struct flash_bank *bank)
2623 {
2624         int result, i;
2625         uint8_t fcfg2_maxaddr0, fcfg2_pflsh, fcfg2_maxaddr1;
2626         unsigned num_blocks, first_nvm_bank;
2627         uint32_t size_k;
2628         struct kinetis_flash_bank *k_bank = bank->driver_priv;
2629         struct kinetis_chip *k_chip;
2630
2631         assert(k_bank);
2632         k_chip = k_bank->k_chip;
2633
2634         k_bank->probed = false;
2635
2636         if (!k_chip->probed) {
2637                 result = kinetis_probe_chip(k_chip);
2638                 if (result != ERROR_OK)
2639                         return result;
2640         }
2641
2642         num_blocks = k_chip->num_pflash_blocks + k_chip->num_nvm_blocks;
2643         first_nvm_bank = k_chip->num_pflash_blocks;
2644
2645         if (k_bank->bank_number < k_chip->num_pflash_blocks) {
2646                 /* pflash, banks start at address zero */
2647                 k_bank->flash_class = FC_PFLASH;
2648                 bank->size = (k_chip->pflash_size / k_chip->num_pflash_blocks);
2649                 bank->base = k_chip->pflash_base + bank->size * k_bank->bank_number;
2650                 k_bank->prog_base = 0x00000000 + bank->size * k_bank->bank_number;
2651                 k_bank->sector_size = k_chip->pflash_sector_size;
2652                 /* pflash is divided into 32 protection areas for
2653                  * parts with more than 32K of PFlash. For parts with
2654                  * less the protection unit is set to 1024 bytes */
2655                 k_bank->protection_size = MAX(k_chip->pflash_size / 32, 1024);
2656                 bank->num_prot_blocks = bank->size / k_bank->protection_size;
2657                 k_bank->protection_block = bank->num_prot_blocks * k_bank->bank_number;
2658
2659                 size_k = bank->size / 1024;
2660                 LOG_DEBUG("Kinetis bank %u: %" PRIu32 "k PFlash, FTFx base 0x%08" PRIx32 ", sect %u",
2661                          k_bank->bank_number, size_k, k_bank->prog_base, k_bank->sector_size);
2662
2663         } else if (k_bank->bank_number < num_blocks) {
2664                 /* nvm, banks start at address 0x10000000 */
2665                 unsigned nvm_ord = k_bank->bank_number - first_nvm_bank;
2666                 uint32_t limit;
2667
2668                 k_bank->flash_class = FC_FLEX_NVM;
2669                 bank->size = k_chip->nvm_size / k_chip->num_nvm_blocks;
2670                 bank->base = k_chip->nvm_base + bank->size * nvm_ord;
2671                 k_bank->prog_base = 0x00800000 + bank->size * nvm_ord;
2672                 k_bank->sector_size = k_chip->nvm_sector_size;
2673                 if (k_chip->dflash_size == 0) {
2674                         k_bank->protection_size = 0;
2675                 } else {
2676                         for (i = k_chip->dflash_size; ~i & 1; i >>= 1)
2677                                 ;
2678                         if (i == 1)
2679                                 k_bank->protection_size = k_chip->dflash_size / 8;      /* data flash size = 2^^n */
2680                         else
2681                                 k_bank->protection_size = k_chip->nvm_size / 8; /* TODO: verify on SF1, not documented in RM */
2682                 }
2683                 bank->num_prot_blocks = 8 / k_chip->num_nvm_blocks;
2684                 k_bank->protection_block = bank->num_prot_blocks * nvm_ord;
2685
2686                 /* EEPROM backup part of FlexNVM is not accessible, use dflash_size as a limit */
2687                 if (k_chip->dflash_size > bank->size * nvm_ord)
2688                         limit = k_chip->dflash_size - bank->size * nvm_ord;
2689                 else
2690                         limit = 0;
2691
2692                 if (bank->size > limit) {
2693                         bank->size = limit;
2694                         LOG_DEBUG("FlexNVM bank %d limited to 0x%08" PRIx32 " due to active EEPROM backup",
2695                                 k_bank->bank_number, limit);
2696                 }
2697
2698                 size_k = bank->size / 1024;
2699                 LOG_DEBUG("Kinetis bank %u: %" PRIu32 "k FlexNVM, FTFx base 0x%08" PRIx32 ", sect %u",
2700                          k_bank->bank_number, size_k, k_bank->prog_base, k_bank->sector_size);
2701
2702         } else {
2703                 LOG_ERROR("Cannot determine parameters for bank %d, only %d banks on device",
2704                                 k_bank->bank_number, num_blocks);
2705                 return ERROR_FLASH_BANK_INVALID;
2706         }
2707
2708         fcfg2_pflsh = (uint8_t)((k_chip->sim_fcfg2 >> 23) & 0x01);
2709         fcfg2_maxaddr0 = (uint8_t)((k_chip->sim_fcfg2 >> 24) & 0x7f);
2710         fcfg2_maxaddr1 = (uint8_t)((k_chip->sim_fcfg2 >> 16) & 0x7f);
2711
2712         if (k_bank->bank_number == 0 && k_chip->fcfg2_maxaddr0_shifted != bank->size)
2713                 LOG_WARNING("MAXADDR0 0x%02" PRIx8 " check failed,"
2714                                 " please report to OpenOCD mailing list", fcfg2_maxaddr0);
2715
2716         if (fcfg2_pflsh) {
2717                 if (k_bank->bank_number == 1 && k_chip->fcfg2_maxaddr1_shifted != bank->size)
2718                         LOG_WARNING("MAXADDR1 0x%02" PRIx8 " check failed,"
2719                                 " please report to OpenOCD mailing list", fcfg2_maxaddr1);
2720         } else {
2721                 if (k_bank->bank_number == first_nvm_bank
2722                                 && k_chip->fcfg2_maxaddr1_shifted != k_chip->dflash_size)
2723                         LOG_WARNING("FlexNVM MAXADDR1 0x%02" PRIx8 " check failed,"
2724                                 " please report to OpenOCD mailing list", fcfg2_maxaddr1);
2725         }
2726
2727         if (bank->sectors) {
2728                 free(bank->sectors);
2729                 bank->sectors = NULL;
2730         }
2731         if (bank->prot_blocks) {
2732                 free(bank->prot_blocks);
2733                 bank->prot_blocks = NULL;
2734         }
2735
2736         if (k_bank->sector_size == 0) {
2737                 LOG_ERROR("Unknown sector size for bank %d", bank->bank_number);
2738                 return ERROR_FLASH_BANK_INVALID;
2739         }
2740
2741         bank->num_sectors = bank->size / k_bank->sector_size;
2742
2743         if (bank->num_sectors > 0) {
2744                 /* FlexNVM bank can be used for EEPROM backup therefore zero sized */
2745                 bank->sectors = alloc_block_array(0, k_bank->sector_size, bank->num_sectors);
2746                 if (!bank->sectors)
2747                         return ERROR_FAIL;
2748
2749                 bank->prot_blocks = alloc_block_array(0, k_bank->protection_size, bank->num_prot_blocks);
2750                 if (!bank->prot_blocks)
2751                         return ERROR_FAIL;
2752
2753         } else {
2754                 bank->num_prot_blocks = 0;
2755         }
2756
2757         k_bank->probed = true;
2758
2759         return ERROR_OK;
2760 }
2761
2762 static int kinetis_auto_probe(struct flash_bank *bank)
2763 {
2764         struct kinetis_flash_bank *k_bank = bank->driver_priv;
2765
2766         if (k_bank && k_bank->probed)
2767                 return ERROR_OK;
2768
2769         return kinetis_probe(bank);
2770 }
2771
2772 static int kinetis_info(struct flash_bank *bank, char *buf, int buf_size)
2773 {
2774         const char *bank_class_names[] = {
2775                 "(ANY)", "PFlash", "FlexNVM", "FlexRAM"
2776         };
2777
2778         struct kinetis_flash_bank *k_bank = bank->driver_priv;
2779         struct kinetis_chip *k_chip = k_bank->k_chip;
2780         uint32_t size_k = bank->size / 1024;
2781
2782         snprintf(buf, buf_size,
2783                 "%s %s: %" PRIu32 "k %s bank %s at " TARGET_ADDR_FMT,
2784                 bank->driver->name, k_chip->name,
2785                 size_k, bank_class_names[k_bank->flash_class],
2786                 bank->name, bank->base);
2787
2788         return ERROR_OK;
2789 }
2790
2791 static int kinetis_blank_check(struct flash_bank *bank)
2792 {
2793         struct kinetis_flash_bank *k_bank = bank->driver_priv;
2794         struct kinetis_chip *k_chip = k_bank->k_chip;
2795         int result;
2796
2797         /* suprisingly blank check does not work in VLPR and HSRUN modes */
2798         result = kinetis_check_run_mode(k_chip);
2799         if (result != ERROR_OK)
2800                 return result;
2801
2802         /* reset error flags */
2803         result = kinetis_ftfx_prepare(bank->target);
2804         if (result != ERROR_OK)
2805                 return result;
2806
2807         if (k_bank->flash_class == FC_PFLASH || k_bank->flash_class == FC_FLEX_NVM) {
2808                 bool block_dirty = true;
2809                 bool use_block_cmd = !(k_chip->flash_support & FS_NO_CMD_BLOCKSTAT);
2810                 uint8_t ftfx_fstat;
2811
2812                 if (use_block_cmd && k_bank->flash_class == FC_FLEX_NVM) {
2813                         uint8_t fcfg1_depart = (uint8_t)((k_chip->sim_fcfg1 >> 8) & 0x0f);
2814                         /* block operation cannot be used on FlexNVM when EEPROM backup partition is set */
2815                         if (fcfg1_depart != 0xf && fcfg1_depart != 0)
2816                                 use_block_cmd = false;
2817                 }
2818
2819                 if (use_block_cmd) {
2820                         /* check if whole bank is blank */
2821                         result = kinetis_ftfx_command(bank->target, FTFx_CMD_BLOCKSTAT, k_bank->prog_base,
2822                                                          0, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
2823
2824                         if (result != ERROR_OK)
2825                                 kinetis_ftfx_clear_error(bank->target);
2826                         else if ((ftfx_fstat & 0x01) == 0)
2827                                 block_dirty = false;
2828                 }
2829
2830                 if (block_dirty) {
2831                         /* the whole bank is not erased, check sector-by-sector */
2832                         int i;
2833                         for (i = 0; i < bank->num_sectors; i++) {
2834                                 /* normal margin */
2835                                 result = kinetis_ftfx_command(bank->target, FTFx_CMD_SECTSTAT,
2836                                                 k_bank->prog_base + bank->sectors[i].offset,
2837                                                 1, 0, 0, 0,  0, 0, 0, 0, &ftfx_fstat);
2838
2839                                 if (result == ERROR_OK) {
2840                                         bank->sectors[i].is_erased = !(ftfx_fstat & 0x01);
2841                                 } else {
2842                                         LOG_DEBUG("Ignoring errored PFlash sector blank-check");
2843                                         kinetis_ftfx_clear_error(bank->target);
2844                                         bank->sectors[i].is_erased = -1;
2845                                 }
2846                         }
2847                 } else {
2848                         /* the whole bank is erased, update all sectors */
2849                         int i;
2850                         for (i = 0; i < bank->num_sectors; i++)
2851                                 bank->sectors[i].is_erased = 1;
2852                 }
2853         } else {
2854                 LOG_WARNING("kinetis_blank_check not supported yet for FlexRAM");
2855                 return ERROR_FLASH_OPERATION_FAILED;
2856         }
2857
2858         return ERROR_OK;
2859 }
2860
2861
2862 COMMAND_HANDLER(kinetis_nvm_partition)
2863 {
2864         int result;
2865         unsigned bank_idx;
2866         unsigned num_blocks, first_nvm_bank;
2867         unsigned long par, log2 = 0, ee1 = 0, ee2 = 0;
2868         enum { SHOW_INFO, DF_SIZE, EEBKP_SIZE } sz_type = SHOW_INFO;
2869         bool enable;
2870         uint8_t load_flex_ram = 1;
2871         uint8_t ee_size_code = 0x3f;
2872         uint8_t flex_nvm_partition_code = 0;
2873         uint8_t ee_split = 3;
2874         struct target *target = get_current_target(CMD_CTX);
2875         struct kinetis_chip *k_chip;
2876         uint32_t sim_fcfg1;
2877
2878         k_chip = kinetis_get_chip(target);
2879
2880         if (CMD_ARGC >= 2) {
2881                 if (strcmp(CMD_ARGV[0], "dataflash") == 0)
2882                         sz_type = DF_SIZE;
2883                 else if (strcmp(CMD_ARGV[0], "eebkp") == 0)
2884                         sz_type = EEBKP_SIZE;
2885
2886                 par = strtoul(CMD_ARGV[1], NULL, 10);
2887                 while (par >> (log2 + 3))
2888                         log2++;
2889         }
2890         switch (sz_type) {
2891         case SHOW_INFO:
2892                 if (k_chip == NULL) {
2893                         LOG_ERROR("Chip not probed.");
2894                         return ERROR_FAIL;
2895                 }
2896                 result = target_read_u32(target, k_chip->sim_base + SIM_FCFG1_OFFSET, &sim_fcfg1);
2897                 if (result != ERROR_OK)
2898                         return result;
2899
2900                 flex_nvm_partition_code = (uint8_t)((sim_fcfg1 >> 8) & 0x0f);
2901                 switch (flex_nvm_partition_code) {
2902                 case 0:
2903                         command_print(CMD, "No EEPROM backup, data flash only");
2904                         break;
2905                 case 1:
2906                 case 2:
2907                 case 3:
2908                 case 4:
2909                 case 5:
2910                 case 6:
2911                         command_print(CMD, "EEPROM backup %d KB", 4 << flex_nvm_partition_code);
2912                         break;
2913                 case 8:
2914                         command_print(CMD, "No data flash, EEPROM backup only");
2915                         break;
2916                 case 0x9:
2917                 case 0xA:
2918                 case 0xB:
2919                 case 0xC:
2920                 case 0xD:
2921                 case 0xE:
2922                         command_print(CMD, "data flash %d KB", 4 << (flex_nvm_partition_code & 7));
2923                         break;
2924                 case 0xf:
2925                         command_print(CMD, "No EEPROM backup, data flash only (DEPART not set)");
2926                         break;
2927                 default:
2928                         command_print(CMD, "Unsupported EEPROM backup size code 0x%02" PRIx8, flex_nvm_partition_code);
2929                 }
2930                 return ERROR_OK;
2931
2932         case DF_SIZE:
2933                 flex_nvm_partition_code = 0x8 | log2;
2934                 break;
2935
2936         case EEBKP_SIZE:
2937                 flex_nvm_partition_code = log2;
2938                 break;
2939         }
2940
2941         if (CMD_ARGC == 3)
2942                 ee1 = ee2 = strtoul(CMD_ARGV[2], NULL, 10) / 2;
2943         else if (CMD_ARGC >= 4) {
2944                 ee1 = strtoul(CMD_ARGV[2], NULL, 10);
2945                 ee2 = strtoul(CMD_ARGV[3], NULL, 10);
2946         }
2947
2948         enable = ee1 + ee2 > 0;
2949         if (enable) {
2950                 for (log2 = 2; ; log2++) {
2951                         if (ee1 + ee2 == (16u << 10) >> log2)
2952                                 break;
2953                         if (ee1 + ee2 > (16u << 10) >> log2 || log2 >= 9) {
2954                                 LOG_ERROR("Unsupported EEPROM size");
2955                                 return ERROR_FLASH_OPERATION_FAILED;
2956                         }
2957                 }
2958
2959                 if (ee1 * 3 == ee2)
2960                         ee_split = 1;
2961                 else if (ee1 * 7 == ee2)
2962                         ee_split = 0;
2963                 else if (ee1 != ee2) {
2964                         LOG_ERROR("Unsupported EEPROM sizes ratio");
2965                         return ERROR_FLASH_OPERATION_FAILED;
2966                 }
2967
2968                 ee_size_code = log2 | ee_split << 4;
2969         }
2970
2971         if (CMD_ARGC >= 5)
2972                 COMMAND_PARSE_ON_OFF(CMD_ARGV[4], enable);
2973         if (enable)
2974                 load_flex_ram = 0;
2975
2976         LOG_INFO("DEPART 0x%" PRIx8 ", EEPROM size code 0x%" PRIx8,
2977                  flex_nvm_partition_code, ee_size_code);
2978
2979         result = kinetis_check_run_mode(k_chip);
2980         if (result != ERROR_OK)
2981                 return result;
2982
2983         /* reset error flags */
2984         result = kinetis_ftfx_prepare(target);
2985         if (result != ERROR_OK)
2986                 return result;
2987
2988         result = kinetis_ftfx_command(target, FTFx_CMD_PGMPART, load_flex_ram,
2989                                       ee_size_code, flex_nvm_partition_code, 0, 0,
2990                                       0, 0, 0, 0,  NULL);
2991         if (result != ERROR_OK)
2992                 return result;
2993
2994         command_print(CMD, "FlexNVM partition set. Please reset MCU.");
2995
2996         if (k_chip) {
2997                 first_nvm_bank = k_chip->num_pflash_blocks;
2998                 num_blocks = k_chip->num_pflash_blocks + k_chip->num_nvm_blocks;
2999                 for (bank_idx = first_nvm_bank; bank_idx < num_blocks; bank_idx++)
3000                         k_chip->banks[bank_idx].probed = false; /* re-probe before next use */
3001                 k_chip->probed = false;
3002         }
3003
3004         command_print(CMD, "FlexNVM banks will be re-probed to set new data flash size.");
3005         return ERROR_OK;
3006 }
3007
3008 COMMAND_HANDLER(kinetis_fcf_source_handler)
3009 {
3010         if (CMD_ARGC > 1)
3011                 return ERROR_COMMAND_SYNTAX_ERROR;
3012
3013         if (CMD_ARGC == 1) {
3014                 if (strcmp(CMD_ARGV[0], "write") == 0)
3015                         allow_fcf_writes = true;
3016                 else if (strcmp(CMD_ARGV[0], "protection") == 0)
3017                         allow_fcf_writes = false;
3018                 else
3019                         return ERROR_COMMAND_SYNTAX_ERROR;
3020         }
3021
3022         if (allow_fcf_writes) {
3023                 command_print(CMD, "Arbitrary Flash Configuration Field writes enabled.");
3024                 command_print(CMD, "Protection info writes to FCF disabled.");
3025                 LOG_WARNING("BEWARE: incorrect flash configuration may permanently lock the device.");
3026         } else {
3027                 command_print(CMD, "Protection info writes to Flash Configuration Field enabled.");
3028                 command_print(CMD, "Arbitrary FCF writes disabled. Mode safe from unwanted locking of the device.");
3029         }
3030
3031         return ERROR_OK;
3032 }
3033
3034 COMMAND_HANDLER(kinetis_fopt_handler)
3035 {
3036         if (CMD_ARGC > 1)
3037                 return ERROR_COMMAND_SYNTAX_ERROR;
3038
3039         if (CMD_ARGC == 1) {
3040                 fcf_fopt = (uint8_t)strtoul(CMD_ARGV[0], NULL, 0);
3041                 fcf_fopt_configured = true;
3042         } else {
3043                 command_print(CMD, "FCF_FOPT 0x%02" PRIx8, fcf_fopt);
3044         }
3045
3046         return ERROR_OK;
3047 }
3048
3049 COMMAND_HANDLER(kinetis_create_banks_handler)
3050 {
3051         if (CMD_ARGC > 0)
3052                 return ERROR_COMMAND_SYNTAX_ERROR;
3053
3054         create_banks = true;
3055
3056         return ERROR_OK;
3057 }
3058
3059
3060 static const struct command_registration kinetis_security_command_handlers[] = {
3061         {
3062                 .name = "check_security",
3063                 .mode = COMMAND_EXEC,
3064                 .help = "Check status of device security lock",
3065                 .usage = "",
3066                 .handler = kinetis_check_flash_security_status,
3067         },
3068         {
3069                 .name = "halt",
3070                 .mode = COMMAND_EXEC,
3071                 .help = "Issue a halt via the MDM-AP",
3072                 .usage = "",
3073                 .handler = kinetis_mdm_halt,
3074         },
3075         {
3076                 .name = "mass_erase",
3077                 .mode = COMMAND_EXEC,
3078                 .help = "Issue a complete flash erase via the MDM-AP",
3079                 .usage = "",
3080                 .handler = kinetis_mdm_mass_erase,
3081         },
3082         {
3083                 .name = "reset",
3084                 .mode = COMMAND_EXEC,
3085                 .help = "Issue a reset via the MDM-AP",
3086                 .usage = "",
3087                 .handler = kinetis_mdm_reset,
3088         },
3089         COMMAND_REGISTRATION_DONE
3090 };
3091
3092 static const struct command_registration kinetis_exec_command_handlers[] = {
3093         {
3094                 .name = "mdm",
3095                 .mode = COMMAND_ANY,
3096                 .help = "MDM-AP command group",
3097                 .usage = "",
3098                 .chain = kinetis_security_command_handlers,
3099         },
3100         {
3101                 .name = "disable_wdog",
3102                 .mode = COMMAND_EXEC,
3103                 .help = "Disable the watchdog timer",
3104                 .usage = "",
3105                 .handler = kinetis_disable_wdog_handler,
3106         },
3107         {
3108                 .name = "nvm_partition",
3109                 .mode = COMMAND_EXEC,
3110                 .help = "Show/set data flash or EEPROM backup size in kilobytes,"
3111                         " set two EEPROM sizes in bytes and FlexRAM loading during reset",
3112                 .usage = "('info'|'dataflash' size|'eebkp' size) [eesize1 eesize2] ['on'|'off']",
3113                 .handler = kinetis_nvm_partition,
3114         },
3115         {
3116                 .name = "fcf_source",
3117                 .mode = COMMAND_EXEC,
3118                 .help = "Use protection as a source for Flash Configuration Field or allow writing arbitrary values to the FCF"
3119                         " Mode 'protection' is safe from unwanted locking of the device.",
3120                 .usage = "['protection'|'write']",
3121                 .handler = kinetis_fcf_source_handler,
3122         },
3123         {
3124                 .name = "fopt",
3125                 .mode = COMMAND_EXEC,
3126                 .help = "FCF_FOPT value source in 'kinetis fcf_source protection' mode",
3127                 .usage = "[num]",
3128                 .handler = kinetis_fopt_handler,
3129         },
3130         {
3131                 .name = "create_banks",
3132                 .mode = COMMAND_CONFIG,
3133                 .help = "Driver creates additional banks if device with two/four flash blocks is probed",
3134                 .handler = kinetis_create_banks_handler,
3135                 .usage = "",
3136         },
3137         COMMAND_REGISTRATION_DONE
3138 };
3139
3140 static const struct command_registration kinetis_command_handler[] = {
3141         {
3142                 .name = "kinetis",
3143                 .mode = COMMAND_ANY,
3144                 .help = "Kinetis flash controller commands",
3145                 .usage = "",
3146                 .chain = kinetis_exec_command_handlers,
3147         },
3148         COMMAND_REGISTRATION_DONE
3149 };
3150
3151
3152
3153 const struct flash_driver kinetis_flash = {
3154         .name = "kinetis",
3155         .commands = kinetis_command_handler,
3156         .flash_bank_command = kinetis_flash_bank_command,
3157         .erase = kinetis_erase,
3158         .protect = kinetis_protect,
3159         .write = kinetis_write,
3160         .read = default_flash_read,
3161         .probe = kinetis_probe,
3162         .auto_probe = kinetis_auto_probe,
3163         .erase_check = kinetis_blank_check,
3164         .protect_check = kinetis_protect_check,
3165         .info = kinetis_info,
3166         .free_driver_priv = kinetis_free_driver_priv,
3167 };