
Recall first from Misc devices and sysfs
- A misc device is a character driver on major 10 with a dynamically assigned minor, registered with one misc_register call.
- sysfs turns kernel objects into directories and attributes into files, one value per file, read with cat and written with echo.
- misc_register creates the cdev, the class entry and the device node in one call, but the cdev behind it belongs to the misc core, so open must recover the device another way
debugfs: a filesystem for debugging
4 min readThe previous lesson showed sysfs as a stable interface for exposing device state. This lesson answers how to expose development-only debug data and what keeps sysfs objects alive while they are used.
debugfs is the opposite of sysfs in one respect: it promises nothing. The debugfs documentation states plainly that its contents are not a stable interface, may change or vanish between kernel versions, and must never be relied on by a shipped program. In exchange, it is effortless to use, and you can break it without breaking anyone.
The filesystem is usually mounted at /sys/kernel/debug. If your initramfs does not mount it, do so by hand:
mount -t debugfs none /sys/kernel/debug
The API lives in <linux/debugfs.h>. Create a directory for your module, then fill it with files:
#include <linux/debugfs.h>
static struct dentry *dbg_dir;
/* in init */
dbg_dir = debugfs_create_dir("mychar", NULL);
debugfs_create_u32("write_count", 0444, dbg_dir, &write_count);
debugfs_create_x32("last_command", 0444, dbg_dir, &last_cmd);
debugfs_create_u32 makes a file that prints a u32 in decimal; debugfs_create_x32 prints it in hexadecimal. There are variants for u8, u16 and u64, and a debugfs_create_bool for a yes/no flag. Pass the address of the value, and debugfs reads it live each time, so the file always shows the current value with no code from you. A writable mode lets a user change the pointed value directly, which is handy for a quick knob but dangerous for a value your driver also changes.
For anything with real behaviour, such as a get/set pair with validation, define your own file operations with DEFINE_SIMPLE_ATTRIBUTE:
static int mychar_size_get(void *data, u64 *val)
{
*val = mychar.size;
return 0;
}
static int mychar_size_set(void *data, u64 val)
{
if (val > MYCHAR_CAP)
return -EINVAL;
mychar.size = val;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(mychar_size_fops,
mychar_size_get, mychar_size_set, "%llu\n");
/* in init */
debugfs_create_file("size", 0644, dbg_dir, NULL, &mychar_size_fops);
The get function receives a u64 * to fill, the set receives a u64 to check and store, and the format string prints the value. DEFINE_SIMPLE_ATTRIBUTE generates the file_operations that glue a read and a write to those two functions.
To tear everything down, remove the directory and its contents in one call:
/* in exit */
debugfs_remove_recursive(dbg_dir);
Going deeperSafe and unsafe debugfs files
debugfs_create_file returns a file that is safe to remove while a process has it open. It does this by wrapping your file_operations in a proxy layer, so an open file keeps working even after the dentry is gone. The proxy costs an indirection, so the kernel also provides debugfs_create_file_unsafe, which registers your fops directly with no proxy. Use the unsafe variant only when you can guarantee the file is never removed while open, such as a file that exists for the whole lifetime of the module and is removed only at unload after every client has closed. For DEFINE_SIMPLE_ATTRIBUTE files, the safe variant is the right default, because removing an in-use simple-attribute file through the unsafe path can race with a concurrent read.
Choosing between sysfs and debugfs comes down to one question: does anything outside your own development depend on this value? If a shipped program, a script, or another engineer's tool reads it, it belongs in sysfs, with the discipline that implies. If it is a counter you watch while bringing up a board, or a knob you turn during debugging, it belongs in debugfs, where it can be ugly and temporary.
Embedded products often strip debugfs entirely. If the kernel is built without CONFIG_DEBUG_FS, the files simply never exist, and a product that depended on them breaks. This is the practical version of the rule: a board image for the field should not need debugfs, and a driver must never require it to function. Keep the counters in debugfs and the real interface in sysfs or ioctl, and you can compile debugfs away for the release without touching your driver's logic.
Binary attributes and seq_file
3 min readsysfs attributes are text and one value per file, which is perfect for a size or a flag but wrong for two other needs: a large block of raw data, and a report longer than a page.
For raw data, use a a sysfs attribute that reads and writes bulk binary data through file offsets, bypassing the one-value text convention. It is a struct bin_attribute with read and write methods that look like file operations:
static ssize_t cal_read(struct file *file, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t off, size_t count)
{
return memory_read_from_buffer(buf, count, &off, cal_data, CAL_SIZE);
}
static struct bin_attribute cal_attr = {
.attr = { .name = "calibration", .mode = 0644 },
.size = CAL_SIZE,
.read = cal_read,
};
/* in init */
sysfs_create_bin_file(&some_kobj, &cal_attr);
memory_read_from_buffer and its write counterpart copy a region of kernel memory to or from user space, honouring the offset and count. The size field advertises how big the data is. Register with sysfs_create_bin_file and remove with sysfs_remove_bin_file. This is the right tool for a calibration table, a firmware blob, or a register dump that does not belong in a text file.
For long reports, use the kernel's iterator interface for generating large virtual files, which handles seeking and paging so a read works no matter how long the output is. A show function prints lines, and seq_file manages the buffer, the position and partial reads for you:
#include <linux/seq_file.h>
static int mychar_show(struct seq_file *m, void *v)
{
seq_printf(m, "size: %zu\n", mychar.size);
seq_printf(m, "capacity: %u\n", MYCHAR_CAP);
seq_printf(m, "writes: %u\n", write_count);
seq_printf(m, "reads: %u\n", read_count);
return 0;
}
DEFINE_SHOW_ATTRIBUTE(mychar);
/* in init */
debugfs_create_file("stats", 0444, dbg_dir, NULL, &mychar_fops);
DEFINE_SHOW_ATTRIBUTE(mychar) generates a file_operations table named mychar_fops from your mychar_show function, wiring up seq_read and seq_lseek so that cat and less both work no matter how many lines the report holds. The older spelling of the same thing is an explicit single_open in an open method plus single_release; the macro writes that boilerplate for you.
Both tools exist because the one-value text file is deliberately limited. When you find yourself tempted to make a sysfs file whose show prints dozens of lines, or whose store parses a blob, stop. Reach for seq_file in debugfs for the report, or a binary attribute for the blob, and keep sysfs boring.
kobject lifecycle, kref and uevents
5 min readEvery kobject is reference counted. That count is what makes device removal safe: the object is not freed while a driver, a file, or a sysfs reader still holds a pointer to it. The pieces are small but the discipline is exact.
The the kernel's reference counter, a small integer that tracks how many users hold a pointer to an object inside a kobject starts at one when you initialise the object. Each new user of the object takes a reference with kobject_get, and each user that is finished drops one with kobject_put. When the count reaches zero, the kernel calls a function you supplied to free the object.
The lifecycle functions are:
void kobject_init(struct kobject *kobj, struct kobj_type *ktype);
int kobject_add(struct kobject *kobj, struct kobject *parent,
const char *fmt, ...);
int kobject_init_and_add(struct kobject *kobj, struct kobj_type *ktype,
struct kobject *parent, const char *fmt, ...);
void kobject_del(struct kobject *kobj);
void kobject_get(struct kobject *kobj);
void kobject_put(struct kobject *kobj);
kobject_init sets the name, the type and the reference count. kobject_add registers the object in sysfs, creating its directory under the parent. kobject_init_and_add does both, and is what most drivers call. kobject_del removes the directory from sysfs. kobject_put drops a reference.
The ktype, the type of a kobject that holds the release function and the default attributes shared by every object of that type, is where the release function lives. It must free the object, and it runs exactly once, when the count hits zero:
struct my_obj {
struct kobject kobj;
int value;
};
static void my_obj_release(struct kobject *kobj)
{
struct my_obj *obj = container_of(kobj, struct my_obj, kobj);
kfree(obj);
}
static struct kobj_type my_ktype = {
.release = my_obj_release,
};
/* create */
obj = kmalloc(sizeof(*obj), GFP_KERNEL);
kobject_init_and_add(&obj->kobj, &my_ktype, NULL, "myobj");
/* tear down */
kobject_del(&obj->kobj);
kobject_put(&obj->kobj); /* last reference, so my_obj_release frees it */
The release function runs after kobject_put, so you must never touch the object after the last put. This is the same pattern the previous lesson met with cdev_del: the unregister call is separate from the free, and the reference count decides when the free is actually safe.
A a collection of kobjects of one type that share a home in sysfs and a set of uevent operations groups related objects. When a kobject is added with a kset but no parent, it lands in the kset's directory, and the kset can supply the type for all its members. A kobject does not need a kset, but subsystems that manage many identical devices use one to keep them together.
Finally, a a message the kernel sends to user space whenever a kobject is added, removed, changed or moved, which udev and mdev listen for is how userspace learns about device changes. The core emits them automatically on kobject_add and kobject_del, and you can emit one yourself when a device's state changes:
kobject_uevent(&obj->kobj, KOBJ_CHANGE);
The actions are KOBJ_ADD, KOBJ_REMOVE, KOBJ_CHANGE, KOBJ_MOVE, KOBJ_ONLINE and KOBJ_OFFLINE. You have already seen the effect: when the previous lesson's device_create ran, a uevent travelled to udev or mdev, which created or adjusted the /dev node.
Initialise:
kobject_initsets the name, type and a reference count of one.Add:
kobject_addcreates the sysfs directory and emits a KOBJ_ADD uevent.Use: each new user calls
kobject_get, so the count stays above zero while pointers exist.Drop users: each finished user calls
kobject_put, decrementing the count.Delete:
kobject_delremoves the directory and emits a KOBJ_REMOVE uevent.Release: when the last
kobject_putbrings the count to zero, the ktype release function frees the object.
Going deeperWhy release lives in the ktype, not in the object
The release function cannot be stored in the kobject itself, because by the time it runs, the kobject's memory may be about to be freed, and writing a field into it would be use-after-free. Putting release in the type, which is static and shared, keeps the pointer valid. The same reasoning explains the reference rule: for every kobject_get there must be exactly one kobject_put, and after your own last put you must not dereference the object again. A missing put leaks the object forever; an extra put frees it while it is still in use, and the resulting crash shows up long after the buggy code ran.
Try it
1 min readDo the lab for this session: add MYCHAR_IOCTL_RESET, MYCHAR_IOCTL_SET_SIZE and MYCHAR_IOCTL_GET_INFO to the mychar driver with a shared header, and drive them from a small userspace tool. Then convert the driver to a misc device, add a size attribute with DEVICE_ATTR_RW, and add debugfs counters plus a stats file built with DEFINE_SIMPLE_ATTRIBUTE or seq_file. Verify every path with cat, echo and the test tool, and finish with the practice pack, which drills command encoding, the copy-helper contract and the kobject reference rules without repeating the lab steps.
Key takeaways
- debugfs is for debugging and development only; sysfs is a stable interface you must design with care.
- A kobject's reference count, drained through the ktype release function, is what keeps a device object alive until the last user is done.
- debugfs_create_u32 and debugfs_create_x32 read a pointed-to value live and print it in decimal or hexadecimal, and debugfs_remove_recursive tears down a whole directory
- DEFINE_SIMPLE_ATTRIBUTE wires get and set functions into one debugfs file, while a binary attribute carries bulk data and seq_file pages long reports
Reflect
- Explain to a colleague, in two sentences: expose debug counters and settings through debugfs with debugfs_create_u32, DEFINE_SIMPLE_ATTRIBUTE and seq_file
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Official docsLinux kernel documentation: debugfs
- Official docsLinux kernel documentation: the seq_file interface
- Official docsLinux kernel documentation: kobjects, ksets and ktypes
Official documentation first. Links checked when the lesson was published.