Introduction: Linux operating system – when using BIOS boot instead of UEFI is writing useful information into MBR – Master Boot Record, which is stored at the beginning of the hard disk at first 512 bytes, at first 445 bytes boot loader is stored, from 446 until 512 bytes partition table is stored which is describing layout – start and end of existing partitions on our hard disk.

In case these first 512 bytes get wiped, we will be unable to boot our system, recently I was preparing EX342 and got into a situation to test a recovery approach.

Scenario:

Let’s imagine that we did this – dd if=/dev/zero of=/dev/sda bs=512 count=1

Before wiping, let’s say that we had one partition that corresponds to /dev/sda1 – /boot and partition two that corresponds to /dev/sda2 – /

This is going to wipe whole MBR from our disk and we will not be able to boot our system at all, so we need to use the recovery disk and boot into a troubleshooting mode.

It will find(part) our system and mount it under /mnt/sysimage , our mission is to recreate wiped partitions and reinstall boot loader.

Approach:

First, we will create just one partition of the whole disk by using fdisk utility, now we need the figure out what was the last sector of the first(boot) partition because we do not want to screw up our second(root) partition and it’s beginning.

We need to find out how many blocks are used in total by the partition, OS will detect previous filesystem on the partition, in case it is ext(2-4) we can use tune2fs or make2fs to find block count, if it is XFS we can use xfs_info to find the block count, after finding this information, we need to apply below formula in order to find the last sector.

Some facts that we know for sure:

First sector: 2048

Sector size: 512

Block size: 4096

After we found block number, we will apply below formula:

Calculation:

(Number of blocks) x (Block Size) = (Exact number of bytes)

(Exact number of bytes) / (Sector Size) = (Total Sectors)

(Total Sectors) – 2048 – 1 = Last Sector

I am unsure why and where this – 1 has to be added, but I am sure that the above calculation is right.

Now we will destroy the partition with the fdisk and recreate it with the proper last sector, so the next partition can also start at the proper first sector.

After recreation, we will install our grub boot loader with the command grub2-install /dev/sda and we will regenerate new grub config with grub2-mkconfig -o /boot/grub2/grub.cfg , reboot the system, magic is done.