How to write on SD card smaller than sector size (512 bytes)

fatsd

I am writing a library for FAT file system management on STM32 for learning purpose.
I want to use a SD/MMC card connected through SPI bus.

I do some tests with a disk image on PC (I emulate disk_read(),disk_write() with fseek(),fread(),fwrite()) to understand FAT principes.

I just finished the SD/MMC protocole implementation and realize i could not read/write block smaller than a sector (512 bytes)
For reading operation is not a problem, i can ignore unused bytes (window concept), but for writing it seems more complicated…

I heard about the principle of 'read-modify-write', so if i understand i need to read the entire sector i want to modify.
For example, if i write into a file, in worst case, i need to :

  • Read, modify and Write the sector in the file allocation table to update cluster indexes.
  • Read, modify and Write the sector in the file new allocated cluster.
  • Read, modify and Write the sector where the file entry reside.

So in this case, i need 3 reads and 3 writes, sounds like a waste of time, , are you confirm this ?

This also implies that in order to write i need a buffer of at least 512 bytes, are you confirm this ?

(I try to read FatFs source code but it's complicated, but it's complicated. I wonder how he manages to write with a smaller than 512 bytes buffer. Can you explain ?)

I think with a cache mecanism i can limit the number of reads (before modify-write) but this implies to increase the amount of RAM used.

Can you help me see it clearer in this 'write (read-modify-write) sector barrier' ?

Best Answer

Read, modify and Write the sector in the file allocation table to update cluster indexes.

You must do that only when the number of clusters for a file changes. A usual cluster size is 32 KB.

Read, modify and Write the sector in the file new allocated cluster.

No, you only have to write the changed data sectors. You could omit the read cycle when you write the data to card in 512 byte steps.

Read, modify and Write the sector where the file entry reside.

Most FAT implementations write this once on file create, and once on file close (to update the size when written to).