platform虚拟总线驱动框架 2025-10-05

配合platform_device或设备树使用

//(1)写模块的加载和卸载注册函数
module_init(xxxdriver_init);
module_exit(xxxdriver_exit);
//或
module_platform_driver(xxx_driver);
//xxx_driver struct platform_driver

//(2)驱动模块加载和卸载 (如果是module_platform_driver,就不需要这一步)
static int __init xxxdriver_init(void)
{
    return platform_driver_register(&xxx_driver);
}

static int __init xxxdriver_exit(void)
{
    platform_driver_unregister(&xxx_driver);
}

// (3) platform平台驱动结构体
//该结构体定义在文件 include/linux/platform_device.h
static struct platform_driver xxx_driver = {
    //driver是device_driver结构体定义在 include/linux/device.h
    .driver = {
        .name = "xxx", //驱动名字,用于和设备匹配
        .of_match_table = xxx_of_match, //设备树匹配表 of_device_id 结构体类型的实例,该结构体定义在文件 include/linux/mod_devicetable.h
    },
    .probe = xxx_probe, //函数指针,当驱动与设备匹配成功以后probe函数就会执行
    .remove = xxx_remove,
};

//(4)如果使用设备树 写匹配列表 就是上面的xxx_of_match
static const struct of_device_id xxx_of_match[] = {
    {.compatible="xxx-gpio"},
    {/*Sentinel*/}
};

// 使用宏声明设备表
MODULE_DEVICE_TABLE(of, xxx_of_match);

//(5)platform 驱动的probe函数 驱动与设备匹配成功以后此函数会执行
static int xxx_probe(struct platform_device *dev)
{
    ......
    cdev_init(&xxxdev.cdev, &xxx_fops); /* 注册字符设备驱动 */
    return 0;
}
// 对应的移除
static int xxx_remove(struct platform_device *dev)
{
    ......
    cdev_del(&xxxdev.cdev); //删除cdev
    //函数具体内容
    return 0;
}

//其中xxxdev是设备结构体(会将多个结构体放到里面统一管理)
//cdev是字符设备 相关语句 见上一节
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容