1 /*
2  * Copyright (c) 2021 STMicroelectronics
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define LOG_DOMAIN flash_stm32l5
8 #define LOG_LEVEL CONFIG_FLASH_LOG_LEVEL
9 #include <zephyr/logging/log.h>
10 LOG_MODULE_REGISTER(LOG_DOMAIN);
11 
12 #include <zephyr/kernel.h>
13 #include <zephyr/device.h>
14 #include <string.h>
15 #include <zephyr/drivers/flash.h>
16 #include <zephyr/init.h>
17 #include <soc.h>
18 #include <stm32_ll_icache.h>
19 #include <stm32_ll_system.h>
20 
21 #include "flash_stm32.h"
22 
23 #if defined(CONFIG_SOC_SERIES_STM32H5X)
24 /* at this time stm32h5 mcus have 128KB (stm32h50x) or 2MB (stm32h56x/57x) */
25 #define STM32_SERIES_MAX_FLASH	2048
26 #elif defined(CONFIG_SOC_SERIES_STM32L5X)
27 #define STM32_SERIES_MAX_FLASH	512
28 #elif defined(CONFIG_SOC_SERIES_STM32U5X)
29 /* It is used to handle the 2 banks discontinuity case, the discontinuity is not happen on STM32U5,
30  *  so define it to flash size to avoid the unexptected check.
31  */
32 #define STM32_SERIES_MAX_FLASH	(CONFIG_FLASH_SIZE)
33 #endif
34 
35 #define PAGES_PER_BANK ((FLASH_SIZE / FLASH_PAGE_SIZE) / 2)
36 
37 #define BANK2_OFFSET	(KB(STM32_SERIES_MAX_FLASH) / 2)
38 
39 #define ICACHE_DISABLE_TIMEOUT_VALUE           1U   /* 1ms */
40 #define ICACHE_INVALIDATE_TIMEOUT_VALUE        1U   /* 1ms */
41 
stm32_icache_disable(void)42 static int stm32_icache_disable(void)
43 {
44 	int status = 0;
45 	uint32_t tickstart;
46 
47 	LOG_DBG("I-cache Disable");
48 	/* Clear BSYENDF flag first and then disable the instruction cache
49 	 * that starts a cache invalidation procedure
50 	 */
51 	CLEAR_BIT(ICACHE->FCR, ICACHE_FCR_CBSYENDF);
52 
53 	LL_ICACHE_Disable();
54 
55 	/* Get tick */
56 	tickstart = k_uptime_get_32();
57 
58 	/* Wait for instruction cache to get disabled */
59 	while (LL_ICACHE_IsEnabled()) {
60 		if ((k_uptime_get_32() - tickstart) >
61 						ICACHE_DISABLE_TIMEOUT_VALUE) {
62 			/* New check to avoid false timeout detection in case
63 			 * of preemption.
64 			 */
65 			if (LL_ICACHE_IsEnabled()) {
66 				status = -ETIMEDOUT;
67 				break;
68 			}
69 		}
70 	}
71 
72 	return status;
73 }
74 
stm32_icache_enable(void)75 static void stm32_icache_enable(void)
76 {
77 	LOG_DBG("I-cache Enable");
78 	LL_ICACHE_Enable();
79 }
80 
icache_wait_for_invalidate_complete(void)81 static int icache_wait_for_invalidate_complete(void)
82 {
83 	int status = -EIO;
84 	uint32_t tickstart;
85 
86 	/* Check if ongoing invalidation operation */
87 	if (LL_ICACHE_IsActiveFlag_BUSY()) {
88 		/* Get tick */
89 		tickstart = k_uptime_get_32();
90 
91 		/* Wait for end of cache invalidation */
92 		while (!LL_ICACHE_IsActiveFlag_BSYEND()) {
93 			if ((k_uptime_get_32() - tickstart) >
94 					ICACHE_INVALIDATE_TIMEOUT_VALUE) {
95 				break;
96 			}
97 		}
98 	}
99 
100 	/* Clear any pending flags */
101 	if (LL_ICACHE_IsActiveFlag_BSYEND()) {
102 		LOG_DBG("I-cache Invalidation complete");
103 
104 		LL_ICACHE_ClearFlag_BSYEND();
105 		status = 0;
106 	} else {
107 		LOG_ERR("I-cache Invalidation timeout");
108 
109 		status = -ETIMEDOUT;
110 	}
111 
112 	if (LL_ICACHE_IsActiveFlag_ERR()) {
113 		LOG_ERR("I-cache error");
114 
115 		LL_ICACHE_ClearFlag_ERR();
116 		status = -EIO;
117 	}
118 
119 	return status;
120 }
121 
122 /* Macro to check if the flash is Dual bank or not */
123 #if defined(CONFIG_SOC_SERIES_STM32H5X)
124 #define stm32_flash_has_2_banks(flash_device) true
125 #else
126 #define stm32_flash_has_2_banks(flash_device) \
127 	(((FLASH_STM32_REGS(flash_device)->OPTR & FLASH_STM32_DBANK) \
128 	== FLASH_STM32_DBANK) \
129 	? (true) : (false))
130 #endif /* CONFIG_SOC_SERIES_STM32H5X */
131 
132 /*
133  * offset and len must be aligned on write-block-size for write,
134  * positive and not beyond end of flash
135  */
flash_stm32_valid_range(const struct device * dev,off_t offset,uint32_t len,bool write)136 bool flash_stm32_valid_range(const struct device *dev, off_t offset,
137 			     uint32_t len,
138 			     bool write)
139 {
140 	if (stm32_flash_has_2_banks(dev) &&
141 			(CONFIG_FLASH_SIZE < STM32_SERIES_MAX_FLASH)) {
142 		/*
143 		 * In case of bank1/2 discontinuity, the range should not
144 		 * start before bank2 and end beyond bank1 at the same time.
145 		 * Locations beyond bank2 are caught by
146 		 * flash_stm32_range_exists.
147 		 */
148 		if ((offset < BANK2_OFFSET) &&
149 					(offset + len > FLASH_SIZE / 2)) {
150 			return 0;
151 		}
152 	}
153 
154 	if (write && !flash_stm32_valid_write(offset, len)) {
155 		return false;
156 	}
157 	return flash_stm32_range_exists(dev, offset, len);
158 }
159 
write_nwords(const struct device * dev,off_t offset,const uint32_t * buff,size_t n)160 static int write_nwords(const struct device *dev, off_t offset, const uint32_t *buff, size_t n)
161 {
162 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
163 	volatile uint32_t *flash = (uint32_t *)(offset
164 						+ FLASH_STM32_BASE_ADDRESS);
165 	bool full_zero = true;
166 	uint32_t tmp;
167 	int rc;
168 	int i;
169 
170 	/* if the non-secure control register is locked,do not fail silently */
171 	if (regs->NSCR & FLASH_STM32_NSLOCK) {
172 		LOG_ERR("NSCR locked\n");
173 		return -EIO;
174 	}
175 
176 	/* Check that no Flash main memory operation is ongoing */
177 	rc = flash_stm32_wait_flash_idle(dev);
178 	if (rc < 0) {
179 		return rc;
180 	}
181 
182 	/* Check if this double/quad word is erased and value isn't 0.
183 	 *
184 	 * It is allowed to write only zeros over an already written dword / qword
185 	 * See 6.3.7 in STM32L5 reference manual.
186 	 * See 7.3.7 in STM32U5 reference manual.
187 	 * See 7.3.5 in STM32H5 reference manual.
188 	 */
189 	for (i = 0; i < n; i++) {
190 		if (buff[i] != 0) {
191 			full_zero = false;
192 			break;
193 		}
194 	}
195 	if (!full_zero) {
196 		for (i = 0; i < n; i++) {
197 			if (flash[i] != 0xFFFFFFFFUL) {
198 				LOG_ERR("Word at offs %ld not erased", (long)(offset + i));
199 				return -EIO;
200 			}
201 		}
202 	}
203 
204 	/* Set the NSPG bit */
205 	regs->NSCR |= FLASH_STM32_NSPG;
206 
207 	/* Flush the register write */
208 	tmp = regs->NSCR;
209 
210 	/* Perform the data write operation at the desired memory address */
211 	for (i = 0; i < n; i++) {
212 		flash[i] = buff[i];
213 	}
214 
215 	/* Wait until the NSBSY bit is cleared */
216 	rc = flash_stm32_wait_flash_idle(dev);
217 
218 	/* Clear the NSPG bit */
219 	regs->NSCR &= (~FLASH_STM32_NSPG);
220 
221 	return rc;
222 }
223 
erase_page(const struct device * dev,unsigned int offset)224 static int erase_page(const struct device *dev, unsigned int offset)
225 {
226 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
227 	uint32_t tmp;
228 	int rc;
229 	int page;
230 
231 	/* if the non-secure control register is locked,do not fail silently */
232 	if (regs->NSCR & FLASH_STM32_NSLOCK) {
233 		LOG_ERR("NSCR locked\n");
234 		return -EIO;
235 	}
236 
237 	/* Check that no Flash memory operation is ongoing */
238 	rc = flash_stm32_wait_flash_idle(dev);
239 	if (rc < 0) {
240 		return rc;
241 	}
242 
243 	if (stm32_flash_has_2_banks(dev)) {
244 		bool bank_swap;
245 		/* Check whether bank1/2 are swapped */
246 		bank_swap =
247 		((regs->OPTR & FLASH_OPTR_SWAP_BANK) == FLASH_OPTR_SWAP_BANK);
248 
249 		if ((offset < (FLASH_SIZE / 2)) && !bank_swap) {
250 			/* The pages to be erased is in bank 1 */
251 			regs->NSCR &= ~FLASH_STM32_NSBKER_MSK;
252 			page = offset / FLASH_PAGE_SIZE;
253 			LOG_DBG("Erase page %d on bank 1", page);
254 		} else if ((offset >= BANK2_OFFSET) && bank_swap) {
255 			/* The pages to be erased is in bank 1 */
256 			regs->NSCR &= ~FLASH_STM32_NSBKER_MSK;
257 			page = (offset - BANK2_OFFSET) / FLASH_PAGE_SIZE;
258 			LOG_DBG("Erase page %d on bank 1", page);
259 		} else if ((offset < (FLASH_SIZE / 2)) && bank_swap) {
260 			/* The pages to be erased is in bank 2 */
261 			regs->NSCR |= FLASH_STM32_NSBKER;
262 			page = offset / FLASH_PAGE_SIZE;
263 			LOG_DBG("Erase page %d on bank 2", page);
264 		} else if ((offset >= BANK2_OFFSET) && !bank_swap) {
265 			/* The pages to be erased is in bank 2 */
266 			regs->NSCR |= FLASH_STM32_NSBKER;
267 			page = (offset - BANK2_OFFSET) / FLASH_PAGE_SIZE;
268 			LOG_DBG("Erase page %d on bank 2", page);
269 		} else {
270 			LOG_ERR("Offset %d does not exist", offset);
271 			return -EINVAL;
272 		}
273 	} else {
274 		page = offset / FLASH_PAGE_SIZE_128_BITS;
275 		LOG_DBG("Erase page %d\n", page);
276 	}
277 
278 	/* Set the NSPER bit and select the page you wish to erase */
279 	regs->NSCR |= FLASH_STM32_NSPER;
280 	regs->NSCR &= ~FLASH_STM32_NSPNB_MSK;
281 	regs->NSCR |= (page << FLASH_STM32_NSPNB_POS);
282 
283 	/* Set the NSSTRT bit */
284 	regs->NSCR |= FLASH_STM32_NSSTRT;
285 
286 	/* flush the register write */
287 	tmp = regs->NSCR;
288 
289 	/* Wait for the NSBSY bit */
290 	rc = flash_stm32_wait_flash_idle(dev);
291 
292 	if (stm32_flash_has_2_banks(dev)) {
293 		regs->NSCR &= ~(FLASH_STM32_NSPER | FLASH_STM32_NSBKER);
294 	} else {
295 		regs->NSCR &= ~(FLASH_STM32_NSPER);
296 	}
297 
298 	return rc;
299 }
300 
flash_stm32_block_erase_loop(const struct device * dev,unsigned int offset,unsigned int len)301 int flash_stm32_block_erase_loop(const struct device *dev,
302 				 unsigned int offset,
303 				 unsigned int len)
304 {
305 	unsigned int address = offset;
306 	int rc = 0;
307 	bool icache_enabled = LL_ICACHE_IsEnabled();
308 
309 	if (icache_enabled) {
310 		/* Disable icache, this will start the invalidation procedure.
311 		 * All changes(erase/write) to flash memory should happen when
312 		 * i-cache is disabled. A write to flash performed without
313 		 * disabling i-cache will set ERRF error flag in SR register.
314 		 */
315 		rc = stm32_icache_disable();
316 		if (rc != 0) {
317 			return rc;
318 		}
319 	}
320 
321 	for (; address <= offset + len - 1 ; address += FLASH_PAGE_SIZE) {
322 		rc = erase_page(dev, address);
323 		if (rc < 0) {
324 			break;
325 		}
326 	}
327 
328 	if (icache_enabled) {
329 		/* Since i-cache was disabled, this would start the
330 		 * invalidation procedure, so wait for completion.
331 		 */
332 		rc = icache_wait_for_invalidate_complete();
333 
334 		/* I-cache should be enabled only after the
335 		 * invalidation is complete.
336 		 */
337 		stm32_icache_enable();
338 	}
339 
340 	return rc;
341 }
342 
flash_stm32_write_range(const struct device * dev,unsigned int offset,const void * data,unsigned int len)343 int flash_stm32_write_range(const struct device *dev, unsigned int offset,
344 			    const void *data, unsigned int len)
345 {
346 	int i, rc = 0;
347 	bool icache_enabled = LL_ICACHE_IsEnabled();
348 
349 	if (icache_enabled) {
350 		/* Disable icache, this will start the invalidation procedure.
351 		 * All changes(erase/write) to flash memory should happen when
352 		 * i-cache is disabled. A write to flash performed without
353 		 * disabling i-cache will set ERRF error flag in SR register.
354 		 */
355 		rc = stm32_icache_disable();
356 		if (rc != 0) {
357 			return rc;
358 		}
359 	}
360 
361 	for (i = 0; i < len; i += FLASH_STM32_WRITE_BLOCK_SIZE) {
362 		rc = write_nwords(dev, offset + i, ((const uint32_t *) data + (i>>2)),
363 				  FLASH_STM32_WRITE_BLOCK_SIZE / 4);
364 		if (rc < 0) {
365 			break;
366 		}
367 	}
368 
369 	if (icache_enabled) {
370 		/* Since i-cache was disabled, this would start the
371 		 * invalidation procedure, so wait for completion.
372 		 */
373 		rc = icache_wait_for_invalidate_complete();
374 
375 		/* I-cache should be enabled only after the
376 		 * invalidation is complete.
377 		 */
378 		stm32_icache_enable();
379 	}
380 
381 	return rc;
382 }
383 
flash_stm32_page_layout(const struct device * dev,const struct flash_pages_layout ** layout,size_t * layout_size)384 void flash_stm32_page_layout(const struct device *dev,
385 			     const struct flash_pages_layout **layout,
386 			     size_t *layout_size)
387 {
388 	static struct flash_pages_layout stm32_flash_layout[3];
389 	static size_t stm32_flash_layout_size;
390 
391 	*layout = stm32_flash_layout;
392 
393 	if (stm32_flash_layout[0].pages_count != 0) {
394 		/* Short circuit calculation logic if already performed (size is known) */
395 		*layout_size = stm32_flash_layout_size;
396 		return;
397 	}
398 
399 	if (stm32_flash_has_2_banks(dev) &&
400 			(CONFIG_FLASH_SIZE < STM32_SERIES_MAX_FLASH)) {
401 		/*
402 		 * For stm32l552xx with 256 kB flash
403 		 * which have space between banks 1 and 2.
404 		 */
405 
406 		/* Bank1 */
407 		stm32_flash_layout[0].pages_count = PAGES_PER_BANK;
408 		stm32_flash_layout[0].pages_size = FLASH_PAGE_SIZE;
409 
410 		/* Dummy page corresponding to space between banks 1 and 2 */
411 		stm32_flash_layout[1].pages_count = 1;
412 		stm32_flash_layout[1].pages_size = BANK2_OFFSET
413 				- (PAGES_PER_BANK * FLASH_PAGE_SIZE);
414 
415 		/* Bank2 */
416 		stm32_flash_layout[2].pages_count = PAGES_PER_BANK;
417 		stm32_flash_layout[2].pages_size = FLASH_PAGE_SIZE;
418 
419 		stm32_flash_layout_size = ARRAY_SIZE(stm32_flash_layout);
420 	} else {
421 		/*
422 		 * For stm32l562xx & stm32l552xx with 512 flash or stm32u5x,
423 		 * which has no space between banks 1 and 2.
424 		 */
425 
426 		if (stm32_flash_has_2_banks(dev)) {
427 			/* L5 flash with dualbank has 2k pages */
428 			/* U5 flash pages are always 8 kB in size */
429 			/* H5 flash pages are always 8 kB in size */
430 			/* Considering one layout of full flash size, even with 2 banks */
431 			stm32_flash_layout[0].pages_count = FLASH_SIZE / FLASH_PAGE_SIZE;
432 			stm32_flash_layout[0].pages_size = FLASH_PAGE_SIZE;
433 #if defined(CONFIG_SOC_SERIES_STM32L5X)
434 		} else {
435 			/* L5 flash without dualbank has 4k pages */
436 			stm32_flash_layout[0].pages_count = FLASH_PAGE_NB_128_BITS;
437 			stm32_flash_layout[0].pages_size = FLASH_PAGE_SIZE_128_BITS;
438 #endif /* CONFIG_SOC_SERIES_STM32L5X */
439 		}
440 
441 		/*
442 		 * In this case the stm32_flash_layout table has one single element
443 		 * when read by the flash_get_page_info()
444 		 */
445 		stm32_flash_layout_size = 1;
446 	}
447 
448 	*layout_size = stm32_flash_layout_size;
449 }
450