Sunday, June 24, 2007

Creating Virtual File Systems in Linux

When you want to test some configuration involving file systems, its not always possible to use a live running system. In such situations it is a good idea to create a virtual filesystem in your hard disk, which will not affect the operation of your machine, except for occupying the hard disk space that you need.

The first step is to create an empty directory as the mount point for the virtual file system.
[root@LinuxBox1 ~]#mkdir /vfsmount

Now we have to create the virtual file system image. Here we will create a file vfs-image in the directory /var/vfs. This file will hold the virtual file sytem.
[root@LinuxBox1 ~]#mkdir /var/vfs

We will create a file system with a size of 100MB. For this we will have to create the file vfs-image with 100MB size.
[root@LinuxBox1 ~]#dd if=/dev/zero of=/var/vfs/vfs-image count=204800
204800+0 records in
204800+0 records out
104857600 bytes (105 MB) copied, 2.3716 seconds, 44.2 MB/s

The count option indicates how many blocks of data should be filled in the file vfs-image. By default 1 block= 512 bytes
1 MB= 512 x 2 x 1024=2048 Blocks
100 MB = 2048 x 100 Blocks = 204800 Blocks

To cross check this
[root@LinuxBox1 ~]#du -h /var/vfs/vfs-image
101M /var/vfs/vfs-image

Now format this file as an ext3 filesystem
[root@LinuxBox1 ~]#mkfs.ext3 -q /var/vfs/vfs-image
/var/vfs/vfs-image is not a block special device.
Proceed anyway? (y,n) y

'mkfs.ext3' is actually a short form for 'mkfs -t ext3'. You can avoid the warning regarding the file not being a block device by using the '-F' option

Now, to use this file system we will have to mount it. To make this mount permanent add an entry into fstab as follows

/etc/fstab

/var/vfs/vfs-image /vfsmount ext3 rw,loop 0 0

The loop option asigns an availiable loop device to the file system.

[root@LinuxBox1 ~]#mount -a
[root@LinuxBox1 ~]#mount|grep vfs-image
/var/vfs/vfs-image on /vfsmount type ext3 (rw,loop=/dev/loop0)
[root@LinuxBox1 ~]#df -h|grep vfs-image
/var/vfs/vfs-image 97M 5.6M 87M 7% /vfsmount

Now just to demonstarate that we can use this filsystem in the same way as other filesystems:
[root@LinuxBox ~]# cd /vfsmount/
[root@LinuxBox ~]# mkdir temp

Now create a 5MB sized file

[root@LinuxBox vfsmount]# dd if=/dev/zero of=/vfsmount/temp/test-space-usage count=10240
10240+0 records in
10240+0 records out
5242880 bytes (5.2 MB) copied, 0.129863 seconds, 40.4 MB/s

Check the filesystem usage
[root@LinuxBox vfsmount]# df -h|grep vfs-image
/var/vfs/vfs-image 97M 11M 82M 12% /vfsmount