How to auto-mount loop-devices with partitions

1

1

I am testing some filesystem driver code and would like to do so outside of the kernel. The simplest and safest method for doing this is from userspace. So, I have created a file of some length

dd if=/dev/zero of=testfs bs=10M count=50

Then I installed an MBR partitioning scheme using fdisk

fdisk testfs

I can setup a loop device to access my file in block emulated mode:

$ losetup /dev/loop0 testfs

At this point I am able to see this new emulated block device in the device list:

NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0    50G  0 disk 
├─sda1   8:1    0    46G  0 part /
├─sda2   8:2    0     1K  0 part 
└─sda5   8:5    0     4G  0 part [SWAP]
sr0     11:0    1  55.2M  0 rom  
loop0    7:0    0    50M  0 loop 

And this device has the follow partition table

$ fdisk -l /dev/loop0 

Disk /dev/loop0: 52 MB, 52428800 bytes
96 heads, 25 sectors/track, 42 cylinders, total 102400 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: 0xe7d5af9a

      Device Boot      Start         End      Blocks   Id  System
/dev/loop0p1   *        2048      102399       50176    7  HPFS/NTFS/exFAT

However, to create a fileyststem I need to mount the partition, not the "disk". Does the looping system not automatically mount the device's partitions, similar to the other block devices? I was able to create the filesystem by mounting the file through the loop at an offset

$ losetup -o $((2048*512)) /dev/loop0 testfs

But this solution is less than ideal since the behavior is slightly different than real block devices. Is there a way to "automount" partitions when doing through a loop device?

sherrellbc

Posted 2018-02-22T14:11:20.037

Reputation: 447

Answers

2

There is an option for that:

losetup --partscan /dev/loop0 testfs

This will activate the regular partition support in your kernel, creating /dev/loop0p1 and so on.


You can also use partx from util-linux:

losetup /dev/loop0 testfs
partx -u /dev/loop0

This will create kernel-based partitions (/dev/loop0p1, etc.), but the partition table itself will be parsed using libblkid, rather than asking the kernel.


Finally there is kpartx from multipath-tools:

losetup /dev/loop0 testfs
kpartx -u /dev/loop0

Although at first glance this is the same as above, it does not use the kernel's native loop-partition support at all. Instead it creates /dev/mapper/loop0p1 using the device-mapper subsystem (linear mappings).

user1686

Posted 2018-02-22T14:11:20.037

Reputation: 283 655