Mounting full disc images using losetup

There are many guides online about mounting pure loopback filesystems (such as ext2 filesystems) with features such as encryption and other beneficial options. But I found it very hard to get hold of a guide to tell you how to loop complete disk images.

What's the difference?

Well disc images contain more than just a filesystem. sometimes they contain multiple partitions in an image, or a bootloader. Trying to mount these using the simple "mount ./imagefile.img /mount/point -o loop" will not work (and will give you a few errors, depending on the image: mostly to do with a corrupted filesystem).

If you want an example of such an image. Look at my embedded projects. They are provided as images for direct writing. This means they have a built in bootloader and root partition. These cannot be mounted normally.

So how do you mount them?

Well, losetup had a life-saving option called offset. This allowes you to bypass chunks of the image, then mount it (so you can miss out the bootloader and go directly to the filesystem/partition you want).

The command is:

mount  /path/to/image.img /mount/point -o loop,offset=nBytes

...where "nBytes" is the offset in bytes.

This is great and all, but how are you supposed to know what the offset is?

Well, I use fdisk. if you type:

fdisk /path/to/image -lu should get something like this (I used my soundserver project as an example):

You must set cylinders.
You can do this from the extra functions menu.
Disk ./soundserver_nov_05.img: 0 MB, 0 bytes
1 heads, 31 sectors/track, 0 cylinders, total 0 sectors
Units = sectors of 1 * 512 = 512 bytes

                   Device Boot      Start         End      Blocks   Id  System
./soundserver_nov_05.img1              31       31743       15856+  83  Linux

The bits of information that are needed are in bold (do not worry about the set cylinder warning). Basically, the offset needs to be the start of the partition you want to mount (in this case soundserver_nov_05.img1, with value in bold). We are told that the start is 31 blocks in. Great, but we need it in Bytes, not Blocks. This is where the first bold line helps. It gives us the information. In this case it says "Units = sectors of 1 * 512 = 512 bytes". So each block is 512 Bytes, and we are 31 blocks in. Therefore:

512 * 31 = 15872

So we need an offset of 15872 Bytes, we add this to our example mount line:

mount ./soundserver.img /mount/point -o loop,offset=15872

...and the filesystem is mounted! This will work with multiple partitions as well, just select the partition you want to mount, get the start block and calculate the offset. There is not much else to it.