2

I am writing a simple Linux driver with multiple device attributes. Now independently to which attribute you read or write, in the end you will read or write somewhere on the device's memory. Only the offset defining the exact position changes from one attribute to another. This is easier explained with a few lines of code:

/* General read function evoked by attributes */
static const ssize_t foo_show(struct device *dev,
    struct device_attribute *attr, char *buf)
{
    u32 offset;

    if (attr->attr.name == "control")
        offset = OFFSET_CTRL;
    else if (attr->attr.name == "status")
        offset = OFFSET_STATUS;

    u32 data = ioread32(dev_mem + offset);
    ...
}

...

/* declaring attributes, all linking to the same function */
static DEVICE_ATTR(control, S_IWUGO | S_IRUGO, foo_show, foo_set);
static DEVICE_ATTR(status, S_IRUGO, foo_show, NULL);

Now as you may guess using attr->attr.name == foo is not really a nice way of doing it especially since I get the warning "comparison with string literal results in unspecified behavior" telling me to use strcmp. Do you know any better way to identify which attribute was responsible for the call?

Community
  • 1
  • 1
lorenzli
  • 620
  • 1
  • 10
  • 31

2 Answers2

3

The way this seems to be done in existing drivers is to compare to the global attribute directly.

static DEVICE_ATTR(control, S_IWUGO | S_IRUGO, foo_show, foo_set);
static DEVICE_ATTR(status, S_IRUGO, foo_show, NULL);

static const ssize_t foo_show(struct device *dev,
    struct device_attribute *attr, char *buf)
{
    u32 offset;

    if (attr == &dev_attr_control)
        offset = OFFSET_CTRL;
    else if (attr == &dev_attr_status)
        offset = OFFSET_STATUS;
nos
  • 223,662
  • 58
  • 417
  • 506
1

Attributes can identified only based on name. Since only two fields available in attribute by default. http://lxr.free-electrons.com/source/include/linux/sysfs.h#L29

kernel space implementation of strcmp() is available. So using it will works. http://lxr.free-electrons.com/source/lib/string.c#L245

Jeyaram
  • 9,158
  • 7
  • 41
  • 63