Linux总线设备驱动模型

Linux总线设备驱动模型

基于Linux Kernel3.0.8版本

1.总线

总线是处理器和设备之间的通道,在设备模型中, 所有的设备都通过总线相连, 甚至是内部的虚拟“platform”总线。 

在 Linux 设备模型中, 总线由bus_type结构表示, 定义在 <linux/device.h>


/**
 * struct bus_type - The bus type of the device
 *
 * @name:	The name of the bus.
 * @bus_attrs:	Default attributes of the bus.
 * @dev_attrs:	Default attributes of the devices on the bus.
 * @drv_attrs:	Default attributes of the device drivers on the bus.
 * @match:	Called, perhaps multiple times, whenever a new device or driver
 *		is added for this bus. It should return a nonzero value if the
 *		given device can be handled by the given driver.
 * @uevent:	Called when a device is added, removed, or a few other things
 *		that generate uevents to add the environment variables.
 * @probe:	Called when a new device or driver add to this bus, and callback
 *		the specific driver's probe to initial the matched device.
 * @remove:	Called when a device removed from this bus.
 * @shutdown:	Called at shut-down time to quiesce the device.
 * @suspend:	Called when a device on this bus wants to go to sleep mode.
 * @resume:	Called to bring a device on this bus out of sleep mode.
 * @pm:		Power management operations of this bus, callback the specific
 *		device driver's pm-ops.
 * @p:		The private data of the driver core, only the driver core can
 *		touch this.
 *
 * A bus is a channel between the processor and one or more devices. For the
 * purposes of the device model, all devices are connected via a bus, even if
 * it is an internal, virtual, "platform" bus. Buses can plug into each other.
 * A USB controller is usually a PCI device, for example. The device model
 * represents the actual connections between buses and the devices they control.
 * A bus is represented by the bus_type structure. It contains the name, the
 * default attributes, the bus' methods, PM operations, and the driver core's
 * private data.
 */
struct bus_type {
	const char		*name; /*总线名称*/
	struct bus_attribute	*bus_attrs; /*总线属性*/
	struct device_attribute	*dev_attrs; /*设备属性*/
	struct driver_attribute	*drv_attrs; /*驱动属性*/
	
	/* 当一个新设备或新驱动被添加到该总线时调用,用于device和driver的匹配,匹配返回非0值 */
	int (*match)(struct device *dev, struct device_driver *drv);
	/* 在为用户空间产生热插拔事件之前,改方法允许总线添加环境变量 */
	int (*uevent)(struct device *dev, struct kobj_uevent_env *env);
	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);

	const struct dev_pm_ops *pm;

	struct iommu_ops *iommu_ops;

	struct subsys_private *p;
};

struct subsys_private {
	struct kset subsys;
	struct kset *devices_kset;

	struct kset *drivers_kset;
	struct klist klist_devices;
	struct klist klist_drivers;
	struct blocking_notifier_head bus_notifier;
	unsigned int drivers_autoprobe:1;
	struct bus_type *bus;

	struct list_head class_interfaces;
	struct kset glue_dirs;
	struct mutex class_mutex;
	struct class *class;
};

1.1 总线的注册

int bus_register(struct bus_type *bus);
若成功,新的总线将被添加进系统,并可在sysfs 的 /sys/bus 下看到。
/**
 * bus_register - register a bus with the system.
 * @bus: bus.
 *
 * Once we have that, we registered the bus with the kobject
 * infrastructure, then register the children subsystems it has:
 * the devices and drivers that belong to the bus.
 * 基于sysfs文件系统的kobject kset来注册总线
 */
int bus_register(struct bus_type *bus)
{
	int retval;
	struct subsys_private *priv;

	priv = kzalloc(sizeof(struct subsys_private), GFP_KERNEL);
	if (!priv)
		return -ENOMEM;

	priv->bus = bus;
	bus->p = priv;

	BLOCKING_INIT_NOTIFIER_HEAD(&priv->bus_notifier);

	retval = kobject_set_name(&priv->subsys.kobj, "%s", bus->name);
	if (retval)
		goto out;

	priv->subsys.kobj.kset = bus_kset;
	priv->subsys.kobj.ktype = &bus_ktype;
	priv->drivers_autoprobe = 1;
	
	retval = kset_register(&priv->subsys); // 生成/sys/bus/busname/目录
	if (retval)
		goto out;
	/* 创建总线属性文件,生成/sys/bus/busname/uevent文件 */
	retval = bus_create_file(bus, &bus_attr_uevent);
	if (retval)
		goto bus_uevent_fail;
	/* 动态创建一个名为devices的kset结构并添加到sysfs,也就是生成/sys/bus/busname/devices/目录 */
	priv->devices_kset = kset_create_and_add("devices", NULL,
						 &priv->subsys.kobj);
	if (!priv->devices_kset) {
		retval = -ENOMEM;
		goto bus_devices_fail;
	}
	
	/* 动态创建一个名为drivers的kset结构并添加到sysfs,也就是生成/sys/bus/busname/drivers/目录 */
priv->drivers_kset = kset_create_and_add("drivers", NULL, &priv->subsys.kobj);if (!priv->drivers_kset) {retval = -ENOMEM;goto bus_drivers_fail;}klist_init(&priv->klist_devices, klist_devices_get, klist_devices_put);klist_init(&priv->klist_drivers, NULL, NULL);retval = add_probe_files(bus);if (retval)goto bus_probe_files_fail;retval = bus_add_attrs(bus);if (retval)goto bus_attrs_fail;pr_debug("bus: '%s': registered\n", bus->name);return 0;bus_attrs_fail:remove_probe_files(bus);bus_probe_files_fail:kset_unregister(bus->p->drivers_kset);bus_drivers_fail:kset_unregister(bus->p->devices_kset);bus_devices_fail:bus_remove_file(bus, &bus_attr_uevent);bus_uevent_fail:kset_unregister(&bus->p->subsys);out:kfree(bus->p);bus->p = NULL;return retval;}

1.2 总线的删除


void bus_unregister(struct bus_type *bus);
/**
 * bus_unregister - remove a bus from the system
 * @bus: bus.
 *
 * Unregister the child subsystems and the bus itself.
 * Finally, we call bus_put() to release the refcount
 */
void bus_unregister(struct bus_type *bus)
{
	pr_debug("bus: '%s': unregistering\n", bus->name);
	bus_remove_attrs(bus);
	remove_probe_files(bus);
	kset_unregister(bus->p->drivers_kset);
	kset_unregister(bus->p->devices_kset);
	bus_remove_file(bus, &bus_attr_uevent);
	kset_unregister(&bus->p->subsys);
	kfree(bus->p);
	bus->p = NULL;
}

1.3 总线属性

总线属性由结构 bus_attribute 描述,定义如下:
struct bus_attribute {
	struct attribute	attr;
	ssize_t (*show)(struct bus_type *bus, char *buf);
	ssize_t (*store)(struct bus_type *bus, const char *buf, size_t count);
};
// 构造总线属性
#define BUS_ATTR(_name, _mode, _show, _store)	\
struct bus_attribute bus_attr_##_name = __ATTR(_name, _mode, _show, _store)

#define __ATTR(_name,_mode,_show,_store) { \
	.attr = {.name = __stringify(_name), .mode = _mode },	\
	.show	= _show,					\
	.store	= _store,					\
}

// drivers\base\bus.c
static BUS_ATTR(uevent, S_IWUSR, NULL, bus_uevent_store);
static BUS_ATTR(drivers_probe, S_IWUSR, NULL, store_drivers_probe);
static BUS_ATTR(drivers_autoprobe, S_IWUSR | S_IRUGO,
		show_drivers_autoprobe, store_drivers_autoprobe);

1.4 创建总线属性

int bus_create_file(struct bus_type *bus, struct bus_attribute *attr);
int bus_create_file(struct bus_type *bus, struct bus_attribute *attr)
{
	int error;
	if (bus_get(bus)) {
		error = sysfs_create_file(&bus->p->subsys.kobj, &attr->attr);
		bus_put(bus);
	} else
		error = -EINVAL;
	return error;
}

1.5 删除总线属性

void bus_remove_file(struct bus_type *bus, struct bus_attribute *attr);
void bus_remove_file(struct bus_type *bus, struct bus_attribute *attr)
{
	if (bus_get(bus)) {
		sysfs_remove_file(&bus->p->subsys.kobj, &attr->attr);
		bus_put(bus);
	}
}

2. 设备

Linux 系统中的每个设备由一个 struct device 描述:
**
 * struct device - The basic device structure
 * @parent:	The device's "parent" device, the device to which it is attached.
 * 		In most cases, a parent device is some sort of bus or host
 * 		controller. If parent is NULL, the device, is a top-level device,
 * 		which is not usually what you want.
 * @p:		Holds the private data of the driver core portions of the device.
 * 		See the comment of the struct device_private for detail.
 * @kobj:	A top-level, abstract class from which other classes are derived.
 * @init_name:	Initial name of the device.
 * @type:	The type of device.
 * 		This identifies the device type and carries type-specific
 * 		information.
 * @mutex:	Mutex to synchronize calls to its driver.
 * @bus:	Type of bus device is on.
 * @driver:	Which driver has allocated this
 * @platform_data: Platform data specific to the device.
 * 		Example: For devices on custom boards, as typical of embedded
 * 		and SOC based hardware, Linux often uses platform_data to point
 * 		to board-specific structures describing devices and how they
 * 		are wired.  That can include what ports are available, chip
 * 		variants, which GPIO pins act in what additional roles, and so
 * 		on.  This shrinks the "Board Support Packages" (BSPs) and
 * 		minimizes board-specific #ifdefs in drivers.
 * @power:	For device power management.
 * 		See Documentation/power/devices.txt for details.
 * @pwr_domain:	Provide callbacks that are executed during system suspend,
 * 		hibernation, system resume and during runtime PM transitions
 * 		along with subsystem-level and driver-level callbacks.
 * @numa_node:	NUMA node this device is close to.
 * @dma_mask:	Dma mask (if dma'ble device).
 * @coherent_dma_mask: Like dma_mask, but for alloc_coherent mapping as not all
 * 		hardware supports 64-bit addresses for consistent allocations
 * 		such descriptors.
 * @dma_parms:	A low level driver may set these to teach IOMMU code about
 * 		segment limitations.
 * @dma_pools:	Dma pools (if dma'ble device).
 * @dma_mem:	Internal for coherent mem override.
 * @archdata:	For arch-specific additions.
 * @of_node:	Associated device tree node.
 * @devt:	For creating the sysfs "dev".
 * @devres_lock: Spinlock to protect the resource of the device.
 * @devres_head: The resources list of the device.
 * @knode_class: The node used to add the device to the class list.
 * @class:	The class of the device.
 * @groups:	Optional attribute groups.
 * @release:	Callback to free the device after all references have
 * 		gone away. This should be set by the allocator of the
 * 		device (i.e. the bus driver that discovered the device).
 *
 * At the lowest level, every device in a Linux system is represented by an
 * instance of struct device. The device structure contains the information
 * that the device model core needs to model the system. Most subsystems,
 * however, track additional information about the devices they host. As a
 * result, it is rare for devices to be represented by bare device structures;
 * instead, that structure, like kobject structures, is usually embedded within
 * a higher-level representation of the device.
 */
struct device {
	struct device		*parent; /* 指向该设备的父设备,可能是设备所在的总线 */

	struct device_private	*p;

	struct kobject kobj;
	const char		*init_name; /* initial name of the device 相当旧版本的bus_id  */
	const struct device_type *type;

	struct mutex		mutex;	/* mutex to synchronize calls to
					 * its driver.
					 */

	struct bus_type	*bus;		/* type of bus device is on 设备所在总线 */
	struct device_driver *driver;	/* which driver has allocated this
					   device 管理该设备的驱动 */
	void		*platform_data;	/* Platform specific data, device
					   core doesn't touch it */
	struct dev_pm_info	power;
	struct dev_power_domain	*pwr_domain;

#ifdef CONFIG_NUMA
	int		numa_node;	/* NUMA node this device is close to */
#endif
	u64		*dma_mask;	/* dma mask (if dma'able device) */
	u64		coherent_dma_mask;/* Like dma_mask, but for
					     alloc_coherent mappings as
					     not all hardware supports
					     64 bit addresses for consistent
					     allocations such descriptors. */

	struct device_dma_parameters *dma_parms;

	struct list_head	dma_pools;	/* dma pools (if dma'ble) */

	struct dma_coherent_mem	*dma_mem; /* internal for coherent mem
					     override */
#ifdef CONFIG_DMA_CMA
	struct cma	*cma_area;	/* contiguous memory area for dma
						allocation */
#endif
	/* arch specific additions */
	struct dev_archdata	archdata;

	struct device_node	*of_node; /* associated device tree node */

	dev_t			devt;	/* dev_t, creates the sysfs "dev" */

	spinlock_t		devres_lock;
	struct list_head	devres_head;

	struct klist_node	knode_class;
	struct class		*class;
	const struct attribute_group **groups;	/* optional groups */

	void	(*release)(struct device *dev);
};

2.1 注册设备

int device_register(struct device *dev)
/**
 * device_register - register a device with the system.
 * @dev: pointer to the device structure
 *
 * This happens in two clean steps - initialize the device
 * and add it to the system. The two steps can be called
 * separately, but this is the easiest and most common.
 * I.e. you should only call the two helpers separately if
 * have a clearly defined need to use and refcount the device
 * before it is added to the hierarchy.
 *
 * NOTE: _Never_ directly free @dev after calling this function, even
 * if it returned an error! Always use put_device() to give up the
 * reference initialized in this function instead.
 */
int device_register(struct device *dev)
{
	device_initialize(dev);
	return device_add(dev);
}

2.2 注销设备

void device_unregister(struct device *dev)
/**
 * device_unregister - unregister device from system.
 * @dev: device going away.
 *
 * We do this in two parts, like we do device_register(). First,
 * we remove it from all the subsystems with device_del(), then
 * we decrement the reference count via put_device(). If that
 * is the final reference count, the device will be cleaned up
 * via device_release() above. Otherwise, the structure will
 * stick around until the final reference to the device is dropped.
 */
void device_unregister(struct device *dev)
{
	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
	device_del(dev);
	put_device(dev);
}
总线也是个设备,也必须按设备注册

2.3 设备属性

设备属性由struct device_attribute 描述:
/* interface for exporting device attributes */
struct device_attribute {
	struct attribute	attr;
	ssize_t (*show)(struct device *dev, struct device_attribute *attr,
			char *buf);
	ssize_t (*store)(struct device *dev, struct device_attribute *attr,
			 const char *buf, size_t count);
};

2.4 创建设备属性

int device_create_file(struct device *dev, const struct device_attribute *attr);
/**
 * device_create_file - create sysfs attribute file for device.
 * @dev: device.
 * @attr: device attribute descriptor.
 */
int device_create_file(struct device *dev,
		       const struct device_attribute *attr)
{
	int error = 0;
	if (dev)
		error = sysfs_create_file(&dev->kobj, &attr->attr);
	return error;
}

2.5 删除设备属性

void device_remove_file(struct device *dev, const struct device_attribute *attr);
/**
 * device_remove_file - remove sysfs attribute file.
 * @dev: device.
 * @attr: device attribute descriptor.
 */
void device_remove_file(struct device *dev,
			const struct device_attribute *attr)
{
	if (dev)
		sysfs_remove_file(&dev->kobj, &attr->attr);
}

3 驱动

驱动程序由struct device_driver 描述 :
/**
 * struct device_driver - The basic device driver structure
 * @name:	Name of the device driver.
 * @bus:	The bus which the device of this driver belongs to.
 * @owner:	The module owner.
 * @mod_name:	Used for built-in modules.
 * @suppress_bind_attrs: Disables bind/unbind via sysfs.
 * @of_match_table: The open firmware table.
 * @probe:	Called to query the existence of a specific device,
 *		whether this driver can work with it, and bind the driver
 *		to a specific device.
 * @remove:	Called when the device is removed from the system to
 *		unbind a device from this driver.
 * @shutdown:	Called at shut-down time to quiesce the device.
 * @suspend:	Called to put the device to sleep mode. Usually to a
 *		low power state.
 * @resume:	Called to bring a device from sleep mode.
 * @groups:	Default attributes that get created by the driver core
 *		automatically.
 * @pm:		Power management operations of the device which matched
 *		this driver.
 * @p:		Driver core's private data, no one other than the driver
 *		core can touch this.
 *
 * The device driver-model tracks all of the drivers known to the system.
 * The main reason for this tracking is to enable the driver core to match
 * up drivers with new devices. Once drivers are known objects within the
 * system, however, a number of other things become possible. Device drivers
 * can export information and configuration variables that are independent
 * of any specific device.
 */
struct device_driver {
	const char		*name; /*驱动程序的名字( 体现在 sysfs 中 )*/
	struct bus_type		*bus;  /*驱动程序所在的总线*/

	struct module		*owner;
	const char		*mod_name;	/* used for built-in modules */

	bool suppress_bind_attrs;	/* disables bind/unbind via sysfs */

	const struct of_device_id	*of_match_table;

	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);
	const struct attribute_group **groups;

	const struct dev_pm_ops *pm;

	struct driver_private *p;
};

3.1 注册驱动

int driver_register(struct device_driver *drv)
/**
 * driver_register - register driver with bus
 * @drv: driver to register
 *
 * We pass off most of the work to the bus_add_driver() call,
 * since most of the things we have to do deal with the bus
 * structures.
 */
int driver_register(struct device_driver *drv)
{
	int ret;
	struct device_driver *other;

	BUG_ON(!drv->bus->p);

	if ((drv->bus->probe && drv->probe) ||
	    (drv->bus->remove && drv->remove) ||
	    (drv->bus->shutdown && drv->shutdown))
		printk(KERN_WARNING "Driver '%s' needs updating - please use "
			"bus_type methods\n", drv->name);

	other = driver_find(drv->name, drv->bus);
	if (other) {
		put_driver(other);
		printk(KERN_ERR "Error: Driver '%s' is already registered, "
			"aborting...\n", drv->name);
		return -EBUSY;
	}

	ret = bus_add_driver(drv);
	if (ret)
		return ret;
	ret = driver_add_groups(drv, drv->groups);
	if (ret)
		bus_remove_driver(drv);
	return ret;
}

3.2 注销驱动

void driver_unregister(struct device_driver *drv)
/**
 * driver_unregister - remove driver from system.
 * @drv: driver.
 *
 * Again, we pass off most of the work to the bus-level call.
 */
void driver_unregister(struct device_driver *drv)
{
	if (!drv || !drv->p) {
		WARN(1, "Unexpected driver unregister!\n");
		return;
	}
	driver_remove_groups(drv, drv->groups);
	bus_remove_driver(drv);
}

3.3 驱动属性

 驱动的属性使用struct driver_attribute 来描述:
/* sysfs interface for exporting driver attributes */
struct driver_attribute {
	struct attribute attr;
	ssize_t (*show)(struct device_driver *driver, char *buf);
	ssize_t (*store)(struct device_driver *driver, const char *buf,
			 size_t count);
};

3.4 创建驱动属性

int driver_create_file(struct device_driver *drv,const struct driver_attribute *attr);
/**
 * driver_create_file - create sysfs file for driver.
 * @drv: driver.
 * @attr: driver attribute descriptor.
 */
int driver_create_file(struct device_driver *drv,
		       const struct driver_attribute *attr)
{
	int error;
	if (drv)
		error = sysfs_create_file(&drv->p->kobj, &attr->attr);
	else
		error = -EINVAL;
	return error;
}

3.5 删除驱动属性

void driver_remove_file(struct device_driver *drv,const struct driver_attribute *attr);
/**
 * driver_remove_file - remove sysfs file for driver.
 * @drv: driver.
 * @attr: driver attribute descriptor.
 */
void driver_remove_file(struct device_driver *drv,
			const struct driver_attribute *attr)
{
	if (drv)
		sysfs_remove_file(&drv->p->kobj, &attr->attr);
}


设备和驱动什么时候会去相互匹配? 
注册驱动或者注册设备时

驱动和设备怎么匹配? 
由总线的match函数的规则来匹配

4 实例

4.1 总线 bus.c

#include <linux/device.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>

MODULE_AUTHOR("XY");
MODULE_LICENSE("Dual BSD/GPL");

static char *Version = "$Revision: 1.9 $";

static int my_match(struct device *dev, struct device_driver *driver)
{
	// 当驱动注册时,驱动会来总线找能够处理的设备
	// 驱动和设备按照总线这里match函数的规则来匹配
	return !strncmp(dev->bus_id, driver->name, strlen(driver->name));
	// return !strncmp(dev_name(dev), driver->name, strlen(driver->name)); // Linux3.0.8

}

static void my_bus_release(struct device *dev)
{
	printk(KERN_DEBUG "my bus release\n");
}
	
struct device my_bus = {
	.bus_id   = "my_bus0", // linux2.6.22的device结构有bus_id,
	//  .init_name = "my_bus0", // Linux3.0.8用init_name代替
	.release  = my_bus_release//删除设备时调用
};


struct bus_type my_bus_type = {
	.name = "my_bus",// 总线名字
	.match = my_match,// 用于判断指定的驱动程序是否能处理指定的设备
};
//导出结构
EXPORT_SYMBOL(my_bus);
EXPORT_SYMBOL(my_bus_type);


/*
 * Export a simple attribute.
 */
static ssize_t show_bus_version(struct bus_type *bus, char *buf)
{
	return snprintf(buf, PAGE_SIZE, "%s\n", Version);
}

/* include/linux/device.h

#define BUS_ATTR(_name, _mode, _show, _store)   \
        struct bus_attribute bus_attr_##_name = __ATTR(_name, _mode, _show, _store)

==> struct bus_attribute bus_attr_version =
{   attr=>S_IRUGO,
	show=>show_bus_version,
	store=>NULL
 }
*/
static BUS_ATTR(version, S_IRUGO, show_bus_version, NULL);


static int __init my_bus_init(void)
{
	int ret;
        
        /*注册总线*/
	ret = bus_register(&my_bus_type); // 生成/sys/bus/my_bus目录
	if (ret)
		return ret;
		
	/*创建属性文件*/	
	if (bus_create_file(&my_bus_type, &bus_attr_version))
		printk(KERN_NOTICE "Fail to create version attribute!\n");
	
	/*注册总线设备*/
	ret = device_register(&my_bus);
	if (ret)
		printk(KERN_NOTICE "Fail to register device:my_bus!\n");
		
	return ret;
}

static void my_bus_exit(void)
{
	device_unregister(&my_bus);
	bus_unregister(&my_bus_type);
}

module_init(my_bus_init);
module_exit(my_bus_exit);

4.2 设备 device.c

#include <linux/device.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>

MODULE_AUTHOR("XY");
MODULE_LICENSE("Dual BSD/GPL");

extern struct device my_bus; 
extern struct bus_type my_bus_type;

static void my_dev_release(struct device *dev)
{ 
	
}

struct device my_dev = {
	.bus = &my_bus_type,// my_dev这个device挂载在my_bus_type总线(总线名叫my_bus)上
	.parent = &my_bus,// my_dev的父设备是my_bus0(总线设备),总线也是一个设备
	.release = my_dev_release,
};

/*
 * Export a simple attribute.
 */
static ssize_t mydev_show(struct device *dev, char *buf)
{
	return sprintf(buf, "%s\n", "This is my device!");
}

static DEVICE_ATTR(dev, S_IRUGO, mydev_show, NULL);

static int __init my_device_init(void)
{
	int ret = 0;
        
        /* 初始化设备 */
	strncpy(my_dev.bus_id, "my_dev", BUS_ID_SIZE); // linux 2.6.22
	// dev_set_name(&dev, "name"); // linux 3.0.8版本使用 device结构没有bus_id成员
        
        /*注册设备*/
	device_register(&my_dev); // 生成/sys/bus/busname/devices/my_dev -> /sys/devices/my_bus0/my_dev
		
	/*创建属性文件 /sys/devices/my_bus0/my_dev/dev ? */
	device_create_file(&my_dev, &dev_attr_dev);
	
	return ret;	

}

static void my_device_exit(void)
{
	device_unregister(&my_dev);
}

module_init(my_device_init);
module_exit(my_device_exit);

4.3 驱动 driver.c

#include <linux/device.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>

MODULE_AUTHOR("XY");
MODULE_LICENSE("Dual BSD/GPL");

extern struct bus_type my_bus_type;

static int my_probe(struct device *dev)
{
    // 驱动注册,找到总线上能够处理的设备后,执行probe函数 
    // 如果先注册驱动,再注册设备,注册设备后总线会遍历所有的驱动,看那个驱动可以处理
    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,// 能使用的设备被删除时调用
};

/*
 * Export a simple attribute.
 * 应用程序read该drv属性时调用
 */
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);

5 sysfs文件系统

上面总线、设备、驱动的注册操作都是基于sysfs文件系统,如果详细研究上面注册函数,会发现在/sys目录下创建目录或者创建文件是使用kobject和kset来完成的。

"sysfs is a ram-based filesystem initiallybased on ramfs. It provides a means to export kernel data structures, their attributes, and the linkages between them to userspace.”
--- documentation/filesystems/sysfs.txt

sysfs 被看成是与 proc同类别的文件系统。sysfs 把连接在系统上的设备和总线组织成分级的文件,使其从用户空间可以访问到。

Sysfs 被加载在 /sys/ 目录下,它的子目录包括:
Block:在系统中发现的每个块设备在该目录下对应一个子目录。每个子目录中又包含一些属性文件,它们描述了这个块设备的各方面属性,如:设备大小。(loop块设备是使用文件来模拟的)
Bus:在内核中注册的每条总线在该目录下对应一个子目录, 如:ide pci scsi usb pcmcia
其中每个总线目录内又包含两个子目录:devices 和 drivers , devices目录包含了在整个系统中发现的属于该总线类型的设备,drivers目录包含了注册到该总线的所有驱动。
Class:将设备按照功能进行的分类,如/sys/class/net目录下包含了所有网络接口。
Devices:包含系统所有的设备。
Kernel:内核中的配置参数
Module:系统中所有模块的信息
Firmware:系统中的固件
Fs:描述系统中的文件系统
Power:系统中电源选项

5.1 Kobject结构

Kobject 实现了基本的面向对象管理机制,是构成设备模型的核心结构。它与sysfs文件系统紧密相连,在内核中注册的 每个kobject对象对应sysfs文件系统中的一个目录
struct kobject {
    const char *name;
    struct list_head entry;
    struct kobject *parent; //指向父对象
    struct kset *kset;
    struct kobj_type *ktype;
    struct sysfs_dirent *sd;
    struct kref kref; //对象引用计数
    unsigned int state_initialized:1;
    unsigned int state_in_sysfs:1;
    unsigned int state_add_uevent_sent:1;
    unsigned int state_remove_uevent_sent:1;
};

void kobject_init(struct kobject * kobj)
初始化kobject结构

int kobject_add(struct kobject * kobj)
将kobject对象注册到Linux系统

int kobject_init_and_add(struct kobject *kobj, struct kobj_type *ktype,struct kobject *parent,const char*fmt, ...)
初始化kobject,并将其注册到linux系统

void kobject_del(struct kobject * kobj)
从Linux系统中删除kobject对象

struct kobject *kobject_get(struct kobject *kobj)
将kobject对象的引用计数加1,同时返回该对象指针。

void kobject_put(struct kobject * kobj)
将kobject对象的引用计数减1,如果引用计数降为0,则调用release方法释放该kobject对象。

Kobject的ktype成员是一个指向kobj_type结构的指针,该结构中记录了kobject对象的一些属性。
struct kobj_type {
    void (*release)(struct kobject *kobj);
    struct sysfs_ops *sysfs_ops;
    struct attribute **default_attrs;
};
   
   
struct attribute {
char * name; /*属性文件名*/
struct module * owner;
mode_t mode; /*属性的保护位*/
};
struct sysfs_ops
{
ssize_t (*show)(struct kobject *, struct attribute *,char *);
ssize_t (*store)(struct kobject *,struct attribute *,const char *,size_t);
};
release:用于释放kobject占用的资源,当kobject的引用计数为0时被调用。

struct attribute ( 属性): 对应于kobject的目录下的一个文件,Name成员就是文件名。

• Show:当用户读属性文件时,该函数被调用,该函数将属性值存入buffer中返回给用户态;
• Store:当用户写属性文件时,该函数被调用,用于存储用户传入的属性值。

5.2 Kset结构

kset是具有相同类型的kobject的集合,在sysfs中体现成 一个目录(可以包含目录的目录),在内核中用kset数据结构表示,定义为:
struct kset {
    struct list_head list; //连接该kset中所有kobject的链表头
    spinlock_t list_lock;
    struct kobject kobj; //内嵌的kobject
    struct kset_uevent_ops *uevent_ops; //处理热插拔事件的操作集合
}

int kset_register(struct kset *kset)
在内核中注册一个kset
void kset_unregister(struct kset *kset)
从内核中注销一个kset

热插拔事件
在Linux系统中,当 系统配置发生变化时,如:添加kset到系统;移动kobject, 一个通知会从内核空间发送到用户空间,这就是热插拔事件。热插拔事件会导致用户空间中相应的处理程序(如udev,mdev)被调用, 这些处理程序会通过加载驱动程序, 创建设备节点等来响应热插拔事件。
Struct kset_uevent_ops {
    int (*filter)(struct kset *kset, struct kobject *kobj);
    const char *(*name)(struct kset *kset, struct kobject *kobj);
    int (*uevent)(struct kset *kset, struct kobject *kobj,
    struct kobj_uevent_env *env);
}

当该kset所管理的kobject和kset状态发生变化时(如被加入,移动),这三个函数将被调用。
filter:决定是否将事件传递到用户空间。如果 filter返回 0,将不传递事件。(例: uevent_filter)
name:用于将字符串传递给用户空间的热插拔处理程序。
uevent:将用户空间需要的参数添加到环境变量中。(例:dev_uevent)
 

5.3 实例

kobject实例
#include <linux/device.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/stat.h>
 
MODULE_AUTHOR("XY");
MODULE_LICENSE("Dual BSD/GPL");
 
void obj_test_release(struct kobject *kobject);
ssize_t kobj_test_show(struct kobject *kobject, struct attribute *attr,char *buf);
ssize_t kobj_test_store(struct kobject *kobject,struct attribute *attr,const char *buf, size_t count);
 
struct attribute test_attr = {
        .name = "kobj_config",//对应于kobject的目录下的一个文件,Name成员就是文件名
        .mode = S_IRWXUGO,// 读写权限
};
 
static struct attribute *def_attrs[] = {
        &test_attr, 
        NULL,
};
 
 
struct sysfs_ops obj_test_sysops =
{
        .show = kobj_test_show,    //当用户读属性文件时,该函数被调用,该函数将属性值存入buffer中返回给用户态;
        .store = kobj_test_store,  //当用户写属性文件时,该函数被调用,用于存储用户传入的属性值。
};
// 记录了kobject对象的一些属性
struct kobj_type ktype = 
{
        .release = obj_test_release,  //用于释放kobject占用的资源
        .sysfs_ops=&obj_test_sysops,  
        .default_attrs=def_attrs,    
};
 
void obj_test_release(struct kobject *kobject)
{
        printk("eric_test: release .\n");
}
 
ssize_t kobj_test_show(struct kobject *kobject, struct attribute *attr,char *buf)
{
        printk("have show.\n");
        printk("attrname:%s.\n", attr->name);
        sprintf(buf,"%s\n",attr->name);
        return strlen(attr->name)+2;
}
 
ssize_t kobj_test_store(struct kobject *kobject,struct attribute *attr,const char *buf, size_t count)
{
        printk("havestore\n");
        printk("write: %s\n",buf);
        return count;
}
 
struct kobject kobj;
static int kobj_test_init()
{
        printk("kboject test init.\n");
		// 初始化kobject,并将其注册到linux系统,对应sysfs文件系统中的一个目录
        kobject_init_and_add(&kobj,&ktype,NULL,"kobject_test");
        return 0;
}
 
static int kobj_test_exit()
{
        printk("kobject test exit.\n");
        kobject_del(&kobj);
        return 0;
}
 
module_init(kobj_test_init);
module_exit(kobj_test_exit);

kset实例
#include <linux/device.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/stat.h>
#include <linux/kobject.h>
 
MODULE_AUTHOR("David Xie");
MODULE_LICENSE("Dual BSD/GPL");
 
struct kset kset_p;
struct kset kset_c;

int kset_filter(struct kset *kset, struct kobject *kobj)
{
        printk("Filter: kobj %s.\n",kobj->name);
		//如果 filter返回 0,将不传递事件
        return 1;
}
 
const char *kset_name(struct kset *kset, struct kobject *kobj)
{
        static char buf[20];
        printk("Name: kobj %s.\n",kobj->name);
        sprintf(buf,"%s","kset_name");
        return buf;
}
 
int kset_uevent(struct kset *kset, struct kobject *kobj,struct kobj_uevent_env *env)
{
        int i = 0;
        printk("uevent: kobj %s.\n",kobj->name);

        while( i < env->envp_idx){
                printk("%s.\n",env->envp[i]);
                i++;
        }

        return 0;
}

struct kset_uevent_ops uevent_ops = 
{
        .filter = kset_filter,// 决定是否将事件传递到用户空间,首先调用
        .name   = kset_name,//用于将字符串传递给用户空间的热插拔处理程序。
        .uevent = kset_uevent,//将用户空间需要的参数添加到环境变量中。
};
 
int kset_test_init()
{
        printk("kset test init.\n");
        kobject_set_name(&kset_p.kobj,"kset_p");
        kset_p.uevent_ops = &uevent_ops;// kset_p下的配置发生变化时调用
        kset_register(&kset_p); //在内核中注册一个kset
 
        kobject_set_name(&kset_c.kobj,"kset_c");
        kset_c.kobj.kset = &kset_p;// kset_c目录在kset_c目录底下: /sys/kset_p/kset_c/
        kset_register(&kset_c);
        return 0;
}
 
int kset_test_exit()
{
        printk("kset test exit.\n");
        kset_unregister(&kset_p);
        kset_unregister(&kset_c);
        return 0;
}
 
module_init(kset_test_init);
module_exit(kset_test_exit);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值