Skip to content
systemcoding.dev
Kernels

The Complete Guide to Writing a Linux Filesystem Module

Write a Linux filesystem as a loadable module: file_system_type, the mount API, superblock, inodes, directories, page-cache I/O and a mount option, tested.

30 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and FreeBSD logos.

A Linux filesystem is a set of tables of functions and four data structures, and nearly everything the rest of the kernel does with files is expressed through them. The VFS (virtual filesystem switch) does the path walking, the permission checks, the caching of names and the bookkeeping for open files. A filesystem module supplies what the VFS cannot know: what an inode is on this filesystem, how names inside a directory are found, where a file's bytes live. This guide writes one from an empty directory. tinyfs is an in-memory filesystem modeled on the kernel's own ramfs, extended with two mount options, one of which caps the number of inodes. It is small enough to read in a sitting and complete enough to mount, create directories and files, read and write through the page cache, survive concurrent use and unmount cleanly. It targets Linux 6.12, and every interface named here exists in that release, which matters because the VFS interfaces change from one version to the next.

The VFS owns the hard parts. A first filesystem is mostly a decision about which libfs helpers to point at, and the skill is knowing what each helper assumes so that you notice the day an assumption stops being true.

What you will build, and what you need

tinyfs registers a filesystem type named tinyfs. After mount -t tinyfs none /mnt, the directory supports mkdir, touch, rmdir, unlink, rename, hard links, reading, writing, truncating and mmap. File data lives in the page cache and is never written anywhere, so everything disappears at unmount, exactly as with ramfs. Two options are parsed through the new mount API: mode= sets the permission bits of the root directory, and maxinodes= limits how many files and directories the mount may hold, answering ENOSPC beyond that. The second option exists to show the full path of an option from the mount command into filesystem state and back out through the error returned at the limit.

You need a virtual machine or a test machine, root access, the headers for the running kernel, GCC and make. A mistake in a filesystem module can corrupt the dentry cache or lock the machine, so use a disposable system. This filesystem has no on-disk format, so the risk to stored data is nil, but a bug can take the kernel down.

The guide has three parts. The first explains the objects and registers a filesystem type. The second fills in the mount path, the inodes and the operations, and tests the result. The third covers what changes for a filesystem that keeps data on a block device, how to test seriously, and when the right answer is not a kernel filesystem at all.

The VFS objects

Five structures carry all of the state, and every method in a filesystem takes one of them as its first argument.

ObjectOne perHolds
struct file_system_typeFilesystem typeName, flags, the function that starts a mount
struct super_blockMounted instanceBlock size, magic number, operations, root dentry, private data in s_fs_info
struct inodeFile, directory or other objectMode, size, owner, times, link count, operation tables, and an address_space for cached data
struct dentryName in a directoryThe name, the parent, the inode it resolves to; cached by the VFS
struct fileOpen file descriptionThe position, flags and a pointer to the file operations

Their relationships are what the rest of the guide implements. A mount creates one superblock. The superblock has a root dentry, and the root dentry points at the root inode. A lookup in a directory takes a dentry for a name and either attaches an inode to it (the name exists) or leaves it negative (the name does not). Opening a file creates a struct file that points at the dentry and through it at the inode. The inode's address_space is the page cache for the file's data, and its operations table tells the cache how to fill and flush pages.

Lifetimes follow reference counts. The VFS holds references while it uses an object, and the filesystem holds one more when it wants an object to outlive its callers. For a filesystem with no disk, a dentry or inode that is dropped from memory is lost for good, since nothing can reload it. That one fact explains the unusual line in the directory code later in this guide, where the module takes an extra reference on a new dentry to pin it.

Step 1: a filesystem type

A filesystem announces itself by registering a struct file_system_type. Its name is what users pass to mount -t, and its init_fs_context function is the entry point of a mount in the modern API. This is the whole of the registration:

tinyfs.cc
// SPDX-License-Identifier: GPL-2.0
#include <linux/fs.h>
#include <linux/fs_context.h>
#include <linux/fs_parser.h>
#include <linux/magic.h>
#include <linux/module.h>
#include <linux/pagemap.h>
#include <linux/seq_file.h>
#include <linux/slab.h>

#define TINYFS_MAGIC        0x54494e59	/* "TINY" */
#define TINYFS_DEFAULT_MODE 0755

static struct file_system_type tinyfs_fs_type = {
	.owner           = THIS_MODULE,
	.name            = "tinyfs",
	.init_fs_context = tinyfs_init_fs_context,
	.parameters      = tinyfs_fs_parameters,
	.kill_sb         = tinyfs_kill_sb,
	.fs_flags        = FS_USERNS_MOUNT,
};

static int __init tinyfs_init(void)
{
	return register_filesystem(&tinyfs_fs_type);
}

static void __exit tinyfs_exit(void)
{
	unregister_filesystem(&tinyfs_fs_type);
}

module_init(tinyfs_init);
module_exit(tinyfs_exit);

MODULE_DESCRIPTION("A small in-memory filesystem");
MODULE_LICENSE("GPL");

The functions named in the structure are defined in the following steps, and in the final file they come before the structure. .owner pins the module while any mount exists, so rmmod fails until the last unmount. .parameters lists the mount options the filesystem understands. .kill_sb runs when the last reference to a superblock goes away. FS_USERNS_MOUNT lets an unprivileged user mount the filesystem inside a user namespace, which is safe for tinyfs because it touches no device; leave it off for any filesystem that parses untrusted on-disk data.

After loading the module, the kernel's list of filesystems includes the new name:

Shell
sudo insmod tinyfs.ko
grep tinyfs /proc/filesystems
Text
nodev	tinyfs

The word nodev means no block device is required to mount it. A filesystem that mounts a device appears without that prefix.

Step 2: the mount API

Since Linux 5.2 the VFS mounts through a configuration object, struct fs_context. The mount(8) command, via the fsopen, fsconfig and fsmount system calls on modern systems, creates a context for the filesystem type, feeds it each option, and finally asks it to build the superblock. The filesystem hooks in through a table:

tinyfs.cc
struct tinyfs_fs_info {
	umode_t mode;
	unsigned int max_inodes;	/* 0 means no limit */
	atomic_t inodes;
};

enum tinyfs_param {
	Opt_mode,
	Opt_maxinodes,
};

static const struct fs_parameter_spec tinyfs_fs_parameters[] = {
	fsparam_u32oct("mode", Opt_mode),
	fsparam_u32("maxinodes", Opt_maxinodes),
	{}
};

static int tinyfs_parse_param(struct fs_context *fc, struct fs_parameter *param)
{
	struct tinyfs_fs_info *fsi = fc->s_fs_info;
	struct fs_parse_result result;
	int opt;

	opt = fs_parse(fc, tinyfs_fs_parameters, param, &result);
	if (opt == -ENOPARAM) {
		opt = vfs_parse_fs_param_source(fc, param);
		if (opt != -ENOPARAM)
			return opt;
		return invalfc(fc, "Unknown parameter '%s'", param->key);
	}
	if (opt < 0)
		return opt;

	switch (opt) {
	case Opt_mode:
		fsi->mode = result.uint_32 & S_IALLUGO;
		break;
	case Opt_maxinodes:
		fsi->max_inodes = result.uint_32;
		break;
	}
	return 0;
}

The parameter table is declarative. fsparam_u32oct("mode", Opt_mode) says that mode takes an octal integer, and fs_parse() does the conversion and the error reporting when the value is not a number. The result lands in result.uint_32. vfs_parse_fs_param_source() handles the source parameter that mount always passes (the none in mount -t tinyfs none /mnt); a filesystem that does not take a device accepts and ignores it. Anything else is an error, reported with invalfc(), which both logs a message into the context's log, where mount can print it, and returns -EINVAL. The ramfs driver ignores unknown options for historical compatibility; a new filesystem should reject them.

Once the options are parsed, get_tree builds the superblock, and free releases the context's private data if the mount did not consume it. The context operations and the entry point are:

tinyfs.cc
static int tinyfs_get_tree(struct fs_context *fc)
{
	return get_tree_nodev(fc, tinyfs_fill_super);
}

static void tinyfs_free_fc(struct fs_context *fc)
{
	kfree(fc->s_fs_info);
}

static const struct fs_context_operations tinyfs_context_ops = {
	.free        = tinyfs_free_fc,
	.parse_param = tinyfs_parse_param,
	.get_tree    = tinyfs_get_tree,
	.reconfigure = tinyfs_reconfigure,
};

static int tinyfs_init_fs_context(struct fs_context *fc)
{
	struct tinyfs_fs_info *fsi = kzalloc(sizeof(*fsi), GFP_KERNEL);

	if (!fsi)
		return -ENOMEM;
	fsi->mode = TINYFS_DEFAULT_MODE;
	atomic_set(&fsi->inodes, 0);
	fc->s_fs_info = fsi;
	fc->ops = &tinyfs_context_ops;
	return 0;
}

init_fs_context allocates the filesystem's private information and parks it in fc->s_fs_info, with defaults filled in, before any option is parsed. get_tree_nodev() creates a fresh, anonymous superblock for each mount, which is right for a filesystem with no device: two mounts of tinyfs are two independent trees. It takes fc->s_fs_info, hands it to the new superblock as sb->s_fs_info, and calls the fill_super function. The ownership transfer matters: once the superblock owns the structure, free_fc must not free it, and the mount code arranges that by clearing fc->s_fs_info. If the mount fails before that, free_fc runs and frees it. Study that rule until it is automatic, because ownership confusion in the mount path is the commonest source of leaks and double frees in new filesystems.

Step 3: filling in the superblock

fill_super initializes the superblock and creates the root directory. It is the first code that runs with a real struct super_block, and it sets the properties the VFS reads from then on:

tinyfs.cc
static int tinyfs_fill_super(struct super_block *sb, struct fs_context *fc)
{
	struct tinyfs_fs_info *fsi = sb->s_fs_info;
	struct inode *root;

	sb->s_maxbytes      = MAX_LFS_FILESIZE;
	sb->s_blocksize     = PAGE_SIZE;
	sb->s_blocksize_bits = PAGE_SHIFT;
	sb->s_magic         = TINYFS_MAGIC;
	sb->s_op            = &tinyfs_ops;
	sb->s_time_gran     = 1;

	root = tinyfs_get_inode(sb, NULL, S_IFDIR | fsi->mode, 0);
	if (!root)
		return -ENOMEM;

	sb->s_root = d_make_root(root);
	if (!sb->s_root)
		return -ENOMEM;
	return 0;
}

Each field has a reason. s_maxbytes bounds the size of a file, and MAX_LFS_FILESIZE is the largest the page cache's index space can address. s_blocksize and its bit count describe the unit that st_blksize and the statfs numbers use; for an in-memory filesystem the page is the natural block. s_magic is the value statfs reports as the filesystem type, and stat -f prints it. s_op points to the superblock operations in Step 7. s_time_gran of 1 says timestamps have nanosecond resolution, because the inode times are stored in memory with no format to constrain them. Finally, the root directory is made by the same function that makes every inode, and d_make_root() wraps it in a dentry and returns it, or returns NULL and drops the inode if it cannot. It consumes the inode reference in both cases, so the code does not call iput() itself.

Teardown has a matching hook. When the last reference to the superblock is dropped, kill_sb is called, and for an in-memory filesystem it has two jobs: free the private information, and let the generic code shut the tree down:

tinyfs.cc
static void tinyfs_kill_sb(struct super_block *sb)
{
	struct tinyfs_fs_info *fsi = sb->s_fs_info;

	kill_litter_super(sb);
	WARN_ON(atomic_read(&fsi->inodes) != 0);
	kfree(fsi);
}

kill_litter_super() is the helper for filesystems whose dentries are pinned (the "litter" is the extra references that keep dentries alive), and it releases them so that the tree can be freed. The order of the three steps is not optional. Killing the superblock evicts every inode, and eviction runs tinyfs_evict_inode, which reads s_fs_info, so the private structure must still exist while the helper runs. Only after every inode is gone can the counter be checked and the structure freed. The kernel's own ramfs frees first and kills second because its eviction path never touches the structure; copying that order into a filesystem that does touch it is a use after free. The WARN_ON is a cheap leak detector: any creation path that fails to release an inode leaves the counter above zero, and the unmount says so.

Step 4: inodes

Every file and directory is an inode, and one function creates them all. It allocates an inode with new_inode(), fills in the common fields, and chooses the operation tables by file type:

tinyfs.cc
static const struct super_operations tinyfs_ops;
static const struct inode_operations tinyfs_dir_inode_operations;
static const struct inode_operations tinyfs_file_inode_operations = {
	.setattr = simple_setattr,
	.getattr = simple_getattr,
};
static const struct file_operations tinyfs_file_operations = {
	.read_iter   = generic_file_read_iter,
	.write_iter  = generic_file_write_iter,
	.mmap        = generic_file_mmap,
	.fsync       = noop_fsync,
	.splice_read = filemap_splice_read,
	.splice_write = iter_file_splice_write,
	.llseek      = generic_file_llseek,
};

static struct inode *tinyfs_get_inode(struct super_block *sb,
				      const struct inode *dir, umode_t mode,
				      dev_t dev)
{
	struct tinyfs_fs_info *fsi = sb->s_fs_info;
	struct inode *inode;

	if (fsi->max_inodes &&
	    atomic_inc_return(&fsi->inodes) > fsi->max_inodes) {
		atomic_dec(&fsi->inodes);
		return NULL;
	}
	if (!fsi->max_inodes)
		atomic_inc(&fsi->inodes);

	inode = new_inode(sb);
	if (!inode) {
		atomic_dec(&fsi->inodes);
		return NULL;
	}

	inode->i_ino = get_next_ino();
	inode_init_owner(&nop_mnt_idmap, inode, dir, mode);
	inode->i_mapping->a_ops = &ram_aops;
	mapping_set_gfp_mask(inode->i_mapping, GFP_HIGHUSER);
	mapping_set_unevictable(inode->i_mapping);
	simple_inode_init_ts(inode);

	switch (mode & S_IFMT) {
	case S_IFREG:
		inode->i_op = &tinyfs_file_inode_operations;
		inode->i_fop = &tinyfs_file_operations;
		break;
	case S_IFDIR:
		inode->i_op = &tinyfs_dir_inode_operations;
		inode->i_fop = &simple_dir_operations;
		inc_nlink(inode);	/* a directory counts its own "." entry */
		break;
	default:
		init_special_inode(inode, mode, dev);
		break;
	}
	return inode;
}

The counter logic at the top is the inode limit. When maxinodes is set, the increment and the comparison happen in one atomic step, so two concurrent creators cannot both slip past the limit; the loser undoes its increment and returns NULL, which the callers turn into ENOSPC. The !max_inodes branch keeps the count accurate when there is no limit, so that the count can be reported either way.

The fields that follow are the VFS's expectations. get_next_ino() provides a unique inode number per boot, which is enough for a filesystem that cannot be remounted and keep its contents. inode_init_owner() sets the user and group from the current credentials, and inherits the group and setgid bit from a parent directory when there is one. The address_space gets ram_aops, the operations the kernel exports for memory-backed pages: they let the page cache create zero-filled pages on a write and never try to write them anywhere. mapping_set_gfp_mask() and mapping_set_unevictable() say that the pages may come from high memory and must not be reclaimed or swapped, since there is no other copy; that is what makes tinyfs, like ramfs, unable to shed memory under pressure, and why the inode limit is a safety feature and not only a demonstration. A regular file gets the file inode operations and the file operations in the table; a directory gets its own tables and simple_dir_operations, which implements readdir from the dentry cache; anything else (device nodes, FIFOs, sockets) is handed to init_special_inode(), which the VFS post of this series explains.

The file operations are almost entirely generic. generic_file_read_iter() and generic_file_write_iter() implement read(2) and write(2) through the page cache and call back into the address_space operations. generic_file_mmap() maps the cached pages. noop_fsync() makes fsync succeed immediately, since there is nothing to flush. generic_file_llseek() handles seeking against i_size. A filesystem with a disk replaces fsync and the address space operations, and keeps most of the rest.

Step 5: directories

A directory is a set of operations on dentries, and libfs supplies nearly all of them for a filesystem that keeps its names in the dentry cache, which is the entire design of an in-memory filesystem: the directory entries are the dentries, and there is no other copy.

tinyfs.cc
static int tinyfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
			struct dentry *dentry, umode_t mode, dev_t dev)
{
	struct inode *inode = tinyfs_get_inode(dir->i_sb, dir, mode, dev);

	if (!inode)
		return -ENOSPC;

	d_instantiate(dentry, inode);
	dget(dentry);		/* pin it: the dentry cache is the directory */
	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
	return 0;
}

static int tinyfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
			struct dentry *dentry, umode_t mode)
{
	int ret = tinyfs_mknod(idmap, dir, dentry, mode | S_IFDIR, 0);

	if (!ret)
		inc_nlink(dir);	/* the new directory's ".." */
	return ret;
}

static int tinyfs_create(struct mnt_idmap *idmap, struct inode *dir,
			 struct dentry *dentry, umode_t mode, bool excl)
{
	return tinyfs_mknod(idmap, dir, dentry, mode | S_IFREG, 0);
}

static const struct inode_operations tinyfs_dir_inode_operations = {
	.create = tinyfs_create,
	.lookup = simple_lookup,
	.link   = simple_link,
	.unlink = simple_unlink,
	.mkdir  = tinyfs_mkdir,
	.rmdir  = simple_rmdir,
	.mknod  = tinyfs_mknod,
	.rename = simple_rename,
};

Read tinyfs_mknod as the template for every creation. The VFS has already looked the name up and holds a negative dentry for it, and passes it in. The filesystem creates an inode, attaches it with d_instantiate() and updates the directory's times. The dget() is the line that makes an in-memory filesystem possible: it takes an extra reference on the dentry so that the dcache never evicts it. Without it, memory pressure would drop the dentry, the file would vanish from its directory, and nothing could bring it back because there is no disk to reload it from. simple_unlink() drops that extra reference, which is the other half of the pair. Every creator pins and every remover unpins, and a leak in either direction either makes files disappear or makes memory stay allocated after unlink.

simple_lookup() handles the "name not found" case: the VFS asks the filesystem to look up a name, and for a filesystem whose dentries are all pinned, an unpinned negative dentry is the answer, so the helper marks the dentry as always-valid-negative and returns. simple_link, simple_rmdir and simple_rename implement hard links, directory removal and rename in terms of the dentry cache and the link counts. simple_rmdir first calls simple_empty() and returns ENOTEMPTY if the directory has children. They all assume exactly what tinyfs is: names live in the dcache and nowhere else. Take one more step in design and the assumption breaks, which is the subject of the block-backed section later.

The mkdir increments the parent's link count because the new directory's .. entry refers to it, and tinyfs_get_inode already counted the new directory's own .. These counts are what ls -ld shows and what rmdir and find rely on, and a mistake in them is visible as a wrong number in the second column of a directory listing.

Step 6: file I/O through the page cache

No code in this step needs writing, which is itself the lesson. A write follows this path: write(2) reaches generic_file_write_iter(), which, for each page of the range, asks the address space to prepare the page with write_begin, copies the user data into it and calls write_end. With ram_aops those operations are simple_write_begin and simple_write_end, which allocate a zero-filled page if the file did not have one, and mark it dirty and update the file size. The dirty flag is noop_dirty_folio: nothing will ever clean the page, so tracking it is pointless. A read finds the page in the cache and copies it out; a hole in a sparse file reads as zeros because read_folio is simple_read_folio, which fills the page with zeros when it is not present.

Truncation goes through setattr. simple_setattr() updates the inode's attributes and, for a size change, calls truncate_setsize(), which drops the pages beyond the new end. So truncate -s 0 file frees the memory, and unlink frees it when the last reference goes, through evict_inode below. The memory is visible in free as buff/cache, and cannot be reclaimed, which is the practical difference between ramfs and tmpfs: tmpfs can swap its pages and enforces a size limit, and this filesystem does neither. The maxinodes option is the only brake.

Step 7: the superblock operations

The superblock operations table is the filesystem's hooks for whole-filesystem events. tinyfs needs four:

tinyfs.cc
static void tinyfs_evict_inode(struct inode *inode)
{
	struct tinyfs_fs_info *fsi = inode->i_sb->s_fs_info;

	truncate_inode_pages_final(&inode->i_data);
	clear_inode(inode);
	atomic_dec(&fsi->inodes);
}

static int tinyfs_show_options(struct seq_file *m, struct dentry *root)
{
	struct tinyfs_fs_info *fsi = root->d_sb->s_fs_info;

	if (fsi->mode != TINYFS_DEFAULT_MODE)
		seq_printf(m, ",mode=%o", fsi->mode);
	if (fsi->max_inodes)
		seq_printf(m, ",maxinodes=%u", fsi->max_inodes);
	return 0;
}

static const struct super_operations tinyfs_ops = {
	.statfs        = simple_statfs,
	.drop_inode    = generic_delete_inode,
	.evict_inode   = tinyfs_evict_inode,
	.show_options  = tinyfs_show_options,
};

generic_delete_inode as drop_inode tells the VFS that an inode with no remaining references should be evicted immediately and not kept in the inode cache, because there is nothing to write back and no reason to cache a file that has no name. Eviction calls evict_inode, which has a fixed job for any filesystem: truncate_inode_pages_final() throws away the file's cached pages, clear_inode() marks the inode as dead for the VFS's state machine, and then the filesystem releases its own bookkeeping, here the inode count. This is where the pages of a deleted file go back to the system. simple_statfs() fills in the numbers that df shows, using the generic values for a memory-backed filesystem. show_options is how options reach /proc/mounts and findmnt, and a filesystem that parses an option and does not show it leaves administrators guessing what a mount was given.

Step 8: build, load, mount and use

The Makefile is the same one-file Kbuild form as the other modules in this series. Build, load and mount with both options:

Shell
make
sudo insmod tinyfs.ko
sudo mkdir -p /mnt/tiny
sudo mount -t tinyfs -o mode=0700,maxinodes=5 none /mnt/tiny
findmnt /mnt/tiny
ls -ld /mnt/tiny
Text
TARGET    SOURCE FSTYPE  OPTIONS
/mnt/tiny none   tinyfs  rw,relatime,mode=700,maxinodes=5
drwx------ 2 root root 40 Nov 23 16:10 /mnt/tiny

The options column shows what show_options printed. The root directory is drwx------, because mode=0700 was parsed and applied in fill_super. Now use the filesystem up to its limit. The root directory is one inode, so four more fit:

Shell
cd /mnt/tiny
sudo mkdir a
sudo touch a/f1 a/f2 a/f3
sudo touch a/f4
ls -R .
Text
touch: cannot touch 'a/f4': No space left on device
.:
a

./a:
f1  f2  f3

The root plus a, f1, f2 and f3 make five inodes, so the sixth creation hit the limit and tinyfs_mknod returned -ENOSPC, which touch printed with the system's message. Free one and the limit lifts, which proves the accounting in evict_inode is balanced:

Shell
sudo rm a/f1
sudo touch a/f4
ls a
Text
f2  f3  f4

Test real file I/O, hard links, rename and the page cache through the usual tools:

Shell
echo "hello tinyfs" | sudo tee a/f2
sudo ln a/f2 a/f2.link
sudo mv a/f3 a/g3
stat -c '%h links, %s bytes' a/f2
cat a/f2.link
Text
hello tinyfs
2 links, 13 bytes
hello tinyfs

The hard link succeeded at the limit because link creates no inode, only a second name for an existing one, so it does not touch the counter. A result where the link failed would mean the limit counted names and not inodes.

Shell
stat -f -c 'type=%T bsize=%S' /mnt/tiny
Text
type=tinyfs bsize=4096

(stat -f prints the type name only if it recognizes the magic number; for an unknown one it prints UNKNOWN (0x54494e59), and the block size comes from s_blocksize.) Unmount and unload in the right order:

Shell
cd /
sudo umount /mnt/tiny
sudo rmmod tinyfs

The unmount drops every pinned dentry through kill_litter_super(), which evicts every inode and frees every page. If the unmount fails with target is busy, a shell or process still has its working directory in the mount, as the cd / above avoids. rmmod succeeds only after the last unmount, because .owner holds the module.

Watching the VFS call your code

Two tools show the machinery working. On a system whose mount uses the new API (util-linux 2.39 and later), strace shows it as a sequence of calls that map onto the functions above:

Shell
sudo strace -e trace=fsopen,fsconfig,fsmount,move_mount mount -t tinyfs -o maxinodes=5 none /mnt/tiny 2>&1 | head -n 6
Text
fsopen("tinyfs", FSOPEN_CLOEXEC)        = 3
fsconfig(3, FSCONFIG_SET_STRING, "source", "none", 0) = 0
fsconfig(3, FSCONFIG_SET_STRING, "maxinodes", "5", 0) = 0
fsconfig(3, FSCONFIG_CMD_CREATE, NULL, NULL, 0) = 0
fsmount(3, FSMOUNT_CLOEXEC, 0)          = 4
move_mount(4, "", AT_FDCWD, "/mnt/tiny", MOVE_MOUNT_F_EMPTY_PATH) = 0

fsopen is init_fs_context, each fsconfig that sets a string is a call into parse_param, FSCONFIG_CMD_CREATE is get_tree and with it fill_super, and fsmount and move_mount attach the finished superblock to a path. A mount with a bad option fails at the second fsconfig, and the message invalfc() logged is what mount prints:

Text
mount: /mnt/tiny: wrong fs type, bad option, bad superblock on none, missing codepage or helper program, or other error.
dmesg(1) may have more information after failed mount system call.

The kernel's log has the specific line, tinyfs: Unknown parameter 'bogus', in recent versions through the filesystem context log, which newer mount tools show directly. The generic message is the one old mount binaries print for every failure, and it is not a sign that the filesystem is broken.

The second tool is the function tracer. After echo 'tinyfs_*' > /sys/kernel/tracing/set_ftrace_filter and echo function_graph > /sys/kernel/tracing/current_tracer, a touch in the mount shows tinyfs_create calling tinyfs_mknod and tinyfs_get_inode, nested as the code reads. Seeing the real call chain once is worth more than any description of it.

Locking: what the VFS does for you

A filesystem method is called with locks the VFS has already taken, and the rules of which are part of the interface. For a directory operation such as create, unlink or rename, the VFS holds the parent directory's i_rwsem exclusively, so the method does not need its own lock to keep two creations in one directory from racing. lookup is called with the lock held shared. Rename takes the locks of both directories in a defined order (and a per-superblock lock for cross-directory moves) so that two renames cannot deadlock against each other. For file data, generic_file_write_iter() takes the inode's lock exclusively around the write, and readers need none.

What the VFS does not protect is anything the filesystem keeps outside those structures. The inode counter in tinyfs_fs_info is shared by every directory in the mount, so it uses an atomic. A filesystem with a global free-space bitmap needs a lock for it, taken inside the directory lock, and the order of those two locks becomes a rule the whole module follows. Document the order, and let lockdep confirm it: a kernel built with CONFIG_PROVE_LOCKING reports inverted lock orders the first time both paths run, even without an actual deadlock.

Changing options on a live mount

mount -o remount,maxinodes=100 /mnt/tiny changes an option without unmounting. In the mount API that is the reconfigure operation, which receives a context holding the new options and applies them to the existing superblock. A filesystem that does not implement it rejects every remount, which is why mount -o remount,ro fails on such filesystems with a generic error. The method for tinyfs is short, and the care is in what it must refuse:

tinyfs.cc
static int tinyfs_reconfigure(struct fs_context *fc)
{
	struct tinyfs_fs_info *new = fc->s_fs_info;
	struct tinyfs_fs_info *cur = fc->root->d_sb->s_fs_info;

	sync_filesystem(fc->root->d_sb);

	if (new->max_inodes && new->max_inodes < atomic_read(&cur->inodes))
		return invalfc(fc, "maxinodes is below the %d inodes in use",
			       atomic_read(&cur->inodes));

	cur->max_inodes = new->max_inodes;
	return 0;
}

During a remount, the context's private information holds only the options given on this command, parsed by the same parse_param, so the method reads them from fc->s_fs_info and applies the ones it supports to the superblock's own structure, found through fc->root. Lowering the limit below the number of inodes already in use is refused with a message: accepting it would leave the filesystem over its own limit, and the next creation would fail in a way that looks like a bug. The mode option cannot change on a remount, since the root directory already exists with its mode, and the method ignores it; a filesystem that wants to be strict rejects options it cannot apply, with invalfc(). Add .reconfigure = tinyfs_reconfigure to the context operations, and the remount works:

Shell
sudo mount -o remount,maxinodes=100 /mnt/tiny
findmnt -no OPTIONS /mnt/tiny
sudo mount -o remount,maxinodes=1 /mnt/tiny
Text
rw,relatime,mode=700,maxinodes=100
mount: /mnt/tiny: mount point not mounted or bad option.

The second remount fails because the mount holds more than one inode, and the reason is in the kernel log. Note the effect of sync_filesystem(): a remount must make the filesystem consistent before changing state, and for a disk filesystem this writes everything out. For tinyfs it does nothing, and the call documents the intent.

The directory operations above leave out symbolic links. Adding them takes one more method and an inode type, because libfs can store a link target in the page cache like file data. The method creates a link inode and writes the target string through page_symlink():

tinyfs.cc
static int tinyfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
			  struct dentry *dentry, const char *target)
{
	struct inode *inode;
	int ret;

	inode = tinyfs_get_inode(dir->i_sb, dir, S_IFLNK | S_IRWXUGO, 0);
	if (!inode)
		return -ENOSPC;

	ret = page_symlink(inode, target, strlen(target) + 1);
	if (ret) {
		iput(inode);		/* undo the inode and its count */
		return ret;
	}
	d_instantiate(dentry, inode);
	dget(dentry);
	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
	return 0;
}

In tinyfs_get_inode, a new case S_IFLNK: sets inode->i_op = &page_symlink_inode_operations and calls inode_nohighmem(inode), as ramfs does, so that following the link reads the stored string from the page cache. Note the iput() on the failure path, which is the cleanup the previous section's table warned about: it triggers evict_inode, which returns the inode to the counter. The method goes into the directory operations table as .symlink.

Extended attributes follow the same pattern of reusing the generic machinery. A filesystem that wants user. attributes stores them with simple_xattrs, a small helper that keeps a list per inode, and wires the listxattr and handler table. Access control lists need the POSIX ACL helpers and a handful of inode operations. Each feature is a decision to add code that must be tested under xfstests, which has groups for exactly these (attr, acl), so add features when you need them and not by default.

What changes when there is a disk

tinyfs is the simplest case because the dentry cache is the directory and the page cache is the data. A filesystem on a block device keeps the same VFS objects and replaces nearly every piece underneath them. The mapping is direct enough to tabulate:

tinyfsA block-backed filesystem such as ext2
get_tree_nodev()get_tree_bdev(), which opens the device and passes it to fill_super
fill_super builds a root inode in memoryfill_super reads the on-disk superblock with sb_bread(), validates it, and reads the root inode from the inode table
tinyfs_get_inode makes an inode from nothingThe filesystem reads an on-disk inode and converts it; creating one allocates a bit in an inode bitmap
ram_aopsReal read_folio, writepages and write_begin that map file offsets to disk blocks through a block map or extent tree
dget() pins every dentryDentries are disposable; lookup reads the directory blocks to find a name
simple_unlink and friendsReal implementations that edit directory blocks, update link counts on disk and free blocks
noop_fsyncfsync writes dirty data and metadata and issues a device flush
evict_inode frees memoryevict_inode frees the inode on disk if its link count is zero
No recoveryJournaling or an fsck tool, and a crash-consistency story

The largest change is trust. The bytes of a disk are input from outside the system, written by earlier versions of the code, by other operating systems, by corruption, or by an attacker who handed over a crafted image. Every field read from disk must be validated before it is used as an index, a size or a pointer, and a filesystem that mounts untrusted images, such as removable media, is a security boundary. That is why FS_USERNS_MOUNT appears on tinyfs and not on ext4. The second change is durability: ordering writes so that a crash leaves a consistent state, with a journal or careful ordering and device flushes, is most of the engineering effort in a disk filesystem, and nothing in tinyfs prepares you for it. The third is that on-disk formats are forever. A format shipped is a format that every future version must read, with explicit byte order, version fields and feature flags.

If you want to continue from here, read fs/ext2/ in the kernel tree with this guide's table open: ext2_fill_super, ext2_iget, ext2_create and the ext2_aops table correspond one to one with the pieces above, and ext2 has no journal to obscure them.

Testing a filesystem

Mounting and creating a few files is a smoke test. Filesystems fail under stress, under concurrency and in the corners of POSIX semantics, and the kernel community has tools for each.

xfstests (also called fstests) is the standard regression suite for filesystems, with hundreds of tests of POSIX behavior, error handling and stress. The generic group is written to run on any filesystem. Add a stanza for tinyfs to its configuration and run ./check -g quick; tests that need a block device or features the filesystem lacks are skipped, and those that fail are real findings. fsstress and fsx, which ship with it, run random operations against a mount and compare the results with a model, and they are the tools that find the race between a rename and a lookup that a person would never write a test for. pjdfstest checks POSIX conformance of individual calls, for example that rename over a non-empty directory fails with ENOTEMPTY.

Run all of them on a kernel with lockdep, KASAN and DEBUG_ATOMIC_SLEEP enabled, and with CONFIG_FAILSLAB and fault injection turned on so that allocation failures exercise the -ENOMEM paths that otherwise never run. A directory operation that leaks an inode on failure shows up as a nonzero inode count after the final unmount, so tinyfs can assert at unmount time, in kill_sb, that atomic_read(&fsi->inodes) is zero and warn if not. That one assertion catches a whole class of reference-counting bugs in the creation paths.

Failures and where they come from

SymptomLikely cause
mount: unknown filesystem type 'tinyfs'Module not loaded; the name is not in /proc/filesystems
mount: wrong fs type, bad optionparse_param rejected an option; check dmesg or the mount tool's log output
Files disappear under memory pressuredget() missing in the creation path, so the dcache evicted the dentry
Memory not freed after rmMissing simple_unlink() or evict_inode that does not call truncate_inode_pages_final()
rmdir: Directory not empty on an empty directoryChild dentries leaked, or link counts wrong
Oops at unmounts_fs_info freed twice, or an inode outlived the superblock
rmmod: Module tinyfs is in useA mount still exists; unmount it first
ls -l shows wrong link countsMismatch in inc_nlink for mkdir or in . and .. accounting
Inode count nonzero at unmountA creation path that returns an error after tinyfs_get_inode without calling iput

The last row gives away the most instructive bug in this driver. In tinyfs_mknod as written there is no error path after the inode is made, but add one, for instance a call that can fail between tinyfs_get_inode() and d_instantiate(), and the correct cleanup is iput(inode), which triggers evict_inode and decrements the counter. Forgetting it leaks the inode and its slot in the limit.

When a kernel filesystem is the wrong tool

Writing a filesystem in the kernel is a long commitment with a large blast radius. Most needs have a smaller answer, and the cases below say which.

You want a filesystem interface to your own data or service. FUSE lets a user-space program implement the operations, with a debugger, any language and no risk to the kernel, at the cost of a context switch per operation. It is the right answer for network and cloud filesystems, archive mounts and prototypes.

You want to expose kernel state as files. sysfs, debugfs, configfs and procfs exist for this, and kernfs, seq_file and simple_fill_super make a tiny pseudo-filesystem for an in-kernel subsystem a few dozen lines. Debugfs in particular is the right place for developer-facing files that are not ABI.

You want memory-backed storage. tmpfs does what tinyfs does with swapping, size limits and extended attributes, and has been through decades of use. Use it.

You want layered or merged views. overlayfs and bind mounts compose existing trees.

You want encryption, compression or integrity on top of an existing filesystem. fscrypt, fsverity and the filesystems' own features exist, and a block-level device-mapper target is another route.

You want a new on-disk layout for a real workload. Then you are writing a filesystem for real, and the honest first step is reading how ext4, xfs, btrfs, f2fs and bcachefs solved allocation, journaling and recovery, and asking whether one of them, tuned, already does what you need. If none does, plan for years of maintenance, a test suite and an upstream review.

A tiny in-memory filesystem like this one is mostly a learning exercise, and a useful one: it is the shortest path to understanding what every other filesystem does with the same five objects.

The finished module, in file order

Arranged so that every name is defined before it is used, tinyfs.c is: includes and constants; the private-information structure and the parameter enumeration and table; the superblock operations table declarations; the inode and file operation tables; tinyfs_get_inode; the directory functions and their table; the superblock operations and evict_inode; fill_super; the context operations and parse_param; init_fs_context and kill_sb; the file_system_type; and the init and exit functions with the module metadata. Forward declarations of the three tables that refer to later functions (tinyfs_ops, tinyfs_dir_inode_operations and tinyfs_fs_parameters) keep the order workable.

The unmount-time check and the ordering explained in Step 3 are part of this final form: kill_sb kills the superblock first, checks the inode count, then frees the private structure.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.