Description
We detected a potential error that may cause the file system damage when a power outage happens during creating a file or directory.
In the current flow in the _create_file() function, it (1) allocates a start cluster from FAT, (2) assigns the start cluster to the file entry, (3) adds the file entry to its parent directory, and then (4) saves the FAT table. If a power outage happens between (3) and (4), the new file points to an unallocated cluster, which may cause double-pointed clusters and file system damage.
We simulated such kind of failure on Windows and the file system image cannot be mounted.
To solve this issue, we suggest to write the FAT table (call fatfs_fat_purge() ) before calling fatfs_add_file_entry(). We confirmed it can be solved by this solution.