1 /*
2  * Copyright (c) 2020 Vossloh Cogifer
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT st_stm32h7_flash_controller
8 
9 #include <zephyr/sys/util.h>
10 #include <zephyr/kernel.h>
11 #include <zephyr/device.h>
12 #include <string.h>
13 #include <zephyr/drivers/flash.h>
14 #include <zephyr/init.h>
15 #include <zephyr/sys/barrier.h>
16 #include <soc.h>
17 #if defined(CONFIG_SOC_SERIES_STM32H7RSX)
18 #include <stm32h7rsxx_ll_bus.h>
19 #include <stm32h7rsxx_ll_utils.h>
20 #else
21 #include <stm32h7xx_ll_bus.h>
22 #include <stm32h7xx_ll_utils.h>
23 #endif /* CONFIG_SOC_SERIES_STM32H7RSX */
24 
25 #include "flash_stm32.h"
26 #include "stm32_hsem.h"
27 
28 #define LOG_DOMAIN flash_stm32h7
29 #define LOG_LEVEL  CONFIG_FLASH_LOG_LEVEL
30 #include <zephyr/logging/log.h>
31 LOG_MODULE_REGISTER(LOG_DOMAIN);
32 
33 /* Let's wait for double the max erase time to be sure that the operation is
34  * completed.
35  */
36 #define STM32H7_FLASH_TIMEOUT     (2 * DT_PROP(DT_INST(0, st_stm32_nv_flash), max_erase_time))
37 /* No information in documentation about that. */
38 #define STM32H7_FLASH_OPT_TIMEOUT_MS 800
39 
40 #define STM32H7_M4_FLASH_SIZE DT_PROP_OR(DT_INST(0, st_stm32_nv_flash), bank2_flash_size, 0)
41 #ifdef CONFIG_CPU_CORTEX_M4
42 #if STM32H7_M4_FLASH_SIZE == 0
43 #error Flash driver on M4 requires the DT property bank2-flash-size
44 #else
45 #define REAL_FLASH_SIZE_KB (KB(STM32H7_M4_FLASH_SIZE * 2))
46 #endif
47 #else
48 #define REAL_FLASH_SIZE_KB KB(LL_GetFlashSize())
49 #endif
50 #define SECTOR_PER_BANK ((REAL_FLASH_SIZE_KB / FLASH_SECTOR_SIZE) / 2)
51 #if defined(DUAL_BANK)
52 #define STM32H7_SERIES_MAX_FLASH_KB KB(2048)
53 #define BANK2_OFFSET                (STM32H7_SERIES_MAX_FLASH_KB / 2)
54 /* When flash is dual bank and flash size is smaller than Max flash size of
55  * the serie, there is a discontinuty between bank1 and bank2.
56  */
57 #define DISCONTINUOUS_BANKS         (REAL_FLASH_SIZE_KB < STM32H7_SERIES_MAX_FLASH_KB)
58 #define NUMBER_OF_BANKS             2
59 #else
60 #define NUMBER_OF_BANKS             1
61 #endif
62 
63 struct flash_stm32_sector_t {
64 	int sector_index;
65 	int bank;
66 	volatile uint32_t *cr;
67 	volatile uint32_t *sr;
68 };
69 
70 #if defined(CONFIG_FLASH_STM32_READOUT_PROTECTION) || defined(CONFIG_FLASH_STM32_WRITE_PROTECT)
71 
commit_optb(const struct device * dev)72 static int commit_optb(const struct device *dev)
73 {
74 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
75 	int64_t timeout_time = k_uptime_get() + STM32H7_FLASH_OPT_TIMEOUT_MS;
76 
77 	/* Make sure previous write is completed before committing option bytes. */
78 	barrier_dsync_fence_full();
79 	regs->OPTCR |= FLASH_OPTCR_OPTSTART;
80 	barrier_dsync_fence_full();
81 	while (regs->OPTSR_CUR & FLASH_OPTSR_OPT_BUSY) {
82 		if (k_uptime_get() > timeout_time) {
83 			LOG_ERR("Timeout writing option bytes.");
84 			return -ETIMEDOUT;
85 		}
86 	}
87 
88 	return 0;
89 }
90 
91 /* Returns negative value on error, 0 if a change was not need, 1 if a change has been made. */
write_opt(const struct device * dev,uint32_t mask,uint32_t value,uintptr_t cur,bool commit)92 static int write_opt(const struct device *dev, uint32_t mask, uint32_t value, uintptr_t cur,
93 		     bool commit)
94 {
95 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
96 	/* PRG register always follows CUR register. */
97 	uintptr_t prg = cur + 4;
98 	int rc = 0;
99 
100 	if (regs->OPTCR & FLASH_OPTCR_OPTLOCK) {
101 		LOG_ERR("Option bytes locked");
102 		return -EIO;
103 	}
104 
105 	rc = flash_stm32_wait_flash_idle(dev);
106 	if (rc < 0) {
107 		LOG_ERR("Err flash no idle");
108 		return rc;
109 	}
110 
111 	if ((sys_read32(cur) & mask) == value) {
112 		/* A change not needed, return 0. */
113 		return 0;
114 	}
115 
116 	sys_write32((sys_read32(cur) & ~mask) | value, prg);
117 
118 	if (commit) {
119 		rc = commit_optb(dev);
120 		if (rc < 0) {
121 			return rc;
122 		}
123 	}
124 
125 	/* A change has been made, return 1. */
126 	return 1;
127 }
128 
129 #endif /* CONFIG_FLASH_STM32_WRITE_PROTECT || CONFIG_FLASH_STM32_READOUT_PROTECTION */
130 
131 #if defined(CONFIG_FLASH_STM32_READOUT_PROTECTION)
write_optsr(const struct device * dev,uint32_t mask,uint32_t value)132 static int write_optsr(const struct device *dev, uint32_t mask, uint32_t value)
133 {
134 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
135 	uintptr_t cur = (uintptr_t)regs + offsetof(FLASH_TypeDef, OPTSR_CUR);
136 
137 	return write_opt(dev, mask, value, cur, true);
138 }
139 
flash_stm32_get_rdp_level(const struct device * dev)140 uint8_t flash_stm32_get_rdp_level(const struct device *dev)
141 {
142 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
143 
144 	return (regs->OPTSR_CUR & FLASH_OPTSR_RDP_Msk) >> FLASH_OPTSR_RDP_Pos;
145 }
146 
flash_stm32_set_rdp_level(const struct device * dev,uint8_t level)147 void flash_stm32_set_rdp_level(const struct device *dev, uint8_t level)
148 {
149 	write_optsr(dev, FLASH_OPTSR_RDP_Msk, (uint32_t)level << FLASH_OPTSR_RDP_Pos);
150 }
151 #endif /* CONFIG_FLASH_STM32_READOUT_PROTECTION */
152 
153 #if defined(CONFIG_FLASH_STM32_WRITE_PROTECT)
154 
155 #define WP_MSK FLASH_WPSN_WRPSN_Msk
156 #define WP_POS FLASH_WPSN_WRPSN_Pos
157 
write_optwp(const struct device * dev,uint32_t mask,uint32_t value,uint32_t bank)158 static int write_optwp(const struct device *dev, uint32_t mask, uint32_t value, uint32_t bank)
159 {
160 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
161 	uintptr_t cur = (uintptr_t)regs + offsetof(FLASH_TypeDef, WPSN_CUR1);
162 
163 	if (bank >= NUMBER_OF_BANKS) {
164 		return -EINVAL;
165 	}
166 
167 #ifdef DUAL_BANK
168 	if (bank == 1) {
169 		cur = (uintptr_t)regs + offsetof(FLASH_TypeDef, WPSN_CUR2);
170 	}
171 #endif /* DUAL_BANK */
172 
173 	return write_opt(dev, mask, value, cur, false);
174 }
175 
flash_stm32_update_wp_sectors(const struct device * dev,uint64_t changed_sectors,uint64_t protected_sectors)176 int flash_stm32_update_wp_sectors(const struct device *dev, uint64_t changed_sectors,
177 				  uint64_t protected_sectors)
178 {
179 	/* All banks share the same sector mask. */
180 	const uint64_t bank_mask = WP_MSK >> WP_POS;
181 	const uint32_t sectors_per_bank = __builtin_popcount(WP_MSK);
182 	uint64_t sectors_mask = 0;
183 	uint32_t protected_sectors_reg;
184 	uint32_t changed_sectors_reg;
185 	int ret, ret2 = 0;
186 	bool commit = false;
187 
188 	for (int i = 0; i < NUMBER_OF_BANKS; i++) {
189 		sectors_mask |= bank_mask << (sectors_per_bank * i);
190 	}
191 
192 	if ((changed_sectors & sectors_mask) != changed_sectors) {
193 		return -EINVAL;
194 	}
195 
196 	for (int i = 0; i < NUMBER_OF_BANKS; i++) {
197 		/* Prepare protected and changed masks per bank. */
198 		protected_sectors_reg = (protected_sectors >> sectors_per_bank * i) & bank_mask;
199 		changed_sectors_reg = (changed_sectors >> sectors_per_bank * i) & bank_mask;
200 
201 		if (changed_sectors_reg == 0) {
202 			continue;
203 		}
204 		changed_sectors_reg <<= WP_POS;
205 		protected_sectors_reg <<= WP_POS;
206 		/* Sector is protected when bit == 0. Flip protected_sectors bits */
207 		protected_sectors_reg = ~protected_sectors_reg;
208 
209 		ret = write_optwp(dev, changed_sectors_reg, protected_sectors_reg, i);
210 		/* Option byte was successfully changed if the return value is greater than 0. */
211 		if (ret > 0) {
212 			commit = true;
213 		} else if (ret < 0) {
214 			/* Do not continue changing WP on error. */
215 			ret2 = ret;
216 			break;
217 		}
218 	}
219 
220 	if (commit) {
221 		ret = commit_optb(dev);
222 		/* Make sure to return the first error. */
223 		if (ret < 0 && ret2 == 0) {
224 			ret2 = ret;
225 		}
226 	}
227 
228 	return ret2;
229 }
230 
flash_stm32_get_wp_sectors(const struct device * dev,uint64_t * protected_sectors)231 int flash_stm32_get_wp_sectors(const struct device *dev, uint64_t *protected_sectors)
232 {
233 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
234 
235 	*protected_sectors = (~regs->WPSN_CUR1 & WP_MSK) >> WP_POS;
236 #ifdef DUAL_BANK
237 	/* Available only for STM32H7x */
238 	uint64_t proctected_sectors_2 =
239 		(~regs->WPSN_CUR2 & WP_MSK) >> WP_POS;
240 	const uint32_t sectors_per_bank = __builtin_popcount(WP_MSK);
241 	*protected_sectors |= proctected_sectors_2 << sectors_per_bank;
242 #endif /* DUAL_BANK */
243 
244 	return 0;
245 }
246 #endif /* CONFIG_FLASH_STM32_WRITE_PROTECT */
247 
248 #ifdef CONFIG_FLASH_STM32_BLOCK_REGISTERS
flash_stm32_control_register_disable(const struct device * dev)249 int flash_stm32_control_register_disable(const struct device *dev)
250 {
251 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
252 
253 	/*
254 	 * Access to control register can be disabled by writing wrong key to
255 	 * the key register. Option register will remain disabled until reset.
256 	 * Writing wrong key causes a bus fault, so we need to set FAULTMASK to
257 	 * disable faults, and clear bus fault pending bit before enabling them
258 	 * again.
259 	 */
260 	regs->CR1 |= FLASH_CR_LOCK;
261 #ifdef DUAL_BANK
262 	regs->CR2 |= FLASH_CR_LOCK;
263 #endif /* DUAL_BANK */
264 
265 	__set_FAULTMASK(1);
266 	regs->KEYR1 = 0xffffffff;
267 
268 #ifdef DUAL_BANK
269 	regs->KEYR2 = 0xffffffff;
270 #endif /* DUAL_BANK */
271 	/* Make sure that the fault occurs before we clear it. */
272 	barrier_dsync_fence_full();
273 
274 	/* Clear Bus Fault pending bit */
275 	SCB->SHCSR &= ~SCB_SHCSR_BUSFAULTPENDED_Msk;
276 	/* Make sure to clear the fault before changing the fault mask. */
277 	barrier_dsync_fence_full();
278 
279 	__set_FAULTMASK(0);
280 
281 	return 0;
282 }
283 
flash_stm32_option_bytes_disable(const struct device * dev)284 int flash_stm32_option_bytes_disable(const struct device *dev)
285 {
286 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
287 
288 	/*
289 	 * Access to option register can be disabled by writing wrong key to
290 	 * the key register. Option register will remain disabled until reset.
291 	 * Writing wrong key causes a bus fault, so we need to set FAULTMASK to
292 	 * disable faults, and clear bus fault pending bit before enabling them
293 	 * again.
294 	 */
295 	regs->OPTCR |= FLASH_OPTCR_OPTLOCK;
296 
297 	__set_FAULTMASK(1);
298 	regs->OPTKEYR = 0xffffffff;
299 	/* Make sure that the fault occurs before we clear it. */
300 	barrier_dsync_fence_full();
301 
302 	/* Clear Bus Fault pending bit */
303 	SCB->SHCSR &= ~SCB_SHCSR_BUSFAULTPENDED_Msk;
304 	/* Make sure to clear the fault before changing the fault mask. */
305 	barrier_dsync_fence_full();
306 	__set_FAULTMASK(0);
307 
308 	return 0;
309 }
310 #endif /* CONFIG_FLASH_STM32_BLOCK_REGISTERS */
311 
flash_stm32_option_bytes_lock(const struct device * dev,bool enable)312 int flash_stm32_option_bytes_lock(const struct device *dev, bool enable)
313 {
314 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
315 
316 	if (enable) {
317 		regs->OPTCR |= FLASH_OPTCR_OPTLOCK;
318 	} else if (regs->OPTCR & FLASH_OPTCR_OPTLOCK) {
319 #ifdef CONFIG_SOC_SERIES_STM32H7RSX
320 		regs->OPTKEYR = FLASH_OPTKEY1;
321 		regs->OPTKEYR = FLASH_OPTKEY2;
322 #else
323 		regs->OPTKEYR = FLASH_OPT_KEY1;
324 		regs->OPTKEYR = FLASH_OPT_KEY2;
325 #endif /* CONFIG_SOC_SERIES_STM32H7RSX */
326 	}
327 
328 	if (enable) {
329 		LOG_DBG("Option bytes locked");
330 	} else {
331 		LOG_DBG("Option bytes unlocked");
332 	}
333 
334 	return 0;
335 }
336 
flash_stm32_valid_range(const struct device * dev,off_t offset,uint32_t len,bool write)337 bool flash_stm32_valid_range(const struct device *dev, off_t offset, uint32_t len, bool write)
338 {
339 #if defined(DUAL_BANK)
340 	if (DISCONTINUOUS_BANKS) {
341 		/*
342 		 * In case of bank1/2 discontinuity, the range should not
343 		 * start before bank2 and end beyond bank1 at the same time.
344 		 * Locations beyond bank2 are caught by flash_stm32_range_exists
345 		 */
346 		if ((offset < BANK2_OFFSET) && (offset + len > REAL_FLASH_SIZE_KB / 2)) {
347 			LOG_ERR("Range ovelaps flash bank discontinuity");
348 			return false;
349 		}
350 	}
351 #endif
352 
353 	if (write) {
354 		if ((offset % (FLASH_NB_32BITWORD_IN_FLASHWORD * 4)) != 0) {
355 			LOG_ERR("Write offset not aligned on flashword length. "
356 				"Offset: 0x%lx, flashword length: %d",
357 				(unsigned long)offset, FLASH_NB_32BITWORD_IN_FLASHWORD * 4);
358 			return false;
359 		}
360 	}
361 	return flash_stm32_range_exists(dev, offset, len);
362 }
363 
flash_stm32_check_status(const struct device * dev)364 static int flash_stm32_check_status(const struct device *dev)
365 {
366 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
367 	/* The hardware corrects single ECC errors and detects double
368 	 * ECC errors. Corrected data is returned for single ECC
369 	 * errors, so in this case we just log a warning.
370 	 */
371 #ifdef DUAL_BANK
372 	uint32_t const error_bank2 = (FLASH_FLAG_ALL_ERRORS_BANK2 & ~FLASH_FLAG_SNECCERR_BANK2);
373 #endif
374 	uint32_t sr;
375 
376 #if defined(CONFIG_SOC_SERIES_STM32H7RSX)
377 	uint32_t const error_bank =
378 		(FLASH_FLAG_ECC_ERRORS & ~FLASH_FLAG_SNECCERR & ~FLASH_FLAG_DBECCERR);
379 
380 	/* Read the Interrupt status flags. */
381 	sr = regs->ISR;
382 	if (sr & (FLASH_FLAG_SNECCERR)) {
383 		uint32_t word = regs->ECCSFADDR & FLASH_ECCSFADDR_SEC_FADD;
384 
385 		LOG_WRN("Bank%d ECC error at 0x%08x", 1,
386 			word * 4 * FLASH_NB_32BITWORD_IN_FLASHWORD);
387 	}
388 
389 	if (sr & (FLASH_FLAG_DBECCERR)) {
390 		uint32_t word = regs->ECCDFADDR & FLASH_ECCDFADDR_DED_FADD;
391 
392 		LOG_WRN("Bank%d ECC error at 0x%08x", 1,
393 			word * 4 * FLASH_NB_32BITWORD_IN_FLASHWORD);
394 	}
395 
396 	/* Clear the ECC flags (including FA) */
397 	regs->ICR = FLASH_FLAG_ECC_ERRORS;
398 	if (sr & error_bank) {
399 #else
400 	uint32_t const error_bank1 = (FLASH_FLAG_ALL_ERRORS_BANK1 & ~FLASH_FLAG_SNECCERR_BANK1);
401 
402 	/* Read the status flags. */
403 	sr = regs->SR1;
404 	if (sr & (FLASH_FLAG_SNECCERR_BANK1 | FLASH_FLAG_DBECCERR_BANK1)) {
405 		uint32_t word = regs->ECC_FA1 & FLASH_ECC_FA_FAIL_ECC_ADDR;
406 
407 		LOG_WRN("Bank%d ECC error at 0x%08x", 1,
408 			word * 4 * FLASH_NB_32BITWORD_IN_FLASHWORD);
409 	}
410 	/* Clear the flags (including FA1R) */
411 	regs->CCR1 = FLASH_FLAG_ALL_BANK1;
412 
413 	if (sr & error_bank1) {
414 #endif /* CONFIG_SOC_SERIES_STM32H7RSX */
415 		LOG_ERR("Status Bank%d: 0x%08x", 1, sr);
416 		return -EIO;
417 	}
418 
419 #ifdef DUAL_BANK
420 	sr = regs->SR2;
421 	if (sr & (FLASH_FLAG_SNECCERR_BANK1 | FLASH_FLAG_DBECCERR_BANK1)) {
422 		uint32_t word = regs->ECC_FA2 & FLASH_ECC_FA_FAIL_ECC_ADDR;
423 
424 		LOG_WRN("Bank%d ECC error at 0x%08x", 2,
425 			word * 4 * FLASH_NB_32BITWORD_IN_FLASHWORD);
426 	}
427 	regs->CCR2 = FLASH_FLAG_ALL_BANK2;
428 	if (sr & error_bank2) {
429 		/* Sometimes the STRBERR is seen when writing to flash
430 		 * from M4 (upper 128KiB) with code running from lower
431 		 * 896KiB. Don't know why it happens, but technical
432 		 * reference manual (section 4.7.4) says application can
433 		 * ignore this error and continue with normal write. So
434 		 * check and return here if the error is STRBERR and clear
435 		 * the error by setting CCR2 bit.
436 		 */
437 		if (sr & FLASH_FLAG_STRBERR_BANK2) {
438 			regs->CCR2 |= FLASH_FLAG_STRBERR_BANK2;
439 			return 0;
440 		}
441 		LOG_ERR("Status Bank%d: 0x%08x", 2, sr);
442 		return -EIO;
443 	}
444 #endif
445 
446 	return 0;
447 }
448 
449 int flash_stm32_wait_flash_idle(const struct device *dev)
450 {
451 	int64_t timeout_time = k_uptime_get() + STM32H7_FLASH_TIMEOUT;
452 	int rc;
453 
454 	rc = flash_stm32_check_status(dev);
455 	if (rc < 0) {
456 		return -EIO;
457 	}
458 #ifdef DUAL_BANK
459 	while ((FLASH_STM32_REGS(dev)->SR1 & FLASH_SR_QW) ||
460 	       (FLASH_STM32_REGS(dev)->SR2 & FLASH_SR_QW))
461 #else
462 	while (FLASH_STM32_REGS(dev)->SR1 & FLASH_SR_QW)
463 #endif
464 	{
465 		if (k_uptime_get() > timeout_time) {
466 			LOG_ERR("Timeout! val: %d", STM32H7_FLASH_TIMEOUT);
467 			return -EIO;
468 		}
469 	}
470 
471 	return 0;
472 }
473 
474 static struct flash_stm32_sector_t get_sector(const struct device *dev, off_t offset)
475 {
476 	struct flash_stm32_sector_t sector;
477 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
478 
479 #ifdef DUAL_BANK
480 	off_t temp_offset = offset + (CONFIG_FLASH_BASE_ADDRESS & 0xffffff);
481 
482 	bool bank_swap;
483 	/* Check whether bank1/2 are swapped */
484 	bank_swap = (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_SWAP_BANK) == FLASH_OPTCR_SWAP_BANK);
485 	sector.sector_index = offset / FLASH_SECTOR_SIZE;
486 	if ((temp_offset < (REAL_FLASH_SIZE_KB / 2)) && !bank_swap) {
487 		sector.bank = 1;
488 		sector.cr = &regs->CR1;
489 		sector.sr = &regs->SR1;
490 	} else if ((temp_offset >= BANK2_OFFSET) && bank_swap) {
491 		sector.sector_index -= BANK2_OFFSET / FLASH_SECTOR_SIZE;
492 		sector.bank = 1;
493 		sector.cr = &regs->CR2;
494 		sector.sr = &regs->SR2;
495 	} else if ((temp_offset < (REAL_FLASH_SIZE_KB / 2)) && bank_swap) {
496 		sector.bank = 2;
497 		sector.cr = &regs->CR1;
498 		sector.sr = &regs->SR1;
499 	} else if ((temp_offset >= BANK2_OFFSET) && !bank_swap) {
500 		sector.sector_index -= BANK2_OFFSET / FLASH_SECTOR_SIZE;
501 		sector.bank = 2;
502 		sector.cr = &regs->CR2;
503 		sector.sr = &regs->SR2;
504 	} else {
505 		sector.sector_index = 0;
506 		sector.bank = 0;
507 		sector.cr = NULL;
508 		sector.sr = NULL;
509 	}
510 #else
511 	if (offset < REAL_FLASH_SIZE_KB) {
512 		sector.sector_index = offset / FLASH_SECTOR_SIZE;
513 		sector.bank = 1;
514 		sector.cr = &regs->CR1;
515 		sector.sr = &regs->SR1;
516 	} else {
517 		sector.sector_index = 0;
518 		sector.bank = 0;
519 		sector.cr = NULL;
520 		sector.sr = NULL;
521 	}
522 #endif
523 
524 	return sector;
525 }
526 
527 static int erase_sector(const struct device *dev, int offset)
528 {
529 	int rc;
530 	struct flash_stm32_sector_t sector = get_sector(dev, offset);
531 
532 	if (sector.bank == 0) {
533 
534 		LOG_ERR("Offset %ld does not exist", (long)offset);
535 		return -EINVAL;
536 	}
537 
538 	/* if the control register is locked, do not fail silently */
539 	if (*(sector.cr) & FLASH_CR_LOCK) {
540 		return -EIO;
541 	}
542 
543 	rc = flash_stm32_wait_flash_idle(dev);
544 	if (rc < 0) {
545 		return rc;
546 	}
547 
548 	*(sector.cr) &= ~FLASH_CR_SNB;
549 	*(sector.cr) |= (FLASH_CR_SER | ((sector.sector_index << FLASH_CR_SNB_Pos) & FLASH_CR_SNB));
550 	*(sector.cr) |= FLASH_CR_START;
551 	/* flush the register write */
552 	barrier_dsync_fence_full();
553 
554 	rc = flash_stm32_wait_flash_idle(dev);
555 	*(sector.cr) &= ~(FLASH_CR_SER | FLASH_CR_SNB);
556 
557 	return rc;
558 }
559 
560 int flash_stm32_block_erase_loop(const struct device *dev, unsigned int offset, unsigned int len)
561 {
562 	unsigned int address = offset;
563 	int rc = 0;
564 
565 	for (; address <= offset + len - 1; address += FLASH_SECTOR_SIZE) {
566 		rc = erase_sector(dev, address);
567 		if (rc < 0) {
568 			break;
569 		}
570 	}
571 	return rc;
572 }
573 
574 static int wait_write_queue(const struct flash_stm32_sector_t *sector)
575 {
576 	int64_t timeout_time = k_uptime_get() + 100;
577 
578 	while (*(sector->sr) & FLASH_SR_QW) {
579 		if (k_uptime_get() > timeout_time) {
580 			LOG_ERR("Timeout! val: %d", 100);
581 			return -EIO;
582 		}
583 	}
584 
585 	return 0;
586 }
587 
588 static int write_ndwords(const struct device *dev, off_t offset, const uint64_t *data, uint8_t n)
589 {
590 	volatile uint64_t *flash = (uint64_t *)(offset + FLASH_STM32_BASE_ADDRESS);
591 	int rc;
592 	int i;
593 	struct flash_stm32_sector_t sector = get_sector(dev, offset);
594 
595 	if (sector.bank == 0) {
596 		LOG_ERR("Offset %ld does not exist", (long)offset);
597 		return -EINVAL;
598 	}
599 
600 	/* if the control register is locked, do not fail silently */
601 	if (*(sector.cr) & FLASH_CR_LOCK) {
602 		return -EIO;
603 	}
604 
605 	/* Check that no Flash main memory operation is ongoing */
606 	rc = flash_stm32_wait_flash_idle(dev);
607 	if (rc < 0) {
608 		return rc;
609 	}
610 
611 	/* Check if 256 bits location is erased */
612 	for (i = 0; i < n; ++i) {
613 		if (flash[i] != 0xFFFFFFFFFFFFFFFFUL) {
614 			return -EIO;
615 		}
616 	}
617 
618 	/* Set the PG bit */
619 	*(sector.cr) |= FLASH_CR_PG;
620 
621 	/* Flush the register write */
622 	barrier_dsync_fence_full();
623 
624 	/* Perform the data write operation at the desired memory address */
625 	for (i = 0; i < n; ++i) {
626 		/* Source dword may be unaligned, so take extra care when dereferencing it */
627 		flash[i] = UNALIGNED_GET(data + i);
628 
629 		/* Flush the data write */
630 		barrier_dsync_fence_full();
631 
632 		wait_write_queue(&sector);
633 	}
634 
635 	/* Wait until the BSY bit is cleared */
636 	rc = flash_stm32_wait_flash_idle(dev);
637 
638 	/* Clear the PG bit */
639 	*(sector.cr) &= (~FLASH_CR_PG);
640 
641 	return rc;
642 }
643 
644 int flash_stm32_write_range(const struct device *dev, unsigned int offset, const void *data,
645 			    unsigned int len)
646 {
647 	int rc = 0;
648 	int i, j;
649 	const uint8_t ndwords = FLASH_NB_32BITWORD_IN_FLASHWORD / 2;
650 	const uint8_t nbytes = FLASH_NB_32BITWORD_IN_FLASHWORD * 4;
651 	uint8_t unaligned_datas[nbytes];
652 
653 	for (i = 0; i < len && i + nbytes <= len; i += nbytes, offset += nbytes) {
654 		rc = write_ndwords(dev, offset, (const uint64_t *)data + (i >> 3), ndwords);
655 		if (rc < 0) {
656 			return rc;
657 		}
658 	}
659 
660 	/* Handle the remaining bytes if length is not aligned on
661 	 * FLASH_NB_32BITWORD_IN_FLASHWORD
662 	 */
663 	if (i < len) {
664 		memset(unaligned_datas, 0xff, sizeof(unaligned_datas));
665 		for (j = 0; j < len - i; ++j) {
666 			unaligned_datas[j] = ((uint8_t *)data)[i + j];
667 		}
668 		rc = write_ndwords(dev, offset, (const uint64_t *)unaligned_datas, ndwords);
669 		if (rc < 0) {
670 			return rc;
671 		}
672 	}
673 
674 	return rc;
675 }
676 
677 static int flash_stm32h7_cr_lock(const struct device *dev, bool enable)
678 {
679 	FLASH_TypeDef *regs = FLASH_STM32_REGS(dev);
680 
681 	int rc = 0;
682 
683 	if (enable) {
684 		rc = flash_stm32_wait_flash_idle(dev);
685 		if (rc) {
686 			return rc;
687 		}
688 	}
689 
690 	/* Bank 1 */
691 	if (enable) {
692 		regs->CR1 |= FLASH_CR_LOCK;
693 	} else {
694 		if (regs->CR1 & FLASH_CR_LOCK) {
695 			regs->KEYR1 = FLASH_KEY1;
696 			regs->KEYR1 = FLASH_KEY2;
697 		}
698 	}
699 #ifdef DUAL_BANK
700 	/* Bank 2 */
701 	if (enable) {
702 		regs->CR2 |= FLASH_CR_LOCK;
703 	} else {
704 		if (regs->CR2 & FLASH_CR_LOCK) {
705 			regs->KEYR2 = FLASH_KEY1;
706 			regs->KEYR2 = FLASH_KEY2;
707 		}
708 	}
709 #endif
710 
711 	if (enable) {
712 		LOG_DBG("Enable write protection");
713 	} else {
714 		LOG_DBG("Disable write protection");
715 	}
716 
717 	return rc;
718 }
719 
720 #ifdef CONFIG_CPU_CORTEX_M7
721 static void flash_stm32h7_flush_caches(const struct device *dev, off_t offset, size_t len)
722 {
723 	ARG_UNUSED(dev);
724 
725 	if (!(SCB->CCR & SCB_CCR_DC_Msk)) {
726 		return; /* Cache not enabled */
727 	}
728 
729 	SCB_InvalidateDCache_by_Addr((uint32_t *)(FLASH_STM32_BASE_ADDRESS + offset), len);
730 }
731 #endif /* CONFIG_CPU_CORTEX_M7 */
732 
733 static int flash_stm32h7_erase(const struct device *dev, off_t offset, size_t len)
734 {
735 	int rc, rc2;
736 
737 #ifdef CONFIG_CPU_CORTEX_M7
738 	/* Flush whole sectors */
739 	off_t flush_offset = ROUND_DOWN(offset, FLASH_SECTOR_SIZE);
740 	size_t flush_len = ROUND_UP(offset + len - 1, FLASH_SECTOR_SIZE) - flush_offset;
741 #endif /* CONFIG_CPU_CORTEX_M7 */
742 
743 	if (!flash_stm32_valid_range(dev, offset, len, true)) {
744 		LOG_ERR("Erase range invalid. Offset: %ld, len: %zu", (long)offset, len);
745 		return -EINVAL;
746 	}
747 
748 	if (!len) {
749 		return 0;
750 	}
751 
752 	flash_stm32_sem_take(dev);
753 
754 	LOG_DBG("Erase offset: %ld, len: %zu", (long)offset, len);
755 
756 	rc = flash_stm32h7_cr_lock(dev, false);
757 	if (rc) {
758 		goto done;
759 	}
760 
761 	rc = flash_stm32_block_erase_loop(dev, offset, len);
762 
763 #ifdef CONFIG_CPU_CORTEX_M7
764 	/* Flush cache on all sectors affected by the erase */
765 	flash_stm32h7_flush_caches(dev, flush_offset, flush_len);
766 #elif CONFIG_CPU_CORTEX_M4
767 	if (LL_AHB1_GRP1_IsEnabledClock(LL_AHB1_GRP1_PERIPH_ART) && LL_ART_IsEnabled()) {
768 		LOG_ERR("Cortex M4: ART enabled not supported by flash driver");
769 	}
770 #endif /* CONFIG_CPU_CORTEX_M7 */
771 done:
772 	rc2 = flash_stm32h7_cr_lock(dev, true);
773 
774 	if (!rc) {
775 		rc = rc2;
776 	}
777 
778 	flash_stm32_sem_give(dev);
779 
780 	return rc;
781 }
782 
783 static int flash_stm32h7_write(const struct device *dev, off_t offset, const void *data, size_t len)
784 {
785 	int rc;
786 
787 	if (!flash_stm32_valid_range(dev, offset, len, true)) {
788 		LOG_ERR("Write range invalid. Offset: %ld, len: %zu", (long)offset, len);
789 		return -EINVAL;
790 	}
791 
792 	if (!len) {
793 		return 0;
794 	}
795 
796 	flash_stm32_sem_take(dev);
797 
798 	LOG_DBG("Write offset: %ld, len: %zu", (long)offset, len);
799 
800 	rc = flash_stm32h7_cr_lock(dev, false);
801 	if (!rc) {
802 		rc = flash_stm32_write_range(dev, offset, data, len);
803 	}
804 
805 	int rc2 = flash_stm32h7_cr_lock(dev, true);
806 
807 	if (!rc) {
808 		rc = rc2;
809 	}
810 
811 	flash_stm32_sem_give(dev);
812 
813 	return rc;
814 }
815 
816 static int flash_stm32h7_read(const struct device *dev, off_t offset, void *data, size_t len)
817 {
818 	if (!flash_stm32_valid_range(dev, offset, len, false)) {
819 		LOG_ERR("Read range invalid. Offset: %ld, len: %zu", (long)offset, len);
820 		return -EINVAL;
821 	}
822 
823 	if (!len) {
824 		return 0;
825 	}
826 
827 	LOG_DBG("Read offset: %ld, len: %zu", (long)offset, len);
828 
829 	/* During the read we mask bus errors and only allow NMI.
830 	 *
831 	 * If the flash has a double ECC error then there is normally
832 	 * a bus fault, but we want to return an error code instead.
833 	 */
834 	unsigned int irq_lock_key = irq_lock();
835 
836 	__set_FAULTMASK(1);
837 	SCB->CCR |= SCB_CCR_BFHFNMIGN_Msk;
838 	barrier_dsync_fence_full();
839 	barrier_isync_fence_full();
840 
841 	memcpy(data, (uint8_t *)FLASH_STM32_BASE_ADDRESS + offset, len);
842 
843 	__set_FAULTMASK(0);
844 	SCB->CCR &= ~SCB_CCR_BFHFNMIGN_Msk;
845 	barrier_dsync_fence_full();
846 	barrier_isync_fence_full();
847 	irq_unlock(irq_lock_key);
848 
849 	return flash_stm32_check_status(dev);
850 }
851 
852 static const struct flash_parameters flash_stm32h7_parameters = {
853 	.write_block_size = FLASH_STM32_WRITE_BLOCK_SIZE,
854 	.erase_value = 0xff,
855 };
856 
857 static const struct flash_parameters *flash_stm32h7_get_parameters(const struct device *dev)
858 {
859 	ARG_UNUSED(dev);
860 
861 	return &flash_stm32h7_parameters;
862 }
863 
864 void flash_stm32_page_layout(const struct device *dev, const struct flash_pages_layout **layout,
865 			     size_t *layout_size)
866 {
867 	ARG_UNUSED(dev);
868 
869 #if defined(DUAL_BANK)
870 	static struct flash_pages_layout stm32h7_flash_layout[3];
871 
872 	if (DISCONTINUOUS_BANKS) {
873 		if (stm32h7_flash_layout[0].pages_count == 0) {
874 			/* Bank1 */
875 			stm32h7_flash_layout[0].pages_count = SECTOR_PER_BANK;
876 			stm32h7_flash_layout[0].pages_size = FLASH_SECTOR_SIZE;
877 			/*
878 			 * Dummy page corresponding to discontinuity
879 			 * between bank1/2
880 			 */
881 			stm32h7_flash_layout[1].pages_count = 1;
882 			stm32h7_flash_layout[1].pages_size =
883 				BANK2_OFFSET - (SECTOR_PER_BANK * FLASH_SECTOR_SIZE);
884 			/* Bank2 */
885 			stm32h7_flash_layout[2].pages_count = SECTOR_PER_BANK;
886 			stm32h7_flash_layout[2].pages_size = FLASH_SECTOR_SIZE;
887 		}
888 		*layout_size = ARRAY_SIZE(stm32h7_flash_layout);
889 	} else {
890 		if (stm32h7_flash_layout[0].pages_count == 0) {
891 			stm32h7_flash_layout[0].pages_count =
892 				REAL_FLASH_SIZE_KB / FLASH_SECTOR_SIZE;
893 			stm32h7_flash_layout[0].pages_size = FLASH_SECTOR_SIZE;
894 		}
895 		*layout_size = 1;
896 	}
897 #else
898 	static struct flash_pages_layout stm32h7_flash_layout[1];
899 
900 	if (stm32h7_flash_layout[0].pages_count == 0) {
901 		stm32h7_flash_layout[0].pages_count = REAL_FLASH_SIZE_KB / FLASH_SECTOR_SIZE;
902 		stm32h7_flash_layout[0].pages_size = FLASH_SECTOR_SIZE;
903 	}
904 	*layout_size = ARRAY_SIZE(stm32h7_flash_layout);
905 #endif
906 	*layout = stm32h7_flash_layout;
907 }
908 
909 static struct flash_stm32_priv flash_data = {
910 	.regs = (FLASH_TypeDef *)DT_INST_REG_ADDR(0),
911 #if DT_NODE_HAS_PROP(DT_INST(0, st_stm32h7_flash_controller), clocks)
912 	.pclken = {.bus = DT_INST_CLOCKS_CELL(0, bus), .enr = DT_INST_CLOCKS_CELL(0, bits)},
913 #endif
914 };
915 
916 static DEVICE_API(flash, flash_stm32h7_api) = {
917 	.erase = flash_stm32h7_erase,
918 	.write = flash_stm32h7_write,
919 	.read = flash_stm32h7_read,
920 	.get_parameters = flash_stm32h7_get_parameters,
921 #ifdef CONFIG_FLASH_PAGE_LAYOUT
922 	.page_layout = flash_stm32_page_layout,
923 #endif
924 #ifdef CONFIG_FLASH_EX_OP_ENABLED
925 	.ex_op = flash_stm32_ex_op,
926 #endif
927 };
928 
929 static int stm32h7_flash_init(const struct device *dev)
930 {
931 #if DT_NODE_HAS_PROP(DT_INST(0, st_stm32h7_flash_controller), clocks)
932 	/* Only stm32h7 dual core devices have the clocks property */
933 	struct flash_stm32_priv *p = FLASH_STM32_PRIV(dev);
934 	const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
935 
936 	if (!device_is_ready(clk)) {
937 		LOG_ERR("clock control device not ready");
938 		return -ENODEV;
939 	}
940 
941 	/* enable clock : enable the RCC_AHB3ENR_FLASHEN bit */
942 	if (clock_control_on(clk, (clock_control_subsys_t)&p->pclken) != 0) {
943 		LOG_ERR("Failed to enable clock");
944 		return -EIO;
945 	}
946 #endif
947 	flash_stm32_sem_init(dev);
948 
949 	LOG_DBG("Flash initialized. BS: %zu", flash_stm32h7_parameters.write_block_size);
950 
951 #if ((CONFIG_FLASH_LOG_LEVEL >= LOG_LEVEL_DBG) && CONFIG_FLASH_PAGE_LAYOUT)
952 	const struct flash_pages_layout *layout;
953 	size_t layout_size;
954 
955 	flash_stm32_page_layout(dev, &layout, &layout_size);
956 	for (size_t i = 0; i < layout_size; i++) {
957 		LOG_DBG("Block %zu: bs: %zu count: %zu", i, layout[i].pages_size,
958 			layout[i].pages_count);
959 	}
960 #endif
961 
962 	return 0;
963 }
964 
965 DEVICE_DT_INST_DEFINE(0, stm32h7_flash_init, NULL, &flash_data, NULL, POST_KERNEL,
966 		      CONFIG_FLASH_INIT_PRIORITY, &flash_stm32h7_api);
967