gkostka / lwext4

ext2/ext3/ext4 filesystem library for microcontrollers
http://sourceforge.net/projects/lwext4/
Other
482 stars 128 forks source link

Partition CHS values in MBR are incorrect #73

Open rick-masters opened 1 year ago

rick-masters commented 1 year ago

The ext4_mbr_write function calculates CHS (cylinder, head, sector) values incorrectly.

The first problem is that the code incorrectly calculates how many heads (k) are necessary to handle the disk size here: https://github.com/gkostka/lwext4/blob/58bcf89a121b72d4fb66334f1693d3b30e4cb9c5/src/ext4_mbr.c#L145-L153

The disk_size is in bytes but the calculation is in terms of sectors. The disk_size must be divided by the block size to work correctly.

The second problem is that cyl_size is calculated in terms of sectors but should be in bytes: https://github.com/gkostka/lwext4/blob/58bcf89a121b72d4fb66334f1693d3b30e4cb9c5/src/ext4_mbr.c#L155-L156

The final problem is that the bitwise operations to set the CHS bytes are incorrect. When the top two bits of the cylinder are OR'd into the sector value, the lower bits need to be masked off first. Also, when the lower bits are placed in the third byte of the CHS, the top bits must be masked off first: https://github.com/gkostka/lwext4/blob/58bcf89a121b72d4fb66334f1693d3b30e4cb9c5/src/ext4_mbr.c#L179-L186

The forthcoming PR fixes this issue.

By the way, thank you for this project. It is very useful and has been adopted by the live-bootstrap project to help bootstrap a linux distro from "scratch". Specifically, the first kernel is used to create an ext2 initrd file system (using lwext4) for the Fiwix kernel which is used to build and kexec Linux.

Documented here: https://github.com/fosslinux/live-bootstrap/blob/master/parts.rst#20lwext4-100