首先介绍一下注册一个驱动的步骤:
1、定义一个platform_driver结构
2、初始化这个结构,指定其probe、remove等函数,并初始化其中的driver变量
3、实现其probe、remove等函数
struct platform_driver {
int (*probe)(struct platform_device *);
int (*remove)(struct platform_device *);
void (*shutdown)(struct platform_device *);
int (*suspend)(struct platform_device *, pm_message_t state);
int (*suspend_late)(struct platform_device *, pm_message_t state);
int (*resume_early)(struct platform_device *);
int (*resume)(struct platform_device *);
struct device_driver driver;
};
可见,它包含了设备操作的几个功能函数,同样重要的是,它还包含了一个device_driver结构。刚才提到了驱动程序中需要初始化这个变量。下面看一下这个变量的定义,位于include/linux/device.h中:
struct device_driver {
const char * name;
struct bus_type * bus;
struct kobject kobj;
struct klist klist_devices;
struct klist_node knode_bus;
struct module * owner;
const char * mod_name; /* used for built-in modules */
struct module_kobject * mkobj;
int (*probe) (struct device * dev);
int (*remove) (struct device * dev);
void (*shutdown) (struct device * dev);
int (*suspend) (struct device * dev, pm_message_t state);
int (*resume) (struct device * dev);
};
需要注意这两个变量:name和owner。那么的作用主要是为了和相关的platform_device关联起来,owner的作用是说明模块的所有者,驱动程序中一般初始化为THIS_MODULE。
加密磁头的platform_driver定义如下:
static struct platform_driver secure_head_driver = {
.driver = {
.name = "secure_head",
},
.suspend = secure_head_suspend,
.resume = secure_head_resume,
.probe = secure_head_module_probe,
.remove = secure_head_module_remove,
};
注意其中的driver这个结构体,只初始化了name。接着看一下和driver相关的另一个结构,定义如下:
struct platform_device {
const char * name;
int id;
struct device dev;
u32 num_resources;
struct resource * resource;
};
该结构中也有一个name变量。platform_driver从字面上来看就知道是设备驱动。设备驱动是为谁服务的呢?当然是设备了。platform_device就描述了设备对象。加密磁头的platform_device定义如下(定义在arch/arm/mach-mx25/devices.c中):
static struct platform_device mxc_secure_head_device = {
.name = "secure_head",
.id = 0,
.num_resources = ARRAY_SIZE(imx_secure_head_resources),
.resource = imx_secure_head_resources,
.dev = {
.release = NULL,
},
};
它的name变量和刚才上面的platform_driver的name变量是一致的,内核正是通过这个一致性来为驱动程序找到资源,即platform_device中的resource。这个结构的定义如下,位于include/linux/ioport.h中:
struct resource {
resource_size_t start;
resource_size_t end;
const char *name;
unsigned long flags;
struct resource *parent, *sibling, *child;
};
下面是磁头的resource的定义:
static struct resource imx_secure_head_resources[] = {
[0] = {
.start = IOMUX_TO_IRQ(MX25_PIN_DE_B),
.end = IOMUX_TO_IRQ(MX25_PIN_DE_B),
.flags = IORESOURCE_IRQ,
},
};