What happens when a microSD card is hot-unplugged?
Consider a device with a microSD card. The microcontroller writes to the SD card periodically. The operators have an ability to remove the microSD card at any time (they will be removing it every few weeks). Nothing prevents the operators from hot-yanking the microSD card while it’s being written to. Do the microSD cards or the FAT have provisions for such contingency? What provisions should I make in firmware or in hardware?
My device has a switch which puts it into a maintenance mode (the device is headless). The device stops writing to the microSD card in the maintenance mode. The operators are instructed about the switch, but they may forget to flip it before removing the microSD card.
present hardware:
STM32G4 running FatFs. SPI to the microSD card. The card socket is push-in-push-out type, and it has a card detection switch (Hirose DM3AT).
1 answer
There is no provision in FatFS or the fat32 filesystem in general regarding hot-unplug, so this behaviour depends wholly on the implementation layer for your hardware.
As an example, in my use case I have tested the behaviour of my system when I remove the memory card without calling f_close() on open files. I found that there is a 0-sized file that was created when I called f_open(), and when I used filesystem repair tool in Disks on Linux, it created "orphaned" files it found - the data in them was usable up to the removal of the card. If your card socket supports it (ie the card detect triggers before pin contact is lost), you will need to implement card detect interrupt that would flush all filesystem IO and close all opened files if you want to handle it robustly. Alternatively, you will need to buffer data in RAM and write it in f_open -> f_write -> f_sync -> f_close sequence every time. Depending on implementation, it can take a while to do those (a hundred ms is not uncommon).
0 comment threads