modm-io / modm

modm: a C++23 library generator for AVR and ARM Cortex-M devices
https://modm.io
Mozilla Public License 2.0
720 stars 128 forks source link

Documentation / example for "safely" accessible flash #1144

Closed hshose closed 4 months ago

hshose commented 4 months ago

I want to use the STM32G474's flash to save some data, that I calculate in my application, similar to the G474 flash example.

The example starts using the Flash from page 32 on, which is safe since the example is only a few bytes large.

Is there a good way to find a safe starting page automatically?

One way would probably be, to reduce the LENGTH of the FLASH section in the linker script and then use pages beyond that at runtime on the G4, right? In this case, I would have to adjust the FLASH length manually every time application changes size, which is not very nice imho.

Am I missing something obvious? :confused:

chris-durand commented 4 months ago

Is there a good way to find a safe starting page automatically?

In many applications you wouldn't want that. If you like to upgrade the device with a larger binary without overwriting the present data in flash, the data section will have to be placed at a fixed location that can't overlap with the code.

If you know how much space is needed for data you could reserve some pages at the end of flash. In the custom linker script you can reduce the LENGTH of the FLASH section by that amount.

In case you don't need data to be persistent across updates the end of your binary is accessible via the symbol __rom_end defined in the linker script. Just declare extern "C" const uint32_t __rom_end[];. You'd need to align the pointer to the next flash page and put your data after.

salkinium commented 4 months ago

Yes, __rom_end exists for this purpose. You can do Flash::getPage(&__rom_end) + 1 to get the next page, but better check that the index is not beyond the last page, since modm(-devices) currently doesn't know how many pages actually exist.