Monday, September 12, 2011

Formatting a filesystem using loopback Devices



When it comes to selecting a filesystem, Linux provides its users with a vast set of filesystem to choose from. There are many filesystems which are part of the linux kernel and there are others that are developed over fuse layer and the list is constantly growing everyday. When ever a new filesystem is released you might not want to format it on a partition (because of limited disk space, or to avoid disk fragmentation etc). One of the best method to try out a new filesystem is to format it on a loop back device and mount it on a directory. In this post I will demonstrate how to create a loopback device and then format it with ext4 (you can use any Filesystem of your choice) and the mount it on a directory.

The very first step is to create a file which will act as a psuedo partition so choose the size appropriately. There are two ways of doing it
  * using dd command
  * using truncate command
I prefer truncate over dd  because truncate creates a sparse file so the file does not consume any
disk space untill you add data into it but file created using dd will consume the disk space. To confirm that, 
truncate --size=1GB file-1GB
  Now check the output of
ls -l file-1GB
du -h file-1GB
ls will report the file size as 1GB but du will report the file size as 0. So, it can be confirmed that the file doesn't use any disk space.

  Now try
dd if=/dev/zero of=file-1GB bs=1KB count=1000000
  Now check the output of ls and du.

So, now you have created partition but the system doesn't recongnize it. So lets attach it to a device file.
losetup -f
Let's assume that it retured /dev/loop0, now run
losetup /dev/loop0 file-1GB
Okay. Now all set, choose a filesystem of your choice and format the device. I choose ext4 to demonstrate it.
mkfs.ext4 /dev/loop0
Now mount the device on a directory.
mkdir /my-fs
mount -t ext4 -oloop /dev/loop0 /my-fs.
Thats it. You can confirm it by running
df
your Filesystem will be listed there. Happy hacking :)

Note: When you reboot the system your filesystem will not be displayed by df command. You can either add the entry into /etc/fstab or write a script that will attach the file-1GB to a device and run the mount command. A sample script can be found here