This guide explains how to create a disk image, mount it as a loopback device, and use dmsetup to introduce artificial disk latency. This is useful for testing scenarios where disk I/O performance degradation impacts an application.
First, create a disk image that will act as a virtual disk.
# Create a 10GB disk image
fallocate -l 10G /root/slow_disk.img
Associate the disk image with a loopback device.
# Attach the image to a loop device
losetup /dev/loop10 /root/slow_disk.img
Verify the loopback device:
losetup -a
Use dmsetup to create a device that applies latency.
echo "0 $(blockdev --getsz /dev/loop10) delay /dev/loop10 0 1000 /dev/loop10 0 1000" | dmsetup create slow_disk
This command applies a 1000ms delay to both read and write operations.
Check the device table:
dmsetup table slow_disk
Format and mount the new device:
mkfs.ext4 /dev/mapper/slow_disk
mkdir -p /mnt/slow
mount /dev/mapper/slow_disk /mnt/slow
Verify the mount:
mount | grep slow_disk
You can modify the delay without unmounting the disk.
echo "0 $(blockdev --getsz /dev/loop10) delay /dev/loop10 0 3000000 /dev/loop10 0 3000000" | dmsetup reload slow_disk
dmsetup resume slow_disk
This applies a 3000ms (3s) delay.
echo "0 $(blockdev --getsz /dev/loop10) linear /dev/loop10 0" | dmsetup reload slow_disk
dmsetup resume slow_disk
To ensure reads hit the disk and are affected by latency, clear the system cache:
echo 3 > /proc/sys/vm/drop_caches
This will free pagecache, dentries, and inodes.
If you need to clean up the setup:
umount /mnt/slow
dmsetup remove slow_disk
losetup -d /dev/loop10
rm -f /root/slow_disk.img
This will fully remove the virtual disk and restore normal operations.
| Step | Command |
|---|---|
| Create disk image | fallocate -l 10G /root/slow_disk.img |
| Attach loopback device | losetup /dev/loop10 /root/slow_disk.img |
| Create delayed device | dmsetup create slow_disk with delay settings |
| Mount the device | mount /dev/mapper/slow_disk /mnt/slow |
| Modify delay | dmsetup reload slow_disk with new values |
| Drop caches | echo 3 > /proc/sys/vm/drop_caches |
| Cleanup | dmsetup remove slow_disk, losetup -d /dev/loop10, rm -f /root/slow_disk.img |
This setup is useful for testing disk latency impacts in a controlled environment. 🚀