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