STM32 gotchas
61.In 'F42x/43x, erase sector does not work (due to confusing sector numbering)

The STM32F427/249/437/439 comes in two memory sizes: 1MB FLASH and 2MB FLASH. As with all other STM32, individual sectors this FLASH can be erased and rewritten by the application itself.

Sectors in 'F42x/43x are non-uniform, with sizes increasing from 16kB at the beginning of the FLASH to 128kB up to the 1MB boundary, where this pattern starts again. When erasing a sector, the number of sector to be erased has to be written into FLASH_CR.SNB. The varying size of sectors makes calculation of number of sector from memory address a nontrivial task; however, there's one more gotcha ahead.

While in the table denoting the partitioning of 2MB FLASH into sectors, these are numbered sequentially from 0 to 23, the actual value to be written to FLASH_CR.SNB is different. Sectors 0 to 11 are written as 0-11; but starting from sector 12, the value written into FLASH_CR.SNB has to be increased by 4.

As if this would not be confusing enough, there's one more twist on this numbering. The FLASH in 'F42x/43x is dual-bank, which means that it is possible to erase/program one bank while run code and read data from the other1. In the 2MB model, simply the first 1MB is one bank, the second 1MB is the other.

In the 1MB 'F42x/43x model, the picture is more complex: by default, the 1MB is a single-bank FLASH and also behaves as such. However, there's is a bit in the nonvolatile Option bytes, DB1M, which allows the 1MB model to function with dual-bank FLASH. When this bit is set, partitioning of FLASH changes entirely: the first 512kB is one bank and it is partitioned as expected, i.e. exactly like the lower 512kB of the entire FLASH. At the 512kB boundary, the partitioning is restarted (i.e. again starts with 16kB sectors, sector sizes increasing as we go higher with addresses), but also the sectors numbering jumps to 12, as if it would be the 1MB boundary between the two banks in the 2MB model.

And with this, the need to add 4 for sector numbers above and including 12, when writing to FLASH_CR.SNB, still applies.

1. In single-bank FLASH, which is in the vast majority of STM32 models, attempt to read/fetch from FLASH being programmed/erased leads to processor stall until the write/erase finishes, so programs which need to program/erase while running have to run from RAM or external memory where available.