I am on Linux and need to know either of the two things:
1) If i have a regular file on some file system on a partition under Linux is there a way to know the set of the physical blocks that this file occupies on the drive from user space? Or at least the set of the file system's clusters?
2) Is there a way to get the same information about the whole free space of the given file system?
In both cases i understand that if there is any possible way to extract this info it will probably be totally unsafe and racy (anything could happen to these set of blocks between the time i see them and act on them somehow). I also really don't want an implementation that will have to know a lot about every filesystem.
It isn't possible in a filesystem-independent way. Filesystems aren't necessarily even built on top of block devices (simple example: NFS).
For
ext2
,ext3
andext4
you can use theext2fslib
library, which is included in thee2fsprogs
distribution.A filefrag command line tool let's you look at allocation of files. It uses the FIEMAP/FIBMAP ioctls mentioned in earlier answers. As mentioned before this is filesystem dependent. Not sure whether anything else than ext2/3/4 supports those ioctls.
I'm not sure whether the pysical values reported refer to the start of the disk or to the start of the block device (partition or logical volume). I have the feeling it might be the latter one. Calling it on a bunch of files located on the same disk but in different partitions will tell.
The dumpe2fs command will report free blocks. Again it is specific to ext2/3/4 filesystems. Block numbers seem to be relative to the partition.
For at least your first question, it is possible in a filesystem-independent way. Copying from my answer to a serverfault question:
Unfortunately, I do not know of anything similar for the free space. I only know about
FITRIM
, which tells the underlying block device to discard the blocks corresponding to the free space of the filesystem.