Skip to content
systemcoding.dev
Kernels

Create a read-only seq_file in one line with DEFINE_SHOW_ATTRIBUTE

Turn one show function into a complete read-only debugfs file with DEFINE_SHOW_ATTRIBUTE() in Linux 6.12, with no hand-written file_operations.

2 min read
Summarize in AI

Most read-only status files need the same five lines of file_operations boilerplate: open, read, llseek, release. DEFINE_SHOW_ATTRIBUTE(name) generates all of it from a single name_show() function, so a whole file is the show function plus one line. The macro lives in linux/seq_file.h and works in Linux 6.12.

hello.cc
#include <linux/debugfs.h>
#include <linux/module.h>
#include <linux/seq_file.h>

static int hello_show(struct seq_file *m, void *v)
{
	seq_printf(m, "boards: %d\n", 3);
	return 0;
}
DEFINE_SHOW_ATTRIBUTE(hello);

static struct dentry *file;

static int __init hello_init(void)
{
	file = debugfs_create_file("hello", 0444, NULL, NULL, &hello_fops);
	return 0;
}

static void __exit hello_exit(void)
{
	debugfs_remove(file);
}

module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
Text
boards: 3

The macro pastes the name you give it onto three symbols: it expects hello_show(), and it defines hello_open() and hello_fops. The fourth argument of debugfs_create_file() arrives as m->private inside the show function, because the generated open passes inode->i_private to single_open().

The catch is /proc. Since Linux 5.6, proc_create() takes a struct proc_ops, not a file_operations, so this macro does not fit there. Use DEFINE_PROC_SHOW_ATTRIBUTE(name), which generates name_proc_ops, or skip the macro with proc_create_single(). The seq_file model is described in the kernel docs.

Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.