Booting an EXT4 image file from GRUB2

1

My friend needed a fast HDD so I gave her my small 64GB SDD. This SSD had my Linux install on it. I used dd to make an image of the partition (boot, root and home on one partition).

This partition is now sitting on a traditional 500GB EXT4 formatted drive.

Is there any way I can get GRUB to just boot using this .img file I have? I'm not getting my SSD back and I can't be bothered to go through the hassle of setting up my Linux install from scratch. I have come across loopback support in GRUB for ISO images. Does this support EXT4 also? I don't seem to be able to find anything specific and don't want to trash anything.

Cheers.

sjjg

Posted 2012-04-13T10:41:29.690

Reputation: 11

I highly doubt you have an ISO(9660) image. Also note that even if you can boot the kernel with grub, the initrd has no idea about your new (and nested) layout. The shortest solution is to replay the disk image file back onto a (raw) disk, i.e. resolving the loop indirection. – jørgensen – 2012-04-13T14:01:20.517

Yeah I thought as much. I expect booting from the image would cause all kinds of problems with GRUB and kernel updates anyway. Thanks for replying. – sjjg – 2012-04-14T12:01:25.027

Answers

1

even if file contains partition table grub2 can meanwhile boot from, where (hd0,1) is the location of file and (loop,1) is partition within file. however, this will only boot the initramfs, the file is not really mounted.

/etc/grub.d/40_custom

menuentry "My bootable disk image" {
    set isofile="hdd_ext4.img"
    loopback loop (hd0,1)/${isofile}
    linux (loop,1)/boot/vmlinuz-3.16.0-4-amd64 root=/dev/sda1 loop=/${isofile} ro
    initrd (loop,1)/boot/initrd.img-3.16.0-4-amd64
}

write your own mount script, chmod a+x and copy into local-premount folder. use initramfs-tools to create your own "initrd.img-3.16.0-4-amd64" and copy it inside the image file. no need to hard code just use the vars from grub entry ${ROOT} and ${loop} inside the script.

/etc/initramfs-tools/scripts/local-premount

#!/bin/sh

modprobe loop
modprobe ext4

# mount /dev/sda1 (file location)
mkdir /host
mount -n -t ext4 -o rw,data=ordered ${ROOT} /host

# kpartx add partition devmappings for hdd_ext4.img
loop_pt=$(kpartx -av /host${loop} 2>&1 | grep loop | cut -f3 -d" ")

# mount hdd_ext4.img (image file)
mount -n -t ext4 -o loop,rw,data=ordered /dev/mapper/${loop_pt} ${rootmnt}

Note: this will only work if kpartx is installed in initramfs

alecxs

Posted 2012-04-13T10:41:29.690

Reputation: 197

grep loop0p1 from output is not always working, this is more exactly... replace: grep loop | cut -f3 -d" " with: grep -owE '(loop[0-9]+p[0-9]+)' | head -n1 – alecxs – 2018-03-08T19:56:54.990