天天看點

驅動學習--SYS屬性節點建立

<pre name="code" class="objc">#include <linux/module.h>
#include <linux/slab.h>
#include <linux/kobject.h>
#include <linux/platform_device.h>

struct att_dev
{
    struct platform_device *pdev;
    struct kobject *kobj;
};

static struct att_dev *dev = NULL;

static ssize_t att_store(struct device *dev,
                         struct device_attribute *attr,
                         const char *buf, size_t count)
{
    printk("echo debug buf\n");

    return count;
}

static ssize_t att_show(struct device *dev,
                        struct device_attribute *attr,
                        char *buf)
{
    printk("cat debug buf\n");
    return 0;
}
static DEVICE_ATTR(test,0666,att_show,att_store);//使用DEVICE_ATTR,可以在sys fs中添加“檔案”,通過修改該檔案内容,可以實作在運作過程中動态控制device的目的


static __devinit int att_probe(struct platform_device *pdev)
{
    int ret;

    /* 增加節點/sys/devices/platform/att_test  */
    ret = sysfs_create_file(&pdev->dev.kobj,&dev_attr_test.attr);//第一個參數對應的是裝置的kobj,第二個參數則是綁定操作,其實就是綁定DEVICE_ATTR
    if(ret < 0)
    {
        return -ENOMEM;
    }
    return 0;


}

static struct platform_driver att_driver =
{
    .probe = att_probe,
    .driver = {
        .owner = THIS_MODULE,
        .name = "att_test",
    },
};

static int __init att_init(void)
{
    int ret;

    dev = kzalloc(sizeof(struct att_dev),GFP_KERNEL);
    if(dev == NULL)
    {
        printk("%s get dev memory error\n",__func__);
        return -ENOMEM;
    }
    /*在platform bus上增加 name = att_test的device, 友善與driver比對執行driver->probe */
    dev->pdev = platform_device_register_simple("att_test", -1, NULL, 0); //注冊裝置
    if(IS_ERR(dev->pdev))
    {
        PTR_ERR(dev->pdev);
        printk("%s pdev error\n",__func__);
        return -1;
    }
    ret = platform_driver_register(&att_driver); //注冊驅動
    if(ret < 0)
    {
        printk("%s register driver error\n",__func__);
        return ret;
    }
    return 0;
}
static void __exit att_exit(void)
{
    sysfs_remove_file(&dev->pdev->dev.kobj,&dev_attr_test.attr);
    kobject_del(dev->kobj);
    platform_device_unregister(dev->pdev);
    platform_driver_unregister(&att_driver);
    if(dev != NULL)
        kfree(dev);
}
module_init(att_init);
module_exit(att_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("XDmemory <[email protected]>");
           

之後通過insmod指令加載子產品,可以在/sys/devices/platform目錄下看見att_test節點

繼續閱讀