3 * Kamil Lulko, <kamil.lulko@gmail.com>
5 * SPDX-License-Identifier: GPL-2.0+
10 #include <asm/arch/stm32.h>
11 #include "stm32_flash.h"
13 flash_info_t flash_info[CONFIG_SYS_MAX_FLASH_BANKS];
15 #define STM32_FLASH ((struct stm32_flash_regs *)FLASH_CNTL_BASE)
17 void stm32_flash_latency_cfg(int latency)
19 /* 5 wait states, Prefetch enabled, D-Cache enabled, I-Cache enabled */
20 writel(FLASH_ACR_WS(5) | FLASH_ACR_PRFTEN | FLASH_ACR_ICEN
21 | FLASH_ACR_DCEN, &STM32_FLASH->acr);
24 static void stm32_flash_lock(u8 lock)
27 setbits_le32(&STM32_FLASH->cr, STM32_FLASH_CR_LOCK);
29 writel(STM32_FLASH_KEY1, &STM32_FLASH->key);
30 writel(STM32_FLASH_KEY2, &STM32_FLASH->key);
34 unsigned long flash_init(void)
36 unsigned long total_size = 0;
39 for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
40 flash_info[i].flash_id = FLASH_STM32;
41 flash_info[i].sector_count = CONFIG_SYS_MAX_FLASH_SECT;
42 flash_info[i].start[0] = CONFIG_SYS_FLASH_BASE + (i << 20);
43 flash_info[i].size = sect_sz_kb[0];
44 for (j = 1; j < CONFIG_SYS_MAX_FLASH_SECT; j++) {
45 flash_info[i].start[j] = flash_info[i].start[j - 1]
46 + (sect_sz_kb[j - 1]);
47 flash_info[i].size += sect_sz_kb[j];
49 total_size += flash_info[i].size;
55 void flash_print_info(flash_info_t *info)
59 if (info->flash_id == FLASH_UNKNOWN) {
60 printf("missing or unknown FLASH type\n");
62 } else if (info->flash_id == FLASH_STM32) {
63 printf("stm32 Embedded Flash\n");
66 printf(" Size: %ld MB in %d Sectors\n",
67 info->size >> 20, info->sector_count);
69 printf(" Sector Start Addresses:");
70 for (i = 0; i < info->sector_count; ++i) {
75 info->protect[i] ? " (RO)" : " ");
81 int flash_erase(flash_info_t *info, int first, int last)
86 for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
87 if (info == &flash_info[i]) {
97 for (i = first; i <= last; i++) {
98 while (readl(&STM32_FLASH->sr) & STM32_FLASH_SR_BSY)
101 /* clear old sector number before writing a new one */
102 clrbits_le32(&STM32_FLASH->cr, STM32_FLASH_CR_SNB_MASK);
105 setbits_le32(&STM32_FLASH->cr,
106 (i << STM32_FLASH_CR_SNB_OFFSET));
107 } else if (bank == 1) {
108 setbits_le32(&STM32_FLASH->cr,
109 ((0x10 | i) << STM32_FLASH_CR_SNB_OFFSET));
114 setbits_le32(&STM32_FLASH->cr, STM32_FLASH_CR_SER);
115 setbits_le32(&STM32_FLASH->cr, STM32_FLASH_CR_STRT);
117 while (readl(&STM32_FLASH->sr) & STM32_FLASH_SR_BSY)
120 clrbits_le32(&STM32_FLASH->cr, STM32_FLASH_CR_SER);
127 int write_buff(flash_info_t *info, uchar *src, ulong addr, ulong cnt)
131 while (readl(&STM32_FLASH->sr) & STM32_FLASH_SR_BSY)
136 setbits_le32(&STM32_FLASH->cr, STM32_FLASH_CR_PG);
137 /* To make things simple use byte writes only */
138 for (i = 0; i < cnt; i++) {
139 *(uchar *)(addr + i) = src[i];
140 /* avoid re-ordering flash data write and busy status
141 * check as flash memory space attributes are generally Normal
144 while (readl(&STM32_FLASH->sr) & STM32_FLASH_SR_BSY)
147 clrbits_le32(&STM32_FLASH->cr, STM32_FLASH_CR_PG);