Skip to content

Commit 2e103d2

Browse files
mattia-moffadanielinux
authored andcommitted
Fix stm32h5 hal_flash_write alignment issues
1 parent 97230f5 commit 2e103d2

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

hal/stm32h5.c

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,8 @@ int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len)
9999
{
100100
int i = 0;
101101
uint32_t *src, *dst;
102-
uint32_t dword[2];
102+
uint32_t qword[4];
103+
uint8_t *qword_bytes = (uint8_t *)qword;
103104

104105
hal_flash_clear_errors(0);
105106
src = (uint32_t *)data;
@@ -112,21 +113,35 @@ int RAMFUNCTION hal_flash_write(uint32_t address, const uint8_t *data, int len)
112113
}
113114
#endif
114115
while (i < len) {
115-
dword[0] = src[i >> 2];
116-
if (len > i + 1)
117-
dword[1] = src[(i >> 2) + 1];
118-
else
119-
dword[1] = 0xFFFFFFFF;
116+
uint32_t cur_addr = (uint32_t)dst + i;
117+
uint32_t *dst_aligned = (uint32_t *)(cur_addr & ~0xf);
118+
int byte_offset = cur_addr - (uint32_t)dst_aligned;
119+
int i_aligned = i - byte_offset;
120+
int j;
121+
if (byte_offset == 0 && i + 16 <= len) {
122+
/* Full aligned 128 bits */
123+
for (j = 0; j < 4; j++) {
124+
qword[j] = src[(i >> 2) + j];
125+
}
126+
} else {
127+
/* Non-aligned / non-full 128 bits */
128+
for (j = 0; j < 16; j++) {
129+
if (j < byte_offset || i_aligned + j >= len)
130+
qword_bytes[j] = ((uint8_t *)dst)[i_aligned + j];
131+
else
132+
qword_bytes[j] = ((uint8_t *)src)[i_aligned + j];
133+
}
134+
}
120135
FLASH_CR |= FLASH_CR_PG;
121-
dst[i >> 2] = dword[0];
122-
ISB();
123-
dst[(i >> 2) + 1] = dword[1];
124-
ISB();
136+
for (j = 0; j < 4; j++) {
137+
dst_aligned[j] = qword[j];
138+
ISB();
139+
}
125140
hal_flash_wait_complete(0);
126141
if ((FLASH_SR & FLASH_SR_EOP) != 0)
127142
FLASH_SR |= FLASH_SR_EOP;
128143
FLASH_CR &= ~FLASH_CR_PG;
129-
i+=8;
144+
i = i_aligned + 16;
130145
DSB();
131146
}
132147
#if (TZ_SECURE())

0 commit comments

Comments
 (0)