Linux Debugfs implementation as a userspace interface

debugfs is a Linux file system. It is a user space interface to and from the Linux kernel. It is mounted at /sys/kernel/debug. The kernel must be compiled with the CONFIG_DEBUG_FS option to use this file system. It exists in the Linux kernel since version 2.6.10-rc3 [1]

In the below example, you will see an example to a debugfs. A 32-bit flag is created under the /sys/kernel/debug/debugfs_ex directory called enable for read and write.


debugfs_ex.c


#include <linux/version.h>
#include <linux/module.h>
#include <linux/debugfs.h>

static struct dentry *dn; /* Dentry object for debugfs directory */

static int enable;  /* Enable flag for debugfs_ex module */

/*
 * debugfs_ex_init()
 */
static int __init debugfs_ex_init(void)
{
 printk(KERN_INFO "debugfs_ex init\n");

 dn = debugfs_create_dir("debugfs_ex", NULL);
 if (!dn) {
  printk(KERN_ERR "Failed to create debugfs_ex directory in debugfs\n");
  return -1;
 }

 /*
  * Create a 32-bit flag under debugfs_ex directory.
  * This flag is readable and writable.
  */
 if (!debugfs_create_u32("enable", 0666, dn, (u32 *)&enable)) {
  printk(KERN_ALERT "Failed to create enable file in debugfs\n");
  goto fail;
 }

 return 0;
fail:
 debugfs_remove_recursive(dn);

 printk(KERN_INFO "debugfs_ex init failed\n");

 return -1;
}

/*
 * debugfs_ex_exit()
 */
static void __exit debugfs_ex_exit(void)
{
 printk(KERN_INFO "debugfs_ex exit\n");

 if (dn) {
  printk(KERN_INFO "remove debugfs_ex node\n");
  debugfs_remove_recursive(dn);
 }

 printk(KERN_INFO "debugfs_ex exit complete\n");
}

module_init(debugfs_ex_init)
module_exit(debugfs_ex_exit)

MODULE_DESCRIPTION("Debugfs Example");
#ifdef MODULE_LICENSE
MODULE_LICENSE("Dual BSD/GPL");
#endif


Makefile:


obj-m += debugfs_ex.o

all:
 make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules

clean:
 make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean

Compilation:

You need to put the Makefile and debugfs_ex.c file into the same directory and simply run the make command to create the kernel loadable module debugfs_ex.ko

Usage:

Make sure you have the right permission to use your debugfs directory.

Install the module:
insmod ./debugfs_ex.ko

Write 5 to the flag:
echo 5 > /sys/kernel/debug/debugfs_ex/enable

Read the flag:
cat  /sys/kernel/debug/debugfs_ex/enable

Remove module:
rmmod debugfs_ex



[1] https://en.wikipedia.org/wiki/Debugfs

Comments

Popular posts from this blog

How to Use container_of in Linux Kernel Development

Notification Chains in Linux Kernel

Build and Flash OpenWrt for Raspberry Pi