Linux – limit the maximum size of file in ext4 filesystem

ext4filesystemslinux

Ext4 has a maximum filesystem size of 1EB and maximum filesize of 16TB.

However is it possible to make the maximum filesize smaller at filesystem level ? For example I wouldn't like to allow to create files greater than a specified value (e.g. 1MB). How can this be achieved on ext4 ?

If not ext4 then any other modern filesystem has support for such feature ?

Best Answer

ext4 has a max_dir_size_kb mount option to limit the size of directories, but no similar option for regular files.

A process however can be prevented from creating a file bigger than a limit using limits as set by setrlimit() or the ulimit or limit builtin of some shells. Most systems will also let you set those limits system-wide, per user.

When a process exceeds that limit, it receives a SIGXFSZ signal. And when it ignores that signal, the operation that would have caused that file size to be exceeded (like a write() or truncate() system call) fails with a EFBIG error.

To move that limit to the file system, one trick you could do is use a fuse (file system in user space) file system, where the user space handler is started with that limit set. bindfs is a good candidate for that.

If you run bindfs dir dir (that is bind dir over itself), with bindfs started as (zsh syntax):

(limit filesize 1M; trap '' XFSZ; bindfs dir dir)

Then any attempt to create a file bigger than 1M in that dir will fail. bindfs forwards the EFBIG error to the process writing the file.

Note that that limit only applies to regular files, that won't stop directories to grow past that limit (for instance by creating a large number of files in them).

Related Question