Skip to content

Partition CHS values in MBR are incorrect #73

Open
@rick-masters

Description

@rick-masters

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:

lwext4/src/ext4_mbr.c

Lines 145 to 153 in 58bcf89

disk_size = parent->part_size;
/*Calculate CHS*/
uint32_t k = 16;
while ((k < 256) && ((disk_size / k / 63) > 1024))
k *= 2;
if (k == 256)
--k;

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:

lwext4/src/ext4_mbr.c

Lines 155 to 156 in 58bcf89

const uint32_t cyl_size = 63 * k;
const uint32_t cyl_count = disk_size / cyl_size;

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:

lwext4/src/ext4_mbr.c

Lines 179 to 186 in 58bcf89

mbr->part_entry[i].status = 0;
mbr->part_entry[i].chs1[0] = i ? 0 : 1;;
mbr->part_entry[i].chs1[1] = (cyl_it >> 2) + 1;
mbr->part_entry[i].chs1[2] = cyl_it;
mbr->part_entry[i].type = 0x83;
mbr->part_entry[i].chs2[0] = k - 1;
mbr->part_entry[i].chs2[1] = (cyl_end >> 2) + 63;
mbr->part_entry[i].chs2[2] = cyl_end;

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions