Partition Offsets for Loopback Setup

Every so often, I need to mount a filesystem that exists within a logical volume or sparse file. This means delicately treading around the boot sector, or other partitions.

Linux has a nifty command, called losetup, from the util-linux package. It can make a file look like a disk. It can also be used to mount a partition within a disk. The trick is to set a block device that points to a filesystem.

For example, let’s say I this file:

# ls -alsh harddisk.img 
586M -rw-r--r-- 1 tools tools 10G Aug 26 07:42 harddisk.img

It looks like a 10G sparse file that is using 586M. Taking a peek at its partition table, if it has one:

# fdisk -l -u harddisk.img 

Disk harddisk.img: 10.7 GB, 10737418240 bytes
255 heads, 63 sectors/track, 1305 cylinders, total 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

       Device Boot      Start         End      Blocks   Id  System
harddisk.img1   *          63      996029      497983+  83  Linux
harddisk.img2          996030    10779614     4891792+  83  Linux
harddisk.img3        10779615    20948759     5084572+   7  HPFS/NTFS/exFAT

So we do have partitions in there. Notice on the fdisk output I threw the -u option. From the fdisk man page, -u is described as:

       -u[=unit]
              When listing partition tables, show sizes  in  ’sectors’  or  in
              ’cylinders’.   The  default  is  to  show sizes in sectors.  For
              backward compatibility, it is possible to use the option without
              the  argument -- then the default is used.  Note that the
              optional  argument cannot be separated from the -u  option
              by a space, the correct form is for example ’-u=cylinders’.

So how do we mount harddisk.img2? Take the “start” number from the fdisk output – in this case it is 996030. The above fdisk output also tells us that one sector is 512 bytes. Therefore our offset is 996030*512, or 509967360 bytes. Now, we feed this value to the offset option of losetup (-o):

# losetup -f
/dev/loop0
# losetup -o 509967360 /dev/loop0 /data/harddisk.img 
# mount /dev/loop0 /mnt
# ls -alsh /mnt
total 11M
4.0K drwxr-xr-x  3 root root 4.0K Aug 26 07:42 .
8.0K drwxr-xr-x 28 root root 4.0K Aug 14 19:41 ..
 16K drwx------  2 root root  16K Aug 26 07:41 lost+found
 11M -rw-r--r--  1 root root  10M Aug 26 07:42 SECRETS.gpg

That’s all there is to it! Note that the “losetup -f” command above lets me know which loopback device is available for use – in this case loop0 was. Don’t forget to clean up the mess when done.

# umount /mnt
# losetup -d /dev/loop0

Comments are closed.