1、定义数据结构
static struct hw_ps_plat_data platform_data = {
.dev_name = "/dev/ttyAMA4",
.flow_cntrl = 1,
.baud_rate = 115200,
.ldisc_install = 0,
};
static struct platform_device bfg_device = {
.name = "hw-ps",
.id = -1,
.dev = {
.platform_data = &platform_data,
},
};
2、编写show和store函数
static ssize_t show_install(struct device *dev, struct device_attribute *attr, char *buf)
{
retrun sprintf(buf, "%d\n", platform_data.ldisc_install);
}
static size_t show_dev_name(struct device *dev, struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", platform_data.dev_name);
}
static size_t show_baud_rate(struct device *dev, struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%ld\n", platform_data.baud_rate);
}
static size_t show_flow_cntrl(struct device *dev, struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", platform_data.flow_cntrl);
}
3、填充属性
static struct kobj_attribute ldisc_install = __ATTR(install, 0444, (void *)show_install, NULL);
static struct kobj_attribute uart_dev_name = _ATTR(dev_name, 0444, (void *)show_dev_name, NULL);
static struct kobj_attribute uart_flow_cntrl = __ATTR(flow_cntrl, 0444, (void *)show_flow_cntrl, NULL);
static struct kobj_attribute uart_baud_rate = __ATTR(baud_rate, 0444, (void *)show_baud_rate, NULL);
static struct attribute *uim_attrs[] = {
&ldisc_install.attr,
&uart_dev_name.attr,
&uart_baud_rate.attr,
&uart_flow_cntrl.attr,
NULL,
};
static struct attribute_group uim_attr_grp = {
.attrs = uim_attrs,
};
4、创建sysfs节点
int status;
/* 这里是在当前环境下创建节点,这时不需要调用kobject_create_and_and() */
status = sysfs_create_group(&pdev->dev.kobj, &uim_attr_grp);
if (status) {
... //进行错误处理
return -EFAULT;
}
注意事项:
·缓冲区(即buf指针指向的区域)的大小应总为PAGE_SIZE个字节。在i386上,PAGE_SIZE = 4096.
·show方法应该返回放入缓冲区的字节数,即snprintf的返回值。
·show方法因该总是使用snprintf.
·store方法应该返回实际使用的字节数,可以使用strnlen来得到。
·show方法和store方法可能失败,所以当失败时返回错误值。
下面的代码展示了device属性的一个简单的实现:
static ssize_t show_name(struct device *dev, struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%s\n", dev->name);
}
static ssize_t store_name(struct device *dev, const char *buf)
{
sscan(buf, "%s\n", dev->name);
return strnlen(buf, PAGE_SIZE);
}
static DEVICE_ATTR(name, S_IRUGO, show_name, store_name);
注意:实际使用时,并不允许从用户空间设置设备的名字,这里仅是举个例子。
·