1 /***************************************************************************
2  *   Copyright (C) 2015 by Ivan Meleca                                     *
3  *   ivan@artekit.eu                                                       *
4  *                                                                         *
5  *   Modified from kinetis.c                                               *
6  *                                                                         *
7  *   Copyright (C) 2011 by Mathias Kuester                                 *
8  *   kesmtp@freenet.de                                                     *
9  *                                                                         *
10  *   Copyright (C) 2011 sleep(5) ltd                                       *
11  *   tomas@sleepfive.com                                                   *
12  *                                                                         *
13  *   Copyright (C) 2012 by Christopher D. Kilgour                          *
14  *   techie at whiterocker.com                                             *
15  *                                                                         *
16  *   Copyright (C) 2013 Nemui Trinomius                                    *
17  *   nemuisan_kawausogasuki@live.jp                                        *
18  *                                                                         *
19  *   Copyright (C) 2015 Tomas Vanek                                        *
20  *   vanekt@fbl.cz                                                         *
21  *                                                                         *
22  *   This program is free software; you can redistribute it and/or modify  *
23  *   it under the terms of the GNU General Public License as published by  *
24  *   the Free Software Foundation; either version 2 of the License, or     *
25  *   (at your option) any later version.                                   *
26  *                                                                         *
27  *   This program is distributed in the hope that it will be useful,       *
28  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
29  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
30  *   GNU General Public License for more details.                          *
31  *                                                                         *
32  *   You should have received a copy of the GNU General Public License     *
33  *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
34  ***************************************************************************/
35 
36 #ifdef HAVE_CONFIG_H
37 #include "config.h"
38 #endif
39 
40 #include "jtag/interface.h"
41 #include "imp.h"
42 #include <helper/binarybuffer.h>
43 #include <target/algorithm.h>
44 #include <target/armv7m.h>
45 #include <target/cortex_m.h>
46 
47 /* Addresses */
48 #define SIM_SRSID					0x40048000
49 #define ICS_C1						0x40064000
50 #define ICS_C2						0x40064001
51 #define ICS_C3						0x40064002
52 #define ICS_C4						0x40064003
53 #define ICS_S						0x40064004
54 #define SIM_BUSDIV					0x40048018
55 #define SIM_CLKDIV_KE06				0x40048024
56 #define SIM_CLKDIV_KE04_44_64_80	0x40048024
57 #define SIM_CLKDIV_KE04_16_20_24	0x4004801C
58 #define WDOG_CS1					0x40052000
59 
60 #define ICS_C2_BDIV_MASK			0xE0
61 #define ICS_C2_BDIV_SHIFT			5
62 #define ICS_C2_BDIV(x)				(((uint8_t)(((uint8_t)(x))<<ICS_C2_BDIV_SHIFT))&ICS_C2_BDIV_MASK)
63 #define ICS_S_LOCK_MASK				0x40
64 #define ICS_C4_SCFTRIM_MASK			0x1
65 #define SIM_CLKDIV_OUTDIV2_MASK		0x1000000
66 #define FTMRX_FCLKDIV_FDIV_MASK		0x3F
67 #define FTMRX_FCLKDIV_FDIV_SHIFT	0
68 #define FTMRX_FCLKDIV_FDIV(x)		(((uint8_t)(((uint8_t)(x))<<FTMRX_FCLKDIV_FDIV_SHIFT))&FTMRX_FCLKDIV_FDIV_MASK)
69 #define FTMRX_FCLKDIV_FDIVLCK_MASK	0x40
70 #define FTMRX_FCLKDIV_FDIVLCK_SHIFT	6
71 #define FTMRX_FCLKDIV_FDIVLD_MASK	0x80
72 #define FTMRX_FCLKDIV_FDIVLD_SHIFT	7
73 #define FTMRX_FSTAT_CCIF_MASK		0x80
74 #define FTMRX_FSTAT_MGSTAT0_MASK	0x01
75 #define FTMRX_FSTAT_MGSTAT1_MASK	0x02
76 
77 /* Commands */
78 #define FTMRX_CMD_ALLERASED			0x01
79 #define FTMRX_CMD_BLOCKERASED		0x02
80 #define FTMRX_CMD_SECTIONERASED		0x03
81 #define FTMRX_CMD_READONCE			0x04
82 #define FTMRX_CMD_PROGFLASH			0x06
83 #define FTMRX_CMD_PROGONCE			0x07
84 #define FTMRX_CMD_ERASEALL			0x08
85 #define FTMRX_CMD_ERASEBLOCK		0x09
86 #define FTMRX_CMD_ERASESECTOR		0x0A
87 #define FTMRX_CMD_UNSECURE			0x0B
88 #define FTMRX_CMD_VERIFYACCESS		0x0C
89 #define FTMRX_CMD_SETMARGINLVL		0x0D
90 #define FTMRX_CMD_SETFACTORYLVL		0x0E
91 #define FTMRX_CMD_CONFIGNVM			0x0F
92 
93 /* Error codes */
94 #define FTMRX_ERROR_ACCERR			0x20
95 #define FTMRX_ERROR_FPVIOL			0x10
96 
97 #define KINETIS_KE_SRSID_FAMID(x)		((x >> 28) & 0x0F)
98 #define KINETIS_KE_SRSID_SUBFAMID(x)	((x >> 24) & 0x0F)
99 #define KINETIS_KE_SRSID_PINCOUNT(x)	((x >> 16) & 0x0F)
100 
101 #define KINETIS_KE_SRSID_KEX2	0x02
102 #define KINETIS_KE_SRSID_KEX4	0x04
103 #define KINETIS_KE_SRSID_KEX6	0x06
104 
105 struct kinetis_ke_flash_bank {
106 	uint32_t sector_size;
107 	uint32_t protection_size;
108 
109 	uint32_t sim_srsid;
110 	uint32_t ftmrx_fclkdiv_addr;
111 	uint32_t ftmrx_fccobix_addr;
112 	uint32_t ftmrx_fstat_addr;
113 	uint32_t ftmrx_fprot_addr;
114 	uint32_t ftmrx_fccobhi_addr;
115 	uint32_t ftmrx_fccoblo_addr;
116 };
117 
118 #define MDM_REG_STAT		0x00
119 #define MDM_REG_CTRL		0x04
120 #define MDM_REG_ID			0xfc
121 
122 #define MDM_STAT_FMEACK		(1<<0)
123 #define MDM_STAT_FREADY		(1<<1)
124 #define MDM_STAT_SYSSEC		(1<<2)
125 #define MDM_STAT_SYSRES		(1<<3)
126 #define MDM_STAT_FMEEN		(1<<5)
127 #define MDM_STAT_BACKDOOREN	(1<<6)
128 #define MDM_STAT_LPEN		(1<<7)
129 #define MDM_STAT_VLPEN		(1<<8)
130 #define MDM_STAT_LLSMODEXIT	(1<<9)
131 #define MDM_STAT_VLLSXMODEXIT	(1<<10)
132 #define MDM_STAT_CORE_HALTED	(1<<16)
133 #define MDM_STAT_CORE_SLEEPDEEP	(1<<17)
134 #define MDM_STAT_CORESLEEPING	(1<<18)
135 
136 #define MEM_CTRL_FMEIP		(1<<0)
137 #define MEM_CTRL_DBG_DIS	(1<<1)
138 #define MEM_CTRL_DBG_REQ	(1<<2)
139 #define MEM_CTRL_SYS_RES_REQ	(1<<3)
140 #define MEM_CTRL_CORE_HOLD_RES	(1<<4)
141 #define MEM_CTRL_VLLSX_DBG_REQ	(1<<5)
142 #define MEM_CTRL_VLLSX_DBG_ACK	(1<<6)
143 #define MEM_CTRL_VLLSX_STAT_ACK	(1<<7)
144 
145 #define MDM_ACCESS_TIMEOUT	3000 /* iterations */
146 
kinetis_ke_mdm_write_register(struct adiv5_dap * dap,unsigned reg,uint32_t value)147 static int kinetis_ke_mdm_write_register(struct adiv5_dap *dap, unsigned reg, uint32_t value)
148 {
149 	int retval;
150 	LOG_DEBUG("MDM_REG[0x%02x] <- %08" PRIX32, reg, value);
151 
152 	retval = dap_queue_ap_write(dap_ap(dap, 1), reg, value);
153 	if (retval != ERROR_OK) {
154 		LOG_DEBUG("MDM: failed to queue a write request");
155 		return retval;
156 	}
157 
158 	retval = dap_run(dap);
159 	if (retval != ERROR_OK) {
160 		LOG_DEBUG("MDM: dap_run failed");
161 		return retval;
162 	}
163 
164 	return ERROR_OK;
165 }
166 
kinetis_ke_mdm_read_register(struct adiv5_dap * dap,unsigned reg,uint32_t * result)167 static int kinetis_ke_mdm_read_register(struct adiv5_dap *dap, unsigned reg, uint32_t *result)
168 {
169 	int retval;
170 	retval = dap_queue_ap_read(dap_ap(dap, 1), reg, result);
171 	if (retval != ERROR_OK) {
172 		LOG_DEBUG("MDM: failed to queue a read request");
173 		return retval;
174 	}
175 
176 	retval = dap_run(dap);
177 	if (retval != ERROR_OK) {
178 		LOG_DEBUG("MDM: dap_run failed");
179 		return retval;
180 	}
181 
182 	LOG_DEBUG("MDM_REG[0x%02x]: %08" PRIX32, reg, *result);
183 	return ERROR_OK;
184 }
185 
kinetis_ke_mdm_poll_register(struct adiv5_dap * dap,unsigned reg,uint32_t mask,uint32_t value)186 static int kinetis_ke_mdm_poll_register(struct adiv5_dap *dap, unsigned reg, uint32_t mask, uint32_t value)
187 {
188 	uint32_t val;
189 	int retval;
190 	int timeout = MDM_ACCESS_TIMEOUT;
191 
192 	do {
193 		retval = kinetis_ke_mdm_read_register(dap, reg, &val);
194 		if (retval != ERROR_OK || (val & mask) == value)
195 			return retval;
196 
197 		alive_sleep(1);
198 	} while (timeout--);
199 
200 	LOG_DEBUG("MDM: polling timed out");
201 	return ERROR_FAIL;
202 }
203 
kinetis_ke_prepare_flash(struct flash_bank * bank)204 static int kinetis_ke_prepare_flash(struct flash_bank *bank)
205 {
206 	struct target *target = bank->target;
207 	struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
208 	uint8_t c2, c3, c4, s = 0;
209 	uint16_t trim_value = 0;
210 	uint16_t timeout = 0;
211 	uint32_t bus_clock = 0;
212 	uint32_t bus_reg_val = 0;
213 	uint32_t bus_reg_addr = 0;
214 	uint32_t flash_clk_div;
215 	uint8_t fclkdiv;
216 	int result;
217 
218 	/*
219 	 * The RM states that the flash clock has to be set to 1MHz for writing and
220 	 * erasing operations (otherwise it can damage the flash).
221 	 * This function configures the entire clock tree to make sure we
222 	 * run at the specified clock. We'll set FEI mode running from the ~32KHz
223 	 * internal clock. So we need to:
224 	 * - Trim internal clock.
225 	 * - Configure the divider for ICSOUTCLK (ICS module).
226 	 * - Configure the divider to get a bus clock (SIM module).
227 	 * - Configure the flash clock that depends on the bus clock.
228 	 *
229 	 * For MKE02_40 and MKE02_20 we set ICSOUTCLK = 20MHz and bus clock = 20MHz.
230 	 * For MKE04 and MKE06 we run at ICSOUTCLK = 48MHz and bus clock = 24MHz.
231 	 */
232 
233 	/*
234 	 * Trim internal clock
235 	 */
236 	switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
237 
238 		case KINETIS_KE_SRSID_KEX2:
239 			/* Both KE02_20 and KE02_40 should get the same trim value */
240 			trim_value = 0x4C;
241 			break;
242 
243 		case KINETIS_KE_SRSID_KEX4:
244 			trim_value = 0x54;
245 			break;
246 
247 		case KINETIS_KE_SRSID_KEX6:
248 			trim_value = 0x58;
249 			break;
250 	}
251 
252 	result = target_read_u8(target, ICS_C4, &c4);
253 	if (result != ERROR_OK)
254 		return result;
255 
256 	c3 = trim_value;
257 	c4 = (c4 & ~(ICS_C4_SCFTRIM_MASK)) | ((trim_value >> 8) & 0x01);
258 
259 	result = target_write_u8(target, ICS_C3, c3);
260 	if (result != ERROR_OK)
261 		return result;
262 
263 	result = target_write_u8(target, ICS_C4, c4);
264 	if (result != ERROR_OK)
265 		return result;
266 
267 	result = target_read_u8(target, ICS_S, &s);
268 	if (result != ERROR_OK)
269 		return result;
270 
271 	/* Wait */
272 	while (!(s & ICS_S_LOCK_MASK)) {
273 
274 		if (timeout <= 1000) {
275 			timeout++;
276 			alive_sleep(1);
277 		} else {
278 			return ERROR_FAIL;
279 		}
280 
281 		result = target_read_u8(target, ICS_S, &s);
282 		if (result != ERROR_OK)
283 			return result;
284 	}
285 
286 	/* ... trim done ... */
287 
288 	/*
289 	 * Configure SIM (bus clock)
290 	 */
291 	switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
292 
293 		/* KE02 sub-family operates on SIM_BUSDIV */
294 		case KINETIS_KE_SRSID_KEX2:
295 			bus_reg_val = 0;
296 			bus_reg_addr = SIM_BUSDIV;
297 			bus_clock = 20000000;
298 			break;
299 
300 		/* KE04 and KE06 sub-family operates on SIM_CLKDIV
301 		 * Clocks are divided by:
302 		 * DIV1 = core clock = 48MHz
303 		 * DIV2 = bus clock = 24Mhz
304 		 * DIV3 = timer clocks
305 		 * So we need to configure SIM_CLKDIV, DIV1 and DIV2 value
306 		 */
307 		case KINETIS_KE_SRSID_KEX4:
308 			/* KE04 devices have the SIM_CLKDIV register at a different offset
309 			 * depending on the pin count. */
310 			switch (KINETIS_KE_SRSID_PINCOUNT(kinfo->sim_srsid)) {
311 
312 				/* 16, 20 and 24 pins */
313 				case 1:
314 				case 2:
315 				case 3:
316 					bus_reg_addr = SIM_CLKDIV_KE04_16_20_24;
317 					break;
318 
319 				/* 44, 64 and 80 pins */
320 				case 5:
321 				case 7:
322 				case 8:
323 					bus_reg_addr = SIM_CLKDIV_KE04_44_64_80;
324 					break;
325 
326 				default:
327 					LOG_ERROR("KE04 - Unknown pin count");
328 					return ERROR_FAIL;
329 			}
330 
331 			bus_reg_val = SIM_CLKDIV_OUTDIV2_MASK;
332 			bus_clock = 24000000;
333 			break;
334 
335 		case KINETIS_KE_SRSID_KEX6:
336 			bus_reg_val = SIM_CLKDIV_OUTDIV2_MASK;
337 			bus_reg_addr = SIM_CLKDIV_KE06;
338 			bus_clock = 24000000;
339 			break;
340 	}
341 
342 	result = target_write_u32(target, bus_reg_addr, bus_reg_val);
343 	if (result != ERROR_OK)
344 		return result;
345 
346 	/*
347 	 * Configure ICS to FEI (internal source)
348 	 */
349 	result = target_read_u8(target, ICS_C2, &c2);
350 	if (result != ERROR_OK)
351 		return result;
352 
353 	c2 &= ~ICS_C2_BDIV_MASK;
354 
355 	switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
356 
357 		case KINETIS_KE_SRSID_KEX2:
358 			/* Note: since there are two KE02 types, the KE02_40 @ 40MHz and the
359 			 * KE02_20 @ 20MHz, we divide here the ~40MHz ICSFLLCLK down to 20MHz,
360 			 * for compatibility.
361 			 */
362 			c2 |= ICS_C2_BDIV(1);
363 			break;
364 
365 		case KINETIS_KE_SRSID_KEX4:
366 		case KINETIS_KE_SRSID_KEX6:
367 			/* For KE04 and KE06, the ICSFLLCLK can be 48MHz. */
368 			c2 |= ICS_C2_BDIV(0);
369 			break;
370 	}
371 
372 	result = target_write_u8(target, ICS_C2, c2);
373 	if (result != ERROR_OK)
374 		return result;
375 
376 	/* Internal clock as reference (IREFS = 1) */
377 	result = target_write_u8(target, ICS_C1, 4);
378 	if (result != ERROR_OK)
379 		return result;
380 
381 	/* Wait for FLL to lock */
382 	result = target_read_u8(target, ICS_S, &s);
383 	if (result != ERROR_OK)
384 		return result;
385 
386 	while (!(s & ICS_S_LOCK_MASK)) {
387 
388 		if (timeout <= 1000) {
389 			timeout++;
390 			alive_sleep(1);
391 		} else {
392 			return ERROR_FLASH_OPERATION_FAILED;
393 		}
394 
395 		result = target_read_u8(target, ICS_S, &s);
396 		if (result != ERROR_OK)
397 			return result;
398 	}
399 
400 	/*
401 	 * Configure flash clock to 1MHz.
402 	 */
403 	flash_clk_div = bus_clock / 1000000L - 1;
404 
405 	/* Check if the FCLKDIV register is locked */
406 	result = target_read_u8(target, kinfo->ftmrx_fclkdiv_addr, &fclkdiv);
407 	if (result != ERROR_OK)
408 		return result;
409 
410 	if (!(fclkdiv & FTMRX_FCLKDIV_FDIVLCK_MASK)) {
411 		/* Unlocked. Check if the register was configured, and if so, if it has the right value */
412 		if ((fclkdiv & FTMRX_FCLKDIV_FDIVLD_MASK) &&
413 			((fclkdiv & FTMRX_FCLKDIV_FDIV_MASK) != FTMRX_FCLKDIV_FDIV(flash_clk_div))) {
414 			LOG_WARNING("Flash clock was already set and contains an invalid value.");
415 			LOG_WARNING("Please reset the target.");
416 			return ERROR_FAIL;
417 		}
418 
419 		/* Finally, configure the flash clock */
420 		fclkdiv = (fclkdiv & ~(FTMRX_FCLKDIV_FDIV_MASK)) | FTMRX_FCLKDIV_FDIV(flash_clk_div);
421 		result = target_write_u8(target, kinfo->ftmrx_fclkdiv_addr, fclkdiv);
422 		if (result != ERROR_OK)
423 			return result;
424 	} else {
425 		/* Locked. Check if the current value is correct. */
426 		if ((fclkdiv & FTMRX_FCLKDIV_FDIV_MASK) != FTMRX_FCLKDIV_FDIV(flash_clk_div)) {
427 			LOG_WARNING("Flash clock register is locked and contains an invalid value.");
428 			LOG_WARNING("Please reset the target.");
429 			return ERROR_FAIL;
430 		}
431 	}
432 
433 	LOG_INFO("Flash clock ready");
434 	return ERROR_OK;
435 }
436 
kinetis_ke_stop_watchdog(struct target * target)437 static int kinetis_ke_stop_watchdog(struct target *target)
438 {
439 	struct working_area *watchdog_algorithm;
440 	struct armv7m_algorithm armv7m_info;
441 	int retval;
442 	uint8_t cs1;
443 
444 	static const uint8_t watchdog_code[] = {
445 #include "../../../contrib/loaders/flash/kinetis_ke/kinetis_ke_watchdog.inc"
446 	};
447 
448 	if (target->state != TARGET_HALTED) {
449 		LOG_ERROR("Target not halted");
450 		return ERROR_TARGET_NOT_HALTED;
451 	}
452 
453 	/* Check if the watchdog is enabled */
454 	retval = target_read_u8(target, WDOG_CS1, &cs1);
455 	if (retval != ERROR_OK)
456 		return retval;
457 
458 	if (!(cs1 & 0x80)) {
459 		/* Already stopped */
460 		return ERROR_OK;
461 	}
462 
463 	/* allocate working area with watchdog code */
464 	if (target_alloc_working_area(target, sizeof(watchdog_code), &watchdog_algorithm) != ERROR_OK) {
465 		LOG_WARNING("No working area available for watchdog algorithm");
466 		return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
467 	}
468 
469 	retval = target_write_buffer(target, watchdog_algorithm->address,
470 			sizeof(watchdog_code), watchdog_code);
471 	if (retval != ERROR_OK)
472 		return retval;
473 
474 	armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
475 	armv7m_info.core_mode = ARM_MODE_THREAD;
476 
477 	retval = target_run_algorithm(target, 0, NULL, 0, NULL,
478 			watchdog_algorithm->address, 0, 100000, &armv7m_info);
479 	if (retval != ERROR_OK) {
480 		LOG_ERROR("Error executing Kinetis KE watchdog algorithm");
481 	} else {
482 		LOG_INFO("Watchdog stopped");
483 	}
484 
485 	target_free_working_area(target, watchdog_algorithm);
486 
487 	return retval;
488 }
489 
COMMAND_HANDLER(kinetis_ke_disable_wdog_handler)490 COMMAND_HANDLER(kinetis_ke_disable_wdog_handler)
491 {
492 	struct target *target = get_current_target(CMD_CTX);
493 
494 	if (CMD_ARGC > 0)
495 		return ERROR_COMMAND_SYNTAX_ERROR;
496 
497 	return kinetis_ke_stop_watchdog(target);
498 }
499 
COMMAND_HANDLER(kinetis_ke_mdm_mass_erase)500 COMMAND_HANDLER(kinetis_ke_mdm_mass_erase)
501 {
502 	struct target *target = get_current_target(CMD_CTX);
503 	struct cortex_m_common *cortex_m = target_to_cm(target);
504 	struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
505 
506 	if (!dap) {
507 		LOG_ERROR("Cannot perform mass erase with a high-level adapter");
508 		return ERROR_FAIL;
509 	}
510 
511 	int retval;
512 
513 	/* According to chapter 18.3.7.2 of the KE02 reference manual */
514 
515 	/* assert SRST */
516 	if (jtag_get_reset_config() & RESET_HAS_SRST)
517 		adapter_assert_reset();
518 
519 	/*
520 	 * 1. Reset the device by asserting RESET pin or DAP_CTRL[3]
521 	 */
522 	retval = kinetis_ke_mdm_write_register(dap, MDM_REG_CTRL, MEM_CTRL_SYS_RES_REQ);
523 	if (retval != ERROR_OK)
524 		return retval;
525 
526 	/*
527 	 * ... Read the MDM-AP status register until the Flash Ready bit sets...
528 	 */
529 	retval = kinetis_ke_mdm_poll_register(dap, MDM_REG_STAT,
530 					   MDM_STAT_FREADY | MDM_STAT_SYSRES,
531 					   MDM_STAT_FREADY);
532 	if (retval != ERROR_OK) {
533 		LOG_ERROR("MDM : flash ready timeout");
534 		return retval;
535 	}
536 
537 	/*
538 	 * 2. Set DAP_CTRL[0] bit to invoke debug mass erase via SWD
539 	 * 3. Release reset by deasserting RESET pin or DAP_CTRL[3] bit via SWD.
540 	 */
541 	retval = kinetis_ke_mdm_write_register(dap, MDM_REG_CTRL, MEM_CTRL_FMEIP);
542 	if (retval != ERROR_OK)
543 		return retval;
544 
545 	/* As a sanity check make sure that device started mass erase procedure */
546 	retval = kinetis_ke_mdm_poll_register(dap, MDM_REG_STAT,
547 					   MDM_STAT_FMEACK, MDM_STAT_FMEACK);
548 	if (retval != ERROR_OK)
549 		return retval;
550 
551 	/*
552 	 * 4. Wait till DAP_CTRL[0] bit is cleared (after mass erase completes,
553 	 * DAP_CTRL[0] bit is cleared automatically).
554 	 */
555 	retval = kinetis_ke_mdm_poll_register(dap, MDM_REG_CTRL,
556 					   MEM_CTRL_FMEIP,
557 					   0);
558 	if (retval != ERROR_OK)
559 		return retval;
560 
561 	if (jtag_get_reset_config() & RESET_HAS_SRST)
562 		adapter_deassert_reset();
563 
564 	return ERROR_OK;
565 }
566 
567 static const uint32_t kinetis_ke_known_mdm_ids[] = {
568 	0x001C0020,	/* Kinetis-L/M/V/E/KE Series */
569 };
570 
571 /*
572  * This function implements the procedure to connect to
573  * SWD/JTAG on Kinetis K and L series of devices as it is described in
574  * AN4835 "Production Flash Programming Best Practices for Kinetis K-
575  * and L-series MCUs" Section 4.1.1
576  */
COMMAND_HANDLER(kinetis_ke_check_flash_security_status)577 COMMAND_HANDLER(kinetis_ke_check_flash_security_status)
578 {
579 	struct target *target = get_current_target(CMD_CTX);
580 	struct cortex_m_common *cortex_m = target_to_cm(target);
581 	struct adiv5_dap *dap = cortex_m->armv7m.arm.dap;
582 
583 	if (!dap) {
584 		LOG_WARNING("Cannot check flash security status with a high-level adapter");
585 		return ERROR_OK;
586 	}
587 
588 	uint32_t val;
589 	int retval;
590 
591 	/*
592 	 * ... The MDM-AP ID register can be read to verify that the
593 	 * connection is working correctly...
594 	 */
595 	retval = kinetis_ke_mdm_read_register(dap, MDM_REG_ID, &val);
596 	if (retval != ERROR_OK) {
597 		LOG_ERROR("MDM: failed to read ID register");
598 		goto fail;
599 	}
600 
601 	bool found = false;
602 	for (size_t i = 0; i < ARRAY_SIZE(kinetis_ke_known_mdm_ids); i++) {
603 		if (val == kinetis_ke_known_mdm_ids[i]) {
604 			found = true;
605 			break;
606 		}
607 	}
608 
609 	if (!found)
610 		LOG_WARNING("MDM: unknown ID %08" PRIX32, val);
611 
612 	/*
613 	 * ... Read the MDM-AP status register until the Flash Ready bit sets...
614 	 */
615 	retval = kinetis_ke_mdm_poll_register(dap, MDM_REG_STAT,
616 					   MDM_STAT_FREADY,
617 					   MDM_STAT_FREADY);
618 	if (retval != ERROR_OK) {
619 		LOG_ERROR("MDM: flash ready timeout");
620 		goto fail;
621 	}
622 
623 	/*
624 	 * ... Read the System Security bit to determine if security is enabled.
625 	 * If System Security = 0, then proceed. If System Security = 1, then
626 	 * communication with the internals of the processor, including the
627 	 * flash, will not be possible without issuing a mass erase command or
628 	 * unsecuring the part through other means (backdoor key unlock)...
629 	 */
630 	retval = kinetis_ke_mdm_read_register(dap, MDM_REG_STAT, &val);
631 	if (retval != ERROR_OK) {
632 		LOG_ERROR("MDM: failed to read MDM_REG_STAT");
633 		goto fail;
634 	}
635 
636 	if (val & MDM_STAT_SYSSEC) {
637 		jtag_poll_set_enabled(false);
638 
639 		LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
640 		LOG_WARNING("****                                                          ****");
641 		LOG_WARNING("**** Your Kinetis MCU is in secured state, which means that,  ****");
642 		LOG_WARNING("**** with exception for very basic communication, JTAG/SWD    ****");
643 		LOG_WARNING("**** interface will NOT work. In order to restore its         ****");
644 		LOG_WARNING("**** functionality please issue 'kinetis_ke mdm mass_erase'   ****");
645 		LOG_WARNING("**** command, power cycle the MCU and restart OpenOCD.        ****");
646 		LOG_WARNING("****                                                          ****");
647 		LOG_WARNING("*********** ATTENTION! ATTENTION! ATTENTION! ATTENTION! **********");
648 	} else {
649 		LOG_INFO("MDM: Chip is unsecured. Continuing.");
650 		jtag_poll_set_enabled(true);
651 	}
652 
653 	return ERROR_OK;
654 
655 fail:
656 	LOG_ERROR("MDM: Failed to check security status of the MCU. Cannot proceed further");
657 	jtag_poll_set_enabled(false);
658 	return retval;
659 }
660 
FLASH_BANK_COMMAND_HANDLER(kinetis_ke_flash_bank_command)661 FLASH_BANK_COMMAND_HANDLER(kinetis_ke_flash_bank_command)
662 {
663 	struct kinetis_ke_flash_bank *bank_info;
664 
665 	if (CMD_ARGC < 6)
666 		return ERROR_COMMAND_SYNTAX_ERROR;
667 
668 	LOG_INFO("add flash_bank kinetis_ke %s", bank->name);
669 
670 	bank_info = malloc(sizeof(struct kinetis_ke_flash_bank));
671 
672 	memset(bank_info, 0, sizeof(struct kinetis_ke_flash_bank));
673 
674 	bank->driver_priv = bank_info;
675 
676 	return ERROR_OK;
677 }
678 
679 /* Kinetis Program-LongWord Microcodes */
680 static uint8_t kinetis_ke_flash_write_code[] = {
681 #include "../../../contrib/loaders/flash/kinetis_ke/kinetis_ke_flash.inc"
682 };
683 
kinetis_ke_write_words(struct flash_bank * bank,const uint8_t * buffer,uint32_t offset,uint32_t words)684 static int kinetis_ke_write_words(struct flash_bank *bank, const uint8_t *buffer,
685 								uint32_t offset, uint32_t words)
686 {
687 	struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
688 	struct target *target = bank->target;
689 	uint32_t ram_buffer_size = 512 + 16;
690 	struct working_area *write_algorithm;
691 	struct working_area *source;
692 	uint32_t address = bank->base + offset;
693 	struct reg_param reg_params[4];
694 	struct armv7m_algorithm armv7m_info;
695 	int retval = ERROR_OK;
696 	uint32_t flash_code_size;
697 
698 	LOG_INFO("Kinetis KE: FLASH Write ...");
699 
700 	/* allocate working area with flash programming code */
701 	if (target_alloc_working_area(target, sizeof(kinetis_ke_flash_write_code),
702 			&write_algorithm) != ERROR_OK) {
703 		LOG_WARNING("no working area available, can't do block memory writes");
704 		return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
705 	}
706 
707 	/* Patch the FTMRx registers addresses */
708 	flash_code_size = sizeof(kinetis_ke_flash_write_code);
709 	buf_set_u32(&kinetis_ke_flash_write_code[flash_code_size-16], 0, 32, kinfo->ftmrx_fstat_addr);
710 	buf_set_u32(&kinetis_ke_flash_write_code[flash_code_size-12], 0, 32, kinfo->ftmrx_fccobix_addr);
711 	buf_set_u32(&kinetis_ke_flash_write_code[flash_code_size-8], 0, 32, kinfo->ftmrx_fccobhi_addr);
712 	buf_set_u32(&kinetis_ke_flash_write_code[flash_code_size-4], 0, 32, kinfo->ftmrx_fccoblo_addr);
713 
714 	retval = target_write_buffer(target, write_algorithm->address,
715 		sizeof(kinetis_ke_flash_write_code), kinetis_ke_flash_write_code);
716 	if (retval != ERROR_OK)
717 		return retval;
718 
719 	/* memory buffer */
720 	if (target_alloc_working_area(target, ram_buffer_size, &source) != ERROR_OK) {
721 		/* free working area, write algorithm already allocated */
722 		target_free_working_area(target, write_algorithm);
723 
724 		LOG_WARNING("No large enough working area available, can't do block memory writes");
725 		return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;
726 	}
727 
728 	armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
729 	armv7m_info.core_mode = ARM_MODE_THREAD;
730 
731 	init_reg_param(&reg_params[0], "r0", 32, PARAM_IN_OUT);
732 	init_reg_param(&reg_params[1], "r1", 32, PARAM_OUT);
733 	init_reg_param(&reg_params[2], "r2", 32, PARAM_OUT);
734 	init_reg_param(&reg_params[3], "r3", 32, PARAM_OUT);
735 
736 	buf_set_u32(reg_params[0].value, 0, 32, address);
737 	buf_set_u32(reg_params[1].value, 0, 32, words);
738 	buf_set_u32(reg_params[2].value, 0, 32, source->address);
739 	buf_set_u32(reg_params[3].value, 0, 32, source->address + source->size);
740 
741 	retval = target_run_flash_async_algorithm(target, buffer, words, 4,
742 			0, NULL,
743 			4, reg_params,
744 			source->address, source->size,
745 			write_algorithm->address, 0,
746 			&armv7m_info);
747 
748 	if (retval == ERROR_FLASH_OPERATION_FAILED) {
749 		if (buf_get_u32(reg_params[0].value, 0, 32) & FTMRX_ERROR_ACCERR)
750 			LOG_ERROR("flash access error");
751 
752 		if (buf_get_u32(reg_params[0].value, 0, 32) & FTMRX_ERROR_FPVIOL)
753 			LOG_ERROR("flash protection violation");
754 	}
755 
756 	target_free_working_area(target, source);
757 	target_free_working_area(target, write_algorithm);
758 
759 	destroy_reg_param(&reg_params[0]);
760 	destroy_reg_param(&reg_params[1]);
761 	destroy_reg_param(&reg_params[2]);
762 	destroy_reg_param(&reg_params[3]);
763 
764 	return retval;
765 }
766 
kinetis_ke_protect(struct flash_bank * bank,int set,unsigned int first,unsigned int last)767 static int kinetis_ke_protect(struct flash_bank *bank, int set,
768 		unsigned int first, unsigned int last)
769 {
770 	LOG_WARNING("kinetis_ke_protect not supported yet");
771 	/* FIXME: TODO */
772 
773 	if (bank->target->state != TARGET_HALTED) {
774 		LOG_ERROR("Target not halted");
775 		return ERROR_TARGET_NOT_HALTED;
776 	}
777 
778 	return ERROR_FLASH_BANK_INVALID;
779 }
780 
kinetis_ke_protect_check(struct flash_bank * bank)781 static int kinetis_ke_protect_check(struct flash_bank *bank)
782 {
783 	struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
784 
785 	if (bank->target->state != TARGET_HALTED) {
786 		LOG_ERROR("Target not halted");
787 		return ERROR_TARGET_NOT_HALTED;
788 	}
789 
790 	int result;
791 	uint8_t fprot;
792 	uint8_t fpopen, fpldis, fphdis;
793 	uint8_t fphs, fpls;
794 	uint32_t lprot_size = 0, hprot_size = 0;
795 	uint32_t lprot_to = 0, hprot_from = 0;
796 
797 	/* read protection register */
798 	result = target_read_u8(bank->target, kinfo->ftmrx_fprot_addr, &fprot);
799 
800 	if (result != ERROR_OK)
801 		return result;
802 
803 	fpopen = fprot & 0x80;
804 	fpldis = fprot & 0x04;
805 	fphdis = fprot & 0x20;
806 	fphs = (fprot >> 3) & 0x03;
807 	fpls = fprot & 0x03;
808 
809 	/* Fully unprotected? */
810 	if (fpopen && fpldis && fphdis) {
811 		LOG_WARNING("No flash protection found.");
812 
813 		for (unsigned int i = 0; i < bank->num_sectors; i++)
814 			bank->sectors[i].is_protected = 0;
815 
816 		kinfo->protection_size = 0;
817 	} else {
818 		LOG_WARNING("Flash protected. FPOPEN=%i FPLDIS=%i FPHDIS=%i FPLS=%i FPHS=%i",
819 					fpopen ? 1 : 0, fpldis ? 1 : 0, fphdis ? 1 : 0, fpls, fphs);
820 
821 		/* Retrieve which region is protected and how much */
822 		if (fpopen) {
823 			if (fpldis == 0)
824 				lprot_size = (kinfo->sector_size * 4) << fpls;
825 
826 			if (fphdis == 0)
827 				hprot_size = (kinfo->sector_size * 2) << fphs;
828 		} else {
829 			if (fpldis == 1)
830 				lprot_size = (kinfo->sector_size * 4) << fpls;
831 
832 			if (fphdis == 1)
833 				hprot_size = (kinfo->sector_size * 2) << fphs;
834 		}
835 
836 		kinfo->protection_size = lprot_size + hprot_size;
837 
838 		/* lprot_to indicates up to where the lower region is protected */
839 		lprot_to = lprot_size / kinfo->sector_size;
840 
841 		/* hprot_from indicates from where the upper region is protected */
842 		hprot_from = (0x8000 - hprot_size) / kinfo->sector_size;
843 
844 		for (unsigned int i = 0; i < bank->num_sectors; i++) {
845 
846 			/* Check if the sector is in the lower region */
847 			if (bank->sectors[i].offset < 0x4000) {
848 				/* Compare the sector start address against lprot_to */
849 				if (lprot_to && (i < lprot_to))
850 					bank->sectors[i].is_protected = 1;
851 				else
852 					bank->sectors[i].is_protected = 0;
853 
854 			/* Check if the sector is between the lower and upper region
855 			 * OR after the upper region */
856 			} else if (bank->sectors[i].offset < 0x6000 || bank->sectors[i].offset >= 0x8000) {
857 				/* If fpopen is 1 then these regions are protected */
858 				if (fpopen)
859 					bank->sectors[i].is_protected = 0;
860 				else
861 					bank->sectors[i].is_protected = 1;
862 
863 			/* Check if the sector is in the upper region */
864 			} else if (bank->sectors[i].offset < 0x8000) {
865 				if (hprot_from && (i > hprot_from))
866 					bank->sectors[i].is_protected = 1;
867 				else
868 					bank->sectors[i].is_protected = 0;
869 			}
870 		}
871 	}
872 
873 	return ERROR_OK;
874 }
875 
kinetis_ke_ftmrx_command(struct flash_bank * bank,uint8_t count,uint8_t * FCCOBIX,uint8_t * FCCOBHI,uint8_t * FCCOBLO,uint8_t * fstat)876 static int kinetis_ke_ftmrx_command(struct flash_bank *bank, uint8_t count,
877 									uint8_t *FCCOBIX, uint8_t *FCCOBHI, uint8_t *FCCOBLO, uint8_t *fstat)
878 {
879 	uint8_t i;
880 	int result;
881 	struct target *target = bank->target;
882 	struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
883 	uint32_t timeout = 0;
884 
885 	/* Clear error flags */
886 	result = target_write_u8(target, kinfo->ftmrx_fstat_addr, 0x30);
887 	if (result != ERROR_OK)
888 		return result;
889 
890 	for (i = 0; i < count; i++)	{
891 		/* Write index */
892 		result = target_write_u8(target, kinfo->ftmrx_fccobix_addr, FCCOBIX[i]);
893 		if (result != ERROR_OK)
894 			return result;
895 
896 		/* Write high part */
897 		result = target_write_u8(target, kinfo->ftmrx_fccobhi_addr, FCCOBHI[i]);
898 		if (result != ERROR_OK)
899 			return result;
900 
901 		/* Write low part (that is not always required) */
902 		if (FCCOBLO) {
903 			result = target_write_u8(target, kinfo->ftmrx_fccoblo_addr, FCCOBLO[i]);
904 			if (result != ERROR_OK)
905 				return result;
906 		}
907 	}
908 
909 	/* Launch the command */
910 	result = target_write_u8(target, kinfo->ftmrx_fstat_addr, 0x80);
911 	if (result != ERROR_OK)
912 		return result;
913 
914 	/* Wait for it to finish */
915 	result = target_read_u8(target, kinfo->ftmrx_fstat_addr, fstat);
916 	if (result != ERROR_OK)
917 		return result;
918 
919 	while (!(*fstat & FTMRX_FSTAT_CCIF_MASK)) {
920 		if (timeout <= 1000) {
921 			timeout++;
922 			alive_sleep(1);
923 		} else {
924 			return ERROR_FLASH_OPERATION_FAILED;
925 		}
926 
927 		result = target_read_u8(target, kinfo->ftmrx_fstat_addr, fstat);
928 		if (result != ERROR_OK)
929 			return result;
930 	}
931 
932 	return ERROR_OK;
933 }
934 
COMMAND_HANDLER(kinetis_ke_securing_test)935 COMMAND_HANDLER(kinetis_ke_securing_test)
936 {
937 	int result;
938 	struct target *target = get_current_target(CMD_CTX);
939 	struct flash_bank *bank = NULL;
940 	uint32_t address;
941 
942 	uint8_t FCCOBIX[2], FCCOBHI[2], FCCOBLO[2], fstat;
943 
944 	result = get_flash_bank_by_addr(target, 0x00000000, true, &bank);
945 	if (result != ERROR_OK)
946 		return result;
947 
948 	assert(bank != NULL);
949 
950 	if (target->state != TARGET_HALTED) {
951 		LOG_ERROR("Target not halted");
952 		return ERROR_TARGET_NOT_HALTED;
953 	}
954 
955 	address = bank->base + 0x00000400;
956 
957 	FCCOBIX[0] = 0;
958 	FCCOBHI[0] = FTMRX_CMD_ERASESECTOR;
959 	FCCOBLO[0] = address >> 16;
960 
961 	FCCOBIX[1] = 1;
962 	FCCOBHI[1] = address >> 8;
963 	FCCOBLO[1] = address;
964 
965 	return kinetis_ke_ftmrx_command(bank, 2, FCCOBIX, FCCOBHI, FCCOBLO, &fstat);
966 }
967 
kinetis_ke_erase(struct flash_bank * bank,unsigned int first,unsigned int last)968 static int kinetis_ke_erase(struct flash_bank *bank, unsigned int first,
969 		unsigned int last)
970 {
971 	int result;
972 	uint8_t FCCOBIX[2], FCCOBHI[2], FCCOBLO[2], fstat;
973 	bool fcf_erased = false;
974 
975 	if (bank->target->state != TARGET_HALTED) {
976 		LOG_ERROR("Target not halted");
977 		return ERROR_TARGET_NOT_HALTED;
978 	}
979 
980 	if ((first > bank->num_sectors) || (last > bank->num_sectors))
981 		return ERROR_FLASH_OPERATION_FAILED;
982 
983 	result = kinetis_ke_prepare_flash(bank);
984 	if (result != ERROR_OK)
985 		return result;
986 
987 	for (unsigned int i = first; i <= last; i++) {
988 		FCCOBIX[0] = 0;
989 		FCCOBHI[0] = FTMRX_CMD_ERASESECTOR;
990 		FCCOBLO[0] = (bank->base + bank->sectors[i].offset) >> 16;
991 
992 		FCCOBIX[1] = 1;
993 		FCCOBHI[1] = (bank->base + bank->sectors[i].offset) >> 8;
994 		FCCOBLO[1] = (bank->base + bank->sectors[i].offset);
995 
996 		result = kinetis_ke_ftmrx_command(bank, 2, FCCOBIX, FCCOBHI, FCCOBLO, &fstat);
997 
998 		if (result != ERROR_OK)	{
999 			LOG_WARNING("erase sector %u failed", i);
1000 			return ERROR_FLASH_OPERATION_FAILED;
1001 		}
1002 
1003 		bank->sectors[i].is_erased = 1;
1004 
1005 		if (i == 2)
1006 			fcf_erased = true;
1007 	}
1008 
1009 	if (fcf_erased) {
1010 		LOG_WARNING
1011 			("flash configuration field erased, please reset the device");
1012 	}
1013 
1014 	return ERROR_OK;
1015 }
1016 
kinetis_ke_write(struct flash_bank * bank,const uint8_t * buffer,uint32_t offset,uint32_t count)1017 static int kinetis_ke_write(struct flash_bank *bank, const uint8_t *buffer,
1018 			 uint32_t offset, uint32_t count)
1019 {
1020 	int result;
1021 	uint8_t *new_buffer = NULL;
1022 	uint32_t words = count / 4;
1023 
1024 	if (bank->target->state != TARGET_HALTED) {
1025 		LOG_ERROR("Target not halted");
1026 		return ERROR_TARGET_NOT_HALTED;
1027 	}
1028 
1029 	if (offset > bank->size)
1030 		return ERROR_FLASH_BANK_INVALID;
1031 
1032 	if (offset & 0x3) {
1033 		LOG_WARNING("offset 0x%" PRIx32 " breaks the required alignment", offset);
1034 		return ERROR_FLASH_DST_BREAKS_ALIGNMENT;
1035 	}
1036 
1037 	result = kinetis_ke_stop_watchdog(bank->target);
1038 	if (result != ERROR_OK)
1039 			return result;
1040 
1041 	result = kinetis_ke_prepare_flash(bank);
1042 	if (result != ERROR_OK)
1043 		return result;
1044 
1045 	if (count & 0x3) {
1046 		uint32_t old_count = count;
1047 		count = (old_count | 3) + 1;
1048 		new_buffer = malloc(count);
1049 		if (new_buffer == NULL) {
1050 			LOG_ERROR("odd number of bytes to write and no memory "
1051 				"for padding buffer");
1052 			return ERROR_FAIL;
1053 		}
1054 
1055 		LOG_INFO("odd number of bytes to write (%" PRIu32 "), extending to %" PRIu32 " "
1056 			"and padding with 0xff", old_count, count);
1057 
1058 		memset(new_buffer, 0xff, count);
1059 		buffer = memcpy(new_buffer, buffer, old_count);
1060 		words++;
1061 	}
1062 
1063 	result = kinetis_ke_write_words(bank, buffer, offset, words);
1064 	free(new_buffer);
1065 
1066 	return result;
1067 }
1068 
kinetis_ke_probe(struct flash_bank * bank)1069 static int kinetis_ke_probe(struct flash_bank *bank)
1070 {
1071 	int result;
1072 	uint32_t offset = 0;
1073 	struct target *target = bank->target;
1074 	struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
1075 
1076 	result = target_read_u32(target, SIM_SRSID, &kinfo->sim_srsid);
1077 	if (result != ERROR_OK)
1078 		return result;
1079 
1080 	if (KINETIS_KE_SRSID_FAMID(kinfo->sim_srsid) != 0x00) {
1081 		LOG_ERROR("Unsupported KE family");
1082 		return ERROR_FLASH_OPER_UNSUPPORTED;
1083 	}
1084 
1085 	switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
1086 		case KINETIS_KE_SRSID_KEX2:
1087 			LOG_INFO("KE02 sub-family");
1088 			break;
1089 
1090 		case KINETIS_KE_SRSID_KEX4:
1091 			LOG_INFO("KE04 sub-family");
1092 			break;
1093 
1094 		case KINETIS_KE_SRSID_KEX6:
1095 			LOG_INFO("KE06 sub-family");
1096 			break;
1097 
1098 		default:
1099 			LOG_ERROR("Unsupported KE sub-family");
1100 			return ERROR_FLASH_OPER_UNSUPPORTED;
1101 	}
1102 
1103 	/* We can only retrieve the ke0x part, but there is no way to know
1104 	 * the flash size, so assume the maximum flash size for the entire
1105 	 * sub family.
1106 	 */
1107 	bank->base = 0x00000000;
1108 	kinfo->sector_size = 512;
1109 
1110 	switch (KINETIS_KE_SRSID_SUBFAMID(kinfo->sim_srsid)) {
1111 
1112 		case KINETIS_KE_SRSID_KEX2:
1113 			/* Max. 64KB */
1114 			bank->size = 0x00010000;
1115 			bank->num_sectors = 128;
1116 
1117 			/* KE02 uses the FTMRH flash controller,
1118 			 * and registers have a different offset from the
1119 			 * FTMRE flash controller. Sort this out here.
1120 			 */
1121 			kinfo->ftmrx_fclkdiv_addr = 0x40020000;
1122 			kinfo->ftmrx_fccobix_addr = 0x40020002;
1123 			kinfo->ftmrx_fstat_addr = 0x40020006;
1124 			kinfo->ftmrx_fprot_addr = 0x40020008;
1125 			kinfo->ftmrx_fccobhi_addr = 0x4002000A;
1126 			kinfo->ftmrx_fccoblo_addr = 0x4002000B;
1127 			break;
1128 
1129 		case KINETIS_KE_SRSID_KEX6:
1130 		case KINETIS_KE_SRSID_KEX4:
1131 			/* Max. 128KB */
1132 			bank->size = 0x00020000;
1133 			bank->num_sectors = 256;
1134 
1135 			/* KE04 and KE06 use the FTMRE flash controller,
1136 			 * and registers have a different offset from the
1137 			 * FTMRH flash controller. Sort this out here.
1138 			 */
1139 			kinfo->ftmrx_fclkdiv_addr = 0x40020003;
1140 			kinfo->ftmrx_fccobix_addr = 0x40020001;
1141 			kinfo->ftmrx_fstat_addr = 0x40020005;
1142 			kinfo->ftmrx_fprot_addr = 0x4002000B;
1143 			kinfo->ftmrx_fccobhi_addr = 0x40020009;
1144 			kinfo->ftmrx_fccoblo_addr = 0x40020008;
1145 			break;
1146 	}
1147 
1148 	free(bank->sectors);
1149 
1150 	assert(bank->num_sectors > 0);
1151 	bank->sectors = malloc(sizeof(struct flash_sector) * bank->num_sectors);
1152 
1153 	for (unsigned int i = 0; i < bank->num_sectors; i++) {
1154 		bank->sectors[i].offset = offset;
1155 		bank->sectors[i].size = kinfo->sector_size;
1156 		offset += kinfo->sector_size;
1157 		bank->sectors[i].is_erased = -1;
1158 		bank->sectors[i].is_protected = 1;
1159 	}
1160 
1161 	return ERROR_OK;
1162 }
1163 
kinetis_ke_auto_probe(struct flash_bank * bank)1164 static int kinetis_ke_auto_probe(struct flash_bank *bank)
1165 {
1166 	struct kinetis_ke_flash_bank *kinfo = bank->driver_priv;
1167 
1168 	if (kinfo->sim_srsid)
1169 		return ERROR_OK;
1170 
1171 	return kinetis_ke_probe(bank);
1172 }
1173 
kinetis_ke_info(struct flash_bank * bank,char * buf,int buf_size)1174 static int kinetis_ke_info(struct flash_bank *bank, char *buf, int buf_size)
1175 {
1176 	(void) snprintf(buf, buf_size,
1177 			"%s driver for flash bank %s at " TARGET_ADDR_FMT,
1178 			bank->driver->name,	bank->name, bank->base);
1179 
1180 	return ERROR_OK;
1181 }
1182 
kinetis_ke_blank_check(struct flash_bank * bank)1183 static int kinetis_ke_blank_check(struct flash_bank *bank)
1184 {
1185 	uint8_t FCCOBIX[3], FCCOBHI[3], FCCOBLO[3], fstat;
1186 	uint16_t longwords = 0;
1187 	int result;
1188 
1189 	if (bank->target->state != TARGET_HALTED) {
1190 		LOG_ERROR("Target not halted");
1191 		return ERROR_TARGET_NOT_HALTED;
1192 	}
1193 
1194 	result = kinetis_ke_prepare_flash(bank);
1195 	if (result != ERROR_OK)
1196 		return result;
1197 
1198 	/* check if whole bank is blank */
1199 	FCCOBIX[0] = 0;
1200 	FCCOBHI[0] = FTMRX_CMD_ALLERASED;
1201 
1202 	result = kinetis_ke_ftmrx_command(bank, 1, FCCOBIX, FCCOBHI, NULL, &fstat);
1203 
1204 	if (result != ERROR_OK)
1205 		return result;
1206 
1207 	if (fstat & (FTMRX_FSTAT_MGSTAT0_MASK | FTMRX_FSTAT_MGSTAT1_MASK)) {
1208 		/* the whole bank is not erased, check sector-by-sector */
1209 		for (unsigned int i = 0; i < bank->num_sectors; i++) {
1210 			FCCOBIX[0] = 0;
1211 			FCCOBHI[0] = FTMRX_CMD_SECTIONERASED;
1212 			FCCOBLO[0] = (bank->base + bank->sectors[i].offset) >> 16;
1213 
1214 			FCCOBIX[1] = 1;
1215 			FCCOBHI[1] = (bank->base + bank->sectors[i].offset) >> 8;
1216 			FCCOBLO[1] = (bank->base + bank->sectors[i].offset);
1217 
1218 			longwords = 128;
1219 
1220 			FCCOBIX[2] = 2;
1221 			FCCOBHI[2] = longwords >> 8;
1222 			FCCOBLO[2] = longwords;
1223 
1224 			result = kinetis_ke_ftmrx_command(bank, 3, FCCOBIX, FCCOBHI, FCCOBLO, &fstat);
1225 
1226 			if (result == ERROR_OK)	{
1227 				bank->sectors[i].is_erased = !(fstat & (FTMRX_FSTAT_MGSTAT0_MASK | FTMRX_FSTAT_MGSTAT1_MASK));
1228 			} else {
1229 				LOG_DEBUG("Ignoring error on PFlash sector blank-check");
1230 				bank->sectors[i].is_erased = -1;
1231 			}
1232 		}
1233 	} else {
1234 		/* the whole bank is erased, update all sectors */
1235 		for (unsigned int i = 0; i < bank->num_sectors; i++)
1236 			bank->sectors[i].is_erased = 1;
1237 	}
1238 
1239 	return ERROR_OK;
1240 }
1241 
1242 static const struct command_registration kinetis_ke_security_command_handlers[] = {
1243 	{
1244 		.name = "check_security",
1245 		.mode = COMMAND_EXEC,
1246 		.help = "",
1247 		.usage = "",
1248 		.handler = kinetis_ke_check_flash_security_status,
1249 	},
1250 	{
1251 		.name = "mass_erase",
1252 		.mode = COMMAND_EXEC,
1253 		.help = "",
1254 		.usage = "",
1255 		.handler = kinetis_ke_mdm_mass_erase,
1256 	},
1257 	{
1258 		.name = "test_securing",
1259 		.mode = COMMAND_EXEC,
1260 		.help = "",
1261 		.usage = "",
1262 		.handler = kinetis_ke_securing_test,
1263 	},
1264 	COMMAND_REGISTRATION_DONE
1265 };
1266 
1267 static const struct command_registration kinetis_ke_exec_command_handlers[] = {
1268 	{
1269 		.name = "mdm",
1270 		.mode = COMMAND_ANY,
1271 		.help = "",
1272 		.usage = "",
1273 		.chain = kinetis_ke_security_command_handlers,
1274 	},
1275 	{
1276 		.name = "disable_wdog",
1277 		.mode = COMMAND_EXEC,
1278 		.help = "Disable the watchdog timer",
1279 		.usage = "",
1280 		.handler = kinetis_ke_disable_wdog_handler,
1281 	},
1282 	COMMAND_REGISTRATION_DONE
1283 };
1284 
1285 static const struct command_registration kinetis_ke_command_handler[] = {
1286 	{
1287 		.name = "kinetis_ke",
1288 		.mode = COMMAND_ANY,
1289 		.help = "Kinetis KE NAND flash controller commands",
1290 		.usage = "",
1291 		.chain = kinetis_ke_exec_command_handlers,
1292 	},
1293 	COMMAND_REGISTRATION_DONE
1294 };
1295 
1296 const struct flash_driver kinetis_ke_flash = {
1297 	.name = "kinetis_ke",
1298 	.commands = kinetis_ke_command_handler,
1299 	.flash_bank_command = kinetis_ke_flash_bank_command,
1300 	.erase = kinetis_ke_erase,
1301 	.protect = kinetis_ke_protect,
1302 	.write = kinetis_ke_write,
1303 	.read = default_flash_read,
1304 	.probe = kinetis_ke_probe,
1305 	.auto_probe = kinetis_ke_auto_probe,
1306 	.erase_check = kinetis_ke_blank_check,
1307 	.protect_check = kinetis_ke_protect_check,
1308 	.info = kinetis_ke_info,
1309 	.free_driver_priv = default_flash_free_driver_priv,
1310 };
1311