1. 准备
首先在 menuconfig 时开启 debugfs
Kernel hacking --->
Generic Kernel Debugging Instruments --->
[*] Debug Filesystem
Debugfs default access (Access normal) --->
挂载debugfs
yangxr@vexpress:/ # cat /etc/fstab
proc /proc proc defaults 0 0
tmpfs /tmp tmpfs defaults 0 0
sysfs /sys sysfs defaults 0 0
var /dev tmpfs defaults 0 0
ramfs /dev tmpfs defaults 0 0
debugfs /debug debugfs defaults 0 0
2. 示例
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/debugfs.h>
#include <linux/uaccess.h>
static struct dentry *hello_dentry;
static u32 hello_u32;
static u16 hello_u16;
static u32 hello_arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9};
static struct debugfs_u32_array arr_info = {
.array = hello_arr,
.n_elements = 9,
};
static struct debugfs_blob_wrapper mem_info;
#define HELLO_MAX_SIZE 32
static char hello_buf[HELLO_MAX_SIZE];
static ssize_t hello_read (struct file *filp, char __user *to,
size_t count, loff_t *ppos)
{
return simple_read_from_buffer(to, count, ppos, hello_buf, HELLO_MAX_SIZE);
}
static ssize_t hello_write (struct file *filp, const char __user *from,
size_t count, loff_t *ppos)
{
if (*ppos == HELLO_MAX_SIZE)
return count;
return simple_write_to_buffer(hello_buf, HELLO_MAX_SIZE, ppos,
from, count);
}
static struct file_operations hello_fops = {
.owner = THIS_MODULE,
.read = hello_read,
.write = hello_write,
};
static int __init hello_init(void)
{
if ((hello_dentry = debugfs_create_dir("hello", NULL)) == NULL) {
printk("Create /debug/hello failed !\n");
return -1;
}
printk("Create /debug/hello succeed !\n");
// 创建u32节点,使用 10进制显示
debugfs_create_u32("u32", 0666, hello_dentry, &hello_u32);
// 创建u16节点,使用 16进制显示
debugfs_create_x16("u16", 0666, hello_dentry, &hello_u16);
// 创建u32数组 (只读)
debugfs_create_u32_array("u32_arr", 0666, hello_dentry, &arr_info);
// 显示一片内存 (只读)
mem_info.data = (void *)hello_arr;
mem_info.size = sizeof(hello_arr);
debugfs_create_blob("mem", 0666, hello_dentry, &mem_info);
if (debugfs_create_file("hello_fops", 0666,
hello_dentry, hello_buf, &hello_fops) == NULL) {
printk("Create /debug/hello_fops failed\n");
return -1;
}
return 0;
}
static void __exit hello_exit(void)
{
if (hello_dentry) {
// 递归删除/debug/hello
debugfs_remove_recursive(hello_dentry);
printk("Remove /debug/hello succeed !\n");
}
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
标签:kernel,arr,dentry,debugfs,static,u32,hello
From: https://www.cnblogs.com/yangxinrui/p/16928071.html