一、簡述:
通過DEVICE_ATTR創建設備節點,可以完成一些簡單的驅動的測試工作,可以向節點做echo cat相關的操作。
二、代碼如下:
(1)驅動代碼:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
//執行cat會調用到此函數
static ssize_t hello_test_show(struct device *dev, struct device_attribute *attr, char *buf)
{
size_t size = 123;
char *ptr = NULL;
printk("hello_test %s,%d\n",__FUNCTION__,__LINE__);
ptr = kmalloc(size, GFP_KERNEL);
if(!ptr){
pr_err("Allocation failed! \n");
return -1;
}
ptr[size] = 'X';
kfree(ptr);
return 0;
}
//執行echo 1 > hello_test會執行到此函數
static ssize_t hello_test_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
int test;
printk("hello_test %s,%d\n",__FUNCTION__,__LINE__);
test = 4;
return printk("%s() test = %d\n",__FUNCTION__,test);
}
static DEVICE_ATTR(hello_test, 0664, hello_test_show, hello_test_store);
//probe初始化函數
static int hello_test_probe(struct platform_device *pdev)
{
printk("%s()\n",__FUNCTION__);
//創建對應的節點file
device_create_file(&pdev->dev, &dev_attr_hello_test);
return 0;
}
static const struct of_device_id hello_of_match[] = {
{ .compatible = "mediatek,hello_test"},
{ },
};
//platform_driver 的結構
static struct platform_driver hello_test_driver = {
.probe = hello_test_probe,
.driver = {
.name = "hello_test",
.of_match_table = hello_of_match, //需要再dts中做匹配
}
};
static int __init hello_init(void)
{
printk("%s()\n",__FUNCTION__);
platform_driver_register(&hello_test_driver);
return 0;
}
static void __exit hello_exit(void)
{
printk("%s()\n",__FUNCTION__);
platform_driver_unregister(&hello_test_driver);
}
module_init(hello_init);
module_exit(hello_exit);
/* Module information */
MODULE_AUTHOR("hello_test");
MODULE_DESCRIPTION("hello driver");
MODULE_LICENSE("GPL v2");
(2)makefile Kconfig dts:
//makefile
obj-$(CONFIG_HELLO_TEST) +=hello_test/
//Kconfig
config HELLO_TEST
bool "HELLO_TEST for transsion solution"
default n
//dts
hello_test: hello_test {
compatible = "mediatek,hello_test";
status = "okay";
};
三、測試:
(1)adb 到設備中可以看到如下節點:
/sys/bus/platform/drivers/hello_test/odm:hello_test/
driver driver_override hello_test modalias of_node power subsystem uevent
(2)執行如下的命令會調用到hello_test_show或hello_test_store函數:
cat hello_test
echo 1 > hello_test
(3)執行如下命令可以看到對應的kernel log中有輸出打印:
while true; do cat /proc/kmsg | grep -nr hello ; done;