流程

make
insmod 001_helloworld_driver.ko #device和driver不分先后
insmod 001_helloworld_device.ko #device和driver不分先后
ls /sys/bus/platform/devices #注册设备时添加
#生成 my_device_test文件,my_device_test文件和device.c中platform_device.name一致
ls /sys/bus/platform/drivers
#生成 my_device_test文件,my_device_test文件和driver.c中platform_driver.name一致

linux系统会自动将名字一样的设备和驱动关联在一起。几乎是瞬间。

代码:001_helloworld_device.c

#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>

static struct resource my_device_resource[]={
    [0]={
        .start = 0x0,
        .end = 0xA,
        .flags = IORESOURCE_MEM
    },
    [1]={
        .start = 0xB,
        .end = 0xF,
        .flags = IORESOURCE_IRQ
    }
};
void my_device_release(struct device *dev){
    printk("this is my_device_release");
}
struct platform_device my_device_test = {
    .name="my_device_test",
    .id = -1,
    .resource = my_device_resource,
    .dev={
        .release= my_device_release
    }
};
static int platform_init(void)
{
    platform_device_register(&my_device_test);
    printk("platform_init");
    return 0;
}
static void platform_exit(void)
{
    platform_device_unregister(&my_device_test);
    printk("platform_exit");
}

module_init(platform_init);
module_exit(platform_exit);

// 模块许可证声明,必须是 GPL 兼容的许可证才能加载到内核中
MODULE_LICENSE("GPL");
// 模块作者信息
MODULE_AUTHOR("wyl");
// 模块描述
MODULE_DESCRIPTION("A simple Hello World Linux Driver");

代码:001_helloworld_driver.c

#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mod_devicetable.h>
int my_probe(struct platform_device * dev){
    printk("my_probe");
    return 0;
}
int my_remove(struct platform_device * dev){
    printk("my_remove");
    return 0;
};
// const struct platform_device_id my_id_table[] = {
//     {.name = "my_device_test"},
//     {},
// };
struct platform_driver driver_test= {
    .probe = my_probe,
    .remove = my_remove,
    .driver = {
        .name = "my_device_test", //与device设备描述名字一致!!!
        .owner = THIS_MODULE,

        // const struct platform_device_id *id_table; //非必须,匹配时优先级最高比上面的name要高
    }
};
static int platform_driver_init(void)
{
    platform_driver_register(&driver_test);
    printk("platform_init");
    return 0;
}
static void platform_driver_exit(void)
{
    platform_driver_unregister(&driver_test);
    printk("platform_exit");
}

module_init(platform_driver_init);
module_exit(platform_driver_exit);

// 模块许可证声明,必须是 GPL 兼容的许可证才能加载到内核中
MODULE_LICENSE("GPL");
// 模块作者信息
MODULE_AUTHOR("wyl");
// 模块描述
MODULE_DESCRIPTION("A simple Hello World Linux Driver");

什么时候需要 id_table

  • 一个驱动支持多个不同名字的设备时(比如同一芯片不同型号)
  • 需要 driver_data 传递设备差异信息时(每个 id 入口可以带一个 kernel_ulong_t 的数据)