Linux驱动学习----驱动注册
Linux下的设备和驱动都需要先注册之后才能使用
设备注册
注册设备使用结构体platform_device,该结构体位置:Linux内核源码/include/linux/platform_device.h
struct platform_device {
const char * name;
int id;
struct device dev;
u32 num_resources;
struct resource * resource;
const struct platform_device_id *id_entry;
/* MFD cell pointer */
struct mfd_cell *mfd_cell;
/* arch specific additions */
struct pdev_archdata archdata;
};
其中,name是设备的名称,名称和驱动名称相互对应之后才能使用
设备注册流程
- 注册设备,将设备结构体放到平台文件中,会自动注册设备,不用去调用注册设备函数
- 在Kconfig文件中添加HELLO设备的宏定义(make menuconfig即可出现HELLO设备相关信息)
- 配置menucofnig中HELLO宏定义生成新的.config文件
- 生成新的zImage
驱动注册
驱动注册使用结构体platform_driver,该结构体位置:Linux内核源码/include/linux/platform_device.h
驱动注册函数(platform_driver_register)和驱动卸载函数(platform_driver_unregister)也都在这个头文件中
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 (*resume)(struct platform_device *);
struct device_driver driver;
const struct platform_device_id *id_table;
};
驱动常见的几种状态:初始化、移除、休眠、复位
几种状态对应的函数如下:
- probe函数:platform_match函数匹配之后,驱动调用的初始化函数(否则不会初始化驱动 )
- remove函数:移除驱动函数
- suspend函数:悬挂(休眠)驱动函数
- resume函数:休眠后恢复驱动
device_driver数据结构的两个参数
- name和注册的设备name要一致
- owner一般赋值为THIS_MODULE
驱动注册实例
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#define DRIVER_NAME "hello_ctl"
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("Wang_Wonk");
static int hello_probe(struct platform_device *pdv){
printk(KERN_EMERG "\tInitialized\n");
return 0;
}
static int hello_remove(struct platform_device *pdv){
return 0;
}
static int hello_suspend(struct platform_device *pdv){
return 0;
}
static int hello_resume(struct platform_device *pdv){
return 0;
}
static void hello_shutdown(struct platform_device *pdv){
}
struct platform_driver hello_driver = {
.probe = hello_probe,
.remove = hello_remove,
.shutdown = hello_shutdown,
.suspend = hello_suspend,
.resume = hello_resume,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
}
};
static int hello_init(void)
{
printk(KERN_EMERG "Hello World enter!\n");
platform_driver_register(&hello_driver);
return 0;
}
static void hello_exit(void)
{
printk(KERN_EMERG "Hello World exit!\n");
platform_driver_unregister(&hello_driver);
}
module_init(hello_init);
module_exit(hello_exit);
此驱动的Makefile文件和之前的mini_linux_module的文件只需改动一处即可
#!/bin/bash
obj-m += probe_linux_module.o
KDIR := /home/Xunwei_work/Driver/linux_source/iTop4412_Kernel_3.0
PWD ?= $(shell pwd)
all:
make -C $(KDIR) M=$(PWD) modules
clean:
rm -rf *.o