2020年5月28日 星期四

Linux kernel module: Add entry to debugfs and a read/write file.

Goal

This module will create Ray_DBG directory in debugfs and create a file REG for read/write. it's similar to previous module(create /proc/Ray), but easier to use and need less line of code.
 

Code


#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/debugfs.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ray Tsai");
static u32 reg_data = 0xaa;
static struct dentry *root;
static int __init test_module_init(void)
{
pr_info("Init Ray test module!\n");
pr_info("Create Ray_DBG !\n");
root = debugfs_create_dir("Ray_DBG", NULL);
if(!root)
return -EFAULT;
pr_info("Create REG debug !\n");
if(!debugfs_create_x32("REG", 0777, root, (u32 *)&reg_data))
goto err;
return 0;
err:
debugfs_remove_recursive(root);
pr_info("Failed to initialize debugfs\n");
return -EFAULT;
}
static void __exit test_module_exit(void)
{
debugfs_remove_recursive(root);
pr_info("Exit Ray test module!\n");
}
module_init(test_module_init);
module_exit(test_module_exit);
view raw gistfile1.txt hosted with ❤ by GitHub

Makefile


obj-m := test_module.o
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
all default: modules
install: modules_install
modules modules_install help clean:
$(MAKE) -C $(KERNELDIR) M=$(shell pwd) $@
view raw gistfile1.txt hosted with ❤ by GitHub

Usage

1. Insert module 
$>insmod test_module.ko
$>dmesg | tail
[7501255.251763] Create Ray_DBG !
[7501255.251776] Create REG debug !
2. Mount debugfs 
$>mount -t debugfs none /sys/kernel/debug
3. Read data
$>cat /sys/kernel/debug/Ray_DBG/REG
$>0x000000aa
4. Write data 
$>echo 0xff>  /sys/kernel/debug/Ray_DBG/REG 
$>cat /sys/kernel/debug/Ray_DBG/REG 
$>0x000000ff

Reference

  1. Kernel document: debugfs
  2. Debugfs

沒有留言:

張貼留言

Linux driver: How to enable dynamic debug at booting time for built-in driver.

 Dynamic debug is useful for debug driver, and can be enable by: 1. Mount debug fs #>mount -t debugfs none /sys/kernel/debug 2. Enable dy...