dev_set_drvdata和dev_get_drvdata函数

 dev_set_drvdata函数用来设置device 的私有数据,

dev_get_drvdata函数用来获取device 的私有数据。

两个函数的定义如下:

/*
 * These exports can't be _GPL due to .h files using this within them, and it
 * might break something that was previously working...
 */
void *dev_get_drvdata(const struct device *dev)
{
	if (dev && dev->p)
		return dev->p->driver_data;
	return NULL;
}
EXPORT_SYMBOL(dev_get_drvdata);

int dev_set_drvdata(struct device *dev, void *data)
{
	int error;

	if (!dev->p) {
		error = device_private_init(dev);
		if (error)
			return error;
	}
	dev->p->driver_data = data;
	return 0;
}
EXPORT_SYMBOL(dev_set_drvdata);

dev_set_drvdata函数一般在初始化 dev后执行, dev_get_drvdata函数主要在于其他子系统交互的函数中执行,用来获取当前driver data。

举例参考:

  power_supply_core.c文件中,  dev_set_drvdata函数在power_supply_register中初始化,

  其他驱动调用power_supply_register注册power_supply。

int power_supply_register(struct device *parent, struct power_supply *psy)
{
	struct device *dev;
	int rc;

	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
	if (!dev)
		return -ENOMEM;

	device_initialize(dev);

	dev->class = power_supply_class;
	dev->type = &power_supply_dev_type;
	dev->parent = parent;
	dev->release = power_supply_dev_release;
	dev_set_drvdata(dev, psy);
	psy->dev = dev;

    ............
}

对dev初始化完毕后执行dev_set_drvdata,保存驱动的私有数据。

static int __power_supply_is_system_supplied(struct device *dev, void *data)
{
	union power_supply_propval ret = {0,};
	struct power_supply *psy = dev_get_drvdata(dev);
	unsigned int *count = data;

	(*count)++;
	if (psy->type != POWER_SUPPLY_TYPE_BATTERY) {
		if (psy->get_property(psy, POWER_SUPPLY_PROP_ONLINE, &ret))
			return 0;
		if (ret.intval)
			return ret.intval;
	}
	return 0;
}

在__power_supply_is_system_supplied函数中调用dev_get_drvdata获取device的私有数据,这样不同的驱动使用power_supply_register注册,都能够获取到对应的device数据。

 

 

你可能感兴趣的:(其它总结)