STM32 gotchas
322. LCD code with FSMC/FMC working in 'F4, does not work in 'F7 (due to cache writebacks into memory not marked as Device)

LCD controllers (LCDC) with built-in graphics memory (GRAM) are often interfaced to microcontrollers using 8080-style parallel bus. However, they usually don't expose the GRAM's address bus, as it's hundreds of kilobytes requiring around 20 pins, and it would be out of the external memory range of moderate-sized microcontrollers anyway. Instead, they recognize that there's rarely a need for random access to GRAM; instead, it is usually written in relatively large chunks sequentially. So, these controllers usually implement GRAM address registers, and they provide autoincrement of this address upon each individual write.

If in STM32 the FMC/FSMC interface is used for interfacing with LCDC, each of the 4 blocks for SRAM interfacing has a 64MB address area allocated. So, as address lines are not connected, user (after setting up the address register in LCDC) can either store data through one single address, or write data to consecutive addresses as if writing to real RAM (e.g. using memcpy() or some similar function of some suitable library.

In STM32F4xx (or any other STM32 based on Cortex-M3 or Cortex-M4) this will work as expected. However, in the Cortex-M7 based STM32 ('F7 and 'H7), if data cache is enabled, erratical data will be displayed on LCD. The reason is, that the 0x6000'0000 area where the FMC/FSMC SRAM banks are allocated, is by default tagged as Normal/Cacheable (Write-back, write allocate). So, the memory subsystem reads in a whole line from that address into the cache - and as LCDs are often connected in a way which does not allow reading, the read value may be some surprising invalid value - writes performed by processor go into the cache, and when the memory subsystem finds it appropriate, it writes out the whole line. However, the "appropriate" does not necessarily mean, that the processor has already written the whole cache line; however, all line is written to external memory at once.

With normal memory, this does not result in any problem: yet-unmodified values are written back to the memory. However, from the LCD's point of view this meanss, that extra data (and possibly invalid, as they were read from unreadable position) are written, these invalid data are displayed as errorneous pixels and the address register gets incremented, so the rest of correctly written pixels are shifted on the screen. The result is corrupted image.

The solution is to mark the given FMC/FSMC block as Device in the MPU. Some STM32 allow to swap the SRAM blocks (e.g. using SYSCFG_MEMRMP.SWP_FMC bitfield) into the 0xC000'0000 area, which by default is tagged as Device, so that may be a convenient way how to solve the above problem with no need to program the MPU.