1 /*
2  * Copyright (c) 2016 Linaro Limited
3  * Copyright 2024 NXP
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/kernel.h>
9 #include <zephyr/device.h>
10 #include <string.h>
11 #include <zephyr/drivers/flash.h>
12 #include <errno.h>
13 #include <zephyr/init.h>
14 #include <soc.h>
15 #include <zephyr/sys/barrier.h>
16 #include "flash_priv.h"
17 
18 #include "fsl_common.h"
19 
20 #define LOG_LEVEL CONFIG_FLASH_LOG_LEVEL
21 #include <zephyr/logging/log.h>
22 LOG_MODULE_REGISTER(flash_mcux);
23 
24 
25 #if DT_NODE_HAS_STATUS_OKAY(DT_INST(0, nxp_kinetis_ftfa))
26 #define DT_DRV_COMPAT nxp_kinetis_ftfa
27 #elif DT_NODE_HAS_STATUS_OKAY(DT_INST(0, nxp_kinetis_ftfe))
28 #define DT_DRV_COMPAT nxp_kinetis_ftfe
29 #elif DT_NODE_HAS_STATUS_OKAY(DT_INST(0, nxp_kinetis_ftfl))
30 #define DT_DRV_COMPAT nxp_kinetis_ftfl
31 #elif DT_NODE_HAS_STATUS_OKAY(DT_INST(0, nxp_iap_fmc55))
32 #define DT_DRV_COMPAT nxp_iap_fmc55
33 #define SOC_HAS_IAP 1
34 #elif DT_NODE_HAS_STATUS_OKAY(DT_INST(0, nxp_iap_fmc553))
35 #define DT_DRV_COMPAT nxp_iap_fmc553
36 #define SOC_HAS_IAP 1
37 #elif DT_NODE_HAS_STATUS_OKAY(DT_INST(0, nxp_msf1))
38 #define DT_DRV_COMPAT nxp_msf1
39 #define SOC_HAS_MSF1 1
40 #else
41 #error No matching compatible for soc_flash_mcux.c
42 #endif
43 
44 #if defined(SOC_HAS_IAP) && !defined(CONFIG_SOC_LPC55S36)
45 #include "fsl_iap.h"
46 #elif defined(CONFIG_SOC_MCXA156)
47 #include "fsl_romapi.h"
48 #define FLASH_Erase   FLASH_EraseSector
49 #define FLASH_Program FLASH_ProgramPhrase
50 #elif defined(CONFIG_MCUX_FLASH_K4_API)
51 #include "fsl_k4_flash.h"
52 #else
53 #include "fsl_flash.h"
54 #endif /* SOC_HAS_IAP && !CONFIG_SOC_LPC55S36*/
55 
56 #define SOC_NV_FLASH_NODE DT_INST(0, soc_nv_flash)
57 
58 #if defined(CONFIG_CHECK_BEFORE_READING) && !defined(CONFIG_SOC_LPC55S36)
59 #define FMC_STATUS_FAIL	FLASH_INT_CLR_ENABLE_FAIL_MASK
60 #define FMC_STATUS_ERR	FLASH_INT_CLR_ENABLE_ERR_MASK
61 #define FMC_STATUS_DONE	FLASH_INT_CLR_ENABLE_DONE_MASK
62 #define FMC_STATUS_ECC	FLASH_INT_CLR_ENABLE_ECC_ERR_MASK
63 
64 #define FMC_STATUS_FAILURES	\
65 	(FMC_STATUS_FAIL | FMC_STATUS_ERR | FMC_STATUS_ECC)
66 
67 #define FMC_CMD_BLANK_CHECK		5
68 #define FMC_CMD_MARGIN_CHECK	6
69 
70 /* Issue single command that uses an a start and stop address. */
get_cmd_status(uint32_t cmd,uint32_t addr,size_t len)71 static uint32_t get_cmd_status(uint32_t cmd, uint32_t addr, size_t len)
72 {
73 	FLASH_Type *p_fmc = (FLASH_Type *)DT_INST_REG_ADDR(0);
74 	uint32_t status;
75 
76 	/* issue low level command */
77 	p_fmc->INT_CLR_STATUS = 0xF;
78 	p_fmc->STARTA = (addr>>4) & 0x3FFFF;
79 	p_fmc->STOPA = ((addr+len-1)>>4) & 0x3FFFF;
80 	p_fmc->CMD = cmd;
81 	barrier_dsync_fence_full();
82 	barrier_isync_fence_full();
83 
84 	/* wait for command to be done */
85 	while (!(p_fmc->INT_STATUS & FMC_STATUS_DONE))
86 		;
87 
88 	/* get read status and then clear it */
89 	status = p_fmc->INT_STATUS;
90 	p_fmc->INT_CLR_STATUS = 0xF;
91 
92 	return status;
93 }
94 
95 /* This function prevents erroneous reading. Some ECC enabled devices will
96  * crash when reading an erased or wrongly programmed area.
97  */
is_area_readable(uint32_t addr,size_t len)98 static status_t is_area_readable(uint32_t addr, size_t len)
99 {
100 	uint32_t key;
101 	status_t status;
102 
103 	key = irq_lock();
104 
105 	/* Check if the are is correctly programmed and can be read. */
106 	status = get_cmd_status(FMC_CMD_MARGIN_CHECK, addr, len);
107 	if (status & FMC_STATUS_FAILURES) {
108 		/* If the area was erased, ECC errors are triggered on read. */
109 		status = get_cmd_status(FMC_CMD_BLANK_CHECK, addr, len);
110 		if (!(status & FMC_STATUS_FAIL)) {
111 			LOG_DBG("read request on erased addr:0x%08x size:%d",
112 				addr, len);
113 			irq_unlock(key);
114 			return -ENODATA;
115 		}
116 		LOG_DBG("read request error for addr:0x%08x size:%d",
117 			addr, len);
118 		irq_unlock(key);
119 		return -EIO;
120 	}
121 
122 	irq_unlock(key);
123 
124 	return 0;
125 }
126 #endif /* CONFIG_CHECK_BEFORE_READING && ! CONFIG_SOC_LPC55S36 */
127 
128 #define SOC_FLASH_NEED_CLEAR_CACHES 1
129 #ifdef CONFIG_SOC_SERIES_MCXW
clear_flash_caches(void)130 static void clear_flash_caches(void)
131 {
132 	volatile uint32_t *const smscm_ocmdr0 = (volatile uint32_t *)0x40015400;
133 	/* this bit clears the flash cache */
134 	*smscm_ocmdr0 |= BIT(8);
135 	volatile uint32_t *mcm_cpcr2 = (volatile uint32_t *)0xe0080034;
136 	/* this bit clears the code cache */
137 	*mcm_cpcr2 |= BIT(0);
138 }
139 #elif CONFIG_SOC_SERIES_MCXN
clear_flash_caches(void)140 static void clear_flash_caches(void)
141 {
142 	volatile uint32_t *const nvm_ctrl = (volatile uint32_t *)0x40000400;
143 	/* this bit clears the flash cache */
144 	*nvm_ctrl |= BIT(5);
145 	volatile uint32_t *const lpcac_ctrl = (volatile uint32_t *)0x40000824;
146 	/* this bit clears the code cache */
147 	*lpcac_ctrl |= BIT(1);
148 }
149 #else
150 #undef SOC_FLASH_NEED_CLEAR_CACHES
151 #define clear_flash_caches(...)
152 #endif
153 
154 struct flash_priv {
155 	flash_config_t config;
156 	/*
157 	 * HACK: flash write protection is managed in software.
158 	 */
159 	struct k_sem write_lock;
160 	uint32_t pflash_block_base;
161 };
162 
163 static const struct flash_parameters flash_mcux_parameters = {
164 #if DT_NODE_HAS_PROP(SOC_NV_FLASH_NODE, write_block_size)
165 	.write_block_size = DT_PROP(SOC_NV_FLASH_NODE, write_block_size),
166 #else
167 	.write_block_size = FSL_FEATURE_FLASH_PFLASH_BLOCK_WRITE_UNIT_SIZE,
168 #endif
169 	.erase_value = 0xff,
170 };
171 
172 /*
173  * Interrupt vectors could be executed from flash hence the need for locking.
174  * The underlying MCUX driver takes care of copying the functions to SRAM.
175  *
176  * For more information, see the application note below on Read-While-Write
177  * http://cache.freescale.com/files/32bit/doc/app_note/AN4695.pdf
178  *
179  */
180 
flash_mcux_erase(const struct device * dev,off_t offset,size_t len)181 static int flash_mcux_erase(const struct device *dev, off_t offset,
182 			    size_t len)
183 {
184 	struct flash_priv *priv = dev->data;
185 	uint32_t addr;
186 	status_t rc;
187 	unsigned int key;
188 
189 	if (k_sem_take(&priv->write_lock, K_FOREVER)) {
190 		return -EACCES;
191 	}
192 
193 	addr = offset + priv->pflash_block_base;
194 
195 	key = irq_lock();
196 	rc = FLASH_Erase(&priv->config,
197 #if CONFIG_MCUX_FLASH_K4_API
198 			(FMU_Type *) DT_INST_REG_ADDR(0),
199 #endif
200 			addr, len, kFLASH_ApiEraseKey);
201 
202 	if (IS_ENABLED(SOC_FLASH_NEED_CLEAR_CACHES)) {
203 		clear_flash_caches();
204 	}
205 
206 	irq_unlock(key);
207 
208 	k_sem_give(&priv->write_lock);
209 
210 	return (rc == kStatus_Success) ? 0 : -EINVAL;
211 }
212 
213 
214 /*
215  * @brief Read a flash memory area.
216  *
217  * @param dev Device struct
218  * @param offset The address's offset
219  * @param data The buffer to store or read the value
220  * @param length The size of the buffer
221  * @return 	0 on success,
222  * 			-EIO for erroneous area
223  */
flash_mcux_read(const struct device * dev,off_t offset,void * data,size_t len)224 static int flash_mcux_read(const struct device *dev, off_t offset,
225 				void *data, size_t len)
226 {
227 	struct flash_priv *priv = dev->data;
228 	uint32_t addr;
229 	status_t rc = 0;
230 
231 	/*
232 	 * The MCUX supports different flash chips whose valid ranges are
233 	 * hidden below the API: until the API export these ranges, we can not
234 	 * do any generic validation
235 	 */
236 	addr = offset + priv->pflash_block_base;
237 
238 #ifdef CONFIG_CHECK_BEFORE_READING
239 	/*
240 	 * Ensure the area is readable, since a direct access may cause faults
241 	 * on erased or otherwise unreadable pages. Emulate erased pages,
242 	 * return other errors.
243 	 */
244   #ifdef CONFIG_SOC_LPC55S36
245 	/* On LPC55S36, use a HAL function to safely copy from Flash. */
246 	rc = FLASH_Read(&priv->config, addr, data, len);
247 	switch (rc) {
248 	case kStatus_FLASH_Success:
249 		rc = 0;
250 		break;
251 	case kStatus_FLASH_EccError:
252 		/* Check id the ECC issue is due to the Flash being erased
253 		 * ("addr" and "len" must be word-aligned for this call).
254 		 */
255 		rc = FLASH_VerifyErase(&priv->config,
256 				       ROUND_DOWN(addr, 4),
257 				       ROUND_DOWN(addr + len + 3, 4) - ROUND_DOWN(addr, 4));
258 		if (rc == kStatus_FLASH_Success) {
259 			rc = -ENODATA;
260 		} else {
261 			rc = -EIO;
262 		}
263 		break;
264 	default:
265 		rc = -EIO;
266 		break;
267 	}
268   #else /* CONFIG_SOC_LPC55S36 */
269 	/* On all other targets, check if the Flash area is readable.
270 	 * If so, copy data from it directly.
271 	 */
272 	rc = is_area_readable(addr, len);
273 	if (!rc) {
274 		memcpy(data, (void *) addr, len);
275 	}
276   #endif /* CONFIG_SOC_LPC55S36 */
277 
278 	if (rc == -ENODATA) {
279 		/* Erased area, return dummy data as an erased page. */
280 		memset(data, 0xFF, len);
281 		rc = 0;
282 	}
283 #else /* CONFIG_CHECK_BEFORE_READING */
284 	/* No safety checks, directly copy the memory mapped data. */
285 	memcpy(data, (void *) addr, len);
286 #endif /* CONFIG_CHECK_BEFORE_READING */
287 
288 	return rc;
289 }
290 
flash_mcux_write(const struct device * dev,off_t offset,const void * data,size_t len)291 static int flash_mcux_write(const struct device *dev, off_t offset,
292 				const void *data, size_t len)
293 {
294 	struct flash_priv *priv = dev->data;
295 	uint32_t addr;
296 	status_t rc;
297 	unsigned int key;
298 
299 	if (k_sem_take(&priv->write_lock, K_FOREVER)) {
300 		return -EACCES;
301 	}
302 
303 	addr = offset + priv->pflash_block_base;
304 
305 	key = irq_lock();
306 	rc = FLASH_Program(&priv->config,
307 #if CONFIG_MCUX_FLASH_K4_API
308 			(FMU_Type *) DT_INST_REG_ADDR(0),
309 #endif
310 			addr, (uint8_t *) data, len);
311 
312 	if (IS_ENABLED(SOC_FLASH_NEED_CLEAR_CACHES)) {
313 		clear_flash_caches();
314 	}
315 
316 	irq_unlock(key);
317 
318 	k_sem_give(&priv->write_lock);
319 
320 	return (rc == kStatus_Success) ? 0 : -EINVAL;
321 }
322 
323 #if defined(CONFIG_FLASH_PAGE_LAYOUT)
324 static const struct flash_pages_layout dev_layout = {
325 	.pages_count = DT_REG_SIZE(SOC_NV_FLASH_NODE) /
326 				DT_PROP(SOC_NV_FLASH_NODE, erase_block_size),
327 	.pages_size = DT_PROP(SOC_NV_FLASH_NODE, erase_block_size),
328 };
329 
flash_mcux_pages_layout(const struct device * dev,const struct flash_pages_layout ** layout,size_t * layout_size)330 static void flash_mcux_pages_layout(const struct device *dev,
331 				    const struct flash_pages_layout **layout,
332 				    size_t *layout_size)
333 {
334 	*layout = &dev_layout;
335 	*layout_size = 1;
336 }
337 #endif /* CONFIG_FLASH_PAGE_LAYOUT */
338 
339 static const struct flash_parameters *
flash_mcux_get_parameters(const struct device * dev)340 flash_mcux_get_parameters(const struct device *dev)
341 {
342 	ARG_UNUSED(dev);
343 
344 	return &flash_mcux_parameters;
345 }
346 
347 static struct flash_priv flash_data;
348 
349 static DEVICE_API(flash, flash_mcux_api) = {
350 	.erase = flash_mcux_erase,
351 	.write = flash_mcux_write,
352 	.read = flash_mcux_read,
353 	.get_parameters = flash_mcux_get_parameters,
354 #if defined(CONFIG_FLASH_PAGE_LAYOUT)
355 	.page_layout = flash_mcux_pages_layout,
356 #endif
357 };
358 
359 #if (defined(SOC_HAS_IAP) || defined(SOC_HAS_MSF1)) && !defined(CONFIG_MCUX_FLASH_K4_API)
360 #define FLASH_PROP_BLOCK_BASE	kFLASH_PropertyPflashBlockBaseAddr
361 #else
362 #define FLASH_PROP_BLOCK_BASE kFLASH_PropertyPflash0BlockBaseAddr
363 #endif
364 
flash_mcux_init(const struct device * dev)365 static int flash_mcux_init(const struct device *dev)
366 {
367 	struct flash_priv *priv = dev->data;
368 	uint32_t pflash_block_base;
369 	status_t rc;
370 
371 	k_sem_init(&priv->write_lock, 1, 1);
372 
373 	rc = FLASH_Init(&priv->config);
374 
375 	FLASH_GetProperty(&priv->config, FLASH_PROP_BLOCK_BASE, &pflash_block_base);
376 
377 	priv->pflash_block_base = (uint32_t) pflash_block_base;
378 
379 	return (rc == kStatus_Success) ? 0 : -EIO;
380 }
381 
382 DEVICE_DT_INST_DEFINE(0, flash_mcux_init, NULL,
383 			&flash_data, NULL, POST_KERNEL,
384 			CONFIG_FLASH_INIT_PRIORITY, &flash_mcux_api);
385