Linux驱动模型-驱动

1、驱动描述

驱动程序由struct device_driver描述

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);

};

2、驱动注册、注销

 int __must_check driver_register(struct device_driver * drv);
 void driver_unregister(struct device_driver * drv);

3、驱动属性

/* sysfs interface for exporting driver attributes */

struct driver_attribute {
struct attribute attr;
ssize_t (*show)(struct device_driver *, char * buf);
ssize_t (*store)(struct device_driver *, const char * buf, size_t count);

};

创建属性

int __must_check driver_create_file(struct device_driver *,struct driver_attribute *);

删除属性

void driver_remove_file(struct device_driver *, struct driver_attribute *);

4、参考实例

#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)
{
       /*注册驱动*/
driver_register(&my_driver);

/*创建属性文件*/
driver_create_file(&my_driver, &driver_attr_drv);

return 0;

}

static void my_driver_exit(void)
{
driver_unregister(&my_driver);
}

module_init(my_driver_init);
module_exit(my_driver_exit);

MODULE_LICENSE("Dual BSD/GPL");

Makefile

ifeq ($(KERNELRELEASE),)
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:                               
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
clean:                                             
        $(MAKE) -C $(KERNELDIR) M=$(PWD) clean
else
    obj-m := driver.o

endif

猜你喜欢

转载自blog.csdn.net/xiezhi123456/article/details/81024183
今日推荐