设备模型跟踪所有系统所知道的设备。进行跟踪的主要原因是让驱动程序协调与设备之间的关系。
先看驱动程序的结构体,仅仅贴出一些重要的成员:
-
/*linux/device.h*/
-
struct device_driver {
-
const char *name; //驱动函数的名字,在对应总线的driver目录下显示
-
struct bus_type *bus; //指定该驱动程序所操作的总线类型,必须设置,不然会注册失败
-
-
struct module *owner;
-
const char *mod_name; /* used for built-in modules */
-
-
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);
-
struct attribute_group **groups;
-
-
struct dev_pm_ops *pm;
-
-
struct driver_private *p;
-
};
驱动注册/注销
int driver_register(struct device_driver *drv) 注册驱动
void driver_unregister(struct device_driver *drv) 注销驱动
驱动属性
驱动的属性使用struct driver_attribute 来描述:
struct driver_attribute {
struct attribute attr;
ssize_t (*show)(struct device_driver *drv,char *buf);
ssize_t (*store)(struct device_driver *drv,const char *buf, size_t count);
}
int driver_create_file(struct device_driver * drv,struct driver_attribute * attr) 创建属性
void driver_remove_file(struct device_driver * drv,struct driver_attribute * attr) 删除属性
源码实例:
-
#include <linux/device.h>
-
#include <linux/module.h>
-
#include <linux/kernel.h>
-
#include <linux/init.h>
-
#include <linux/string.h>
-
-
extern struct bus_type my_bus_type;
-
-
/*当驱动找到对应的设备时会执行该函数*/
-
static int my_probe(struct device *dev)
-
{
-
printk("Driver found device which my driver can handle!\n");
-
return 0;
-
}
-
-
static int my_remove(struct device *dev)
-
{
-
printk("Driver found device unpluged!\n");
-
return 0;
-
}
-
-
struct device_driver my_driver = {
-
.name = "my_dev",
-
.bus = &my_bus_type,
-
.probe = my_probe,
-
.remove = my_remove,
-
};
-
-
static ssize_t mydriver_show(struct device_driver *driver, char *buf)
-
{
-
return sprintf(buf, "%s\n", "This is my driver!");
-
}
-
-
static DRIVER_ATTR(drv, S_IRUGO, mydriver_show, NULL);
-
-
static int __init my_driver_init(void)
-
{
-
int ret = 0;
-
-
/*注册驱动*/
-
driver_register(&my_driver);
-
-
/*创建属性文件*/
-
driver_create_file(&my_driver, &driver_attr_drv);
-
-
return ret;
-
}
-
-
static void my_driver_exit(void)
-
{
-
driver_unregister(&my_driver);
-
}
-
-
module_init(my_driver_init);
-
module_exit(my_driver_exit);
-
-
MODULE_AUTHOR("David Xie");
-
MODULE_LICENSE("GPL");
阅读(148) | 评论(0) | 转发(0) |