util-linux/libfdisk
Pali Rohár 9cade4fbf8 libfdisk: (dos) Fix determining number of heads and sectors per track from MBR
Current algorithm implemented in get_partition_table_geometry() function
is wrong. It take head bits from CHS position from the end of the last
partition and proclaim that this value is number of heads on disk. Same
does for sectors bits from CHS and proclaim that this value is number of
sectors per tracks. As number of disk heads and head bits in CHS position
are different things this just results in bogus detected disk geometry.

Implement a new algorithm to determinate number of heads and sectors per
track from partition sector offsets. In MBR table for every partition is
stored every sector offset in two formats: one as CHS and one as LBA.

Conversion from CHS to LBA is defined by formula:

   LBA = (c * N_heads + h) * N_sectors + (s - 1)

So if we have two different offsets in both CHS and LBA formats, written as
(LBA1, c1, h1, s1) and (LBA2, c2, h2, s2) then we can calculate number of
heads and sectors per tracks by solving linear equations as:

   N_heads = (o1 * h2 - o2 * h1) / (o2 * c1 - o1 * c2)
   N_sectors = (o2 * c1 - o1 * c2) / (c1 * h2 - c2 * h1)

where

   o = LBA - (s - 1)

Integer division also verifies that offsets were calculated from same
number of heads and sectors per track as division must be always positive
with no reminder.

There is a special case when either numerator or denominator is zero. This
indicates that comparing partition offsets have also same CHS offset
divisor which leads to fact that calculation of number of heads and sector
per tracks is not possible.

In MBR table are stored up to 8 offset numbers, so it means there are up
to the 28 of candidates which can expose number of disk heads and number of
disk sectors per track. Start with offsets which belongs to same partition
and start from the first partition. As the first partition in most cases
was used by BIOS for booting.

It is required to skip CHS values 1023/254/63 and 1023/255/63 as these
indicates that values are invalid or overflowed.

Signed-off-by: Pali Rohár <pali.rohar@gmail.com>
2021-07-15 21:49:30 +02:00
..
docs docs: update copyright years 2021-05-31 18:12:07 +02:00
samples libdisk: write sample output to stdout 2019-08-30 16:05:50 +02:00
src libfdisk: (dos) Fix determining number of heads and sectors per track from MBR 2021-07-15 21:49:30 +02:00
COPYING docs: use SPDX license names 2018-08-16 14:47:21 +02:00
Makemodule.am libfdisk: add sample-fdisk-mkpart binary 2017-02-17 16:15:03 +01:00
fdisk.pc.in build-sys: add fdisk.pc 2014-11-26 13:20:16 +01:00
meson.build meson: implement building of static programs 2021-03-17 15:07:27 +01:00