</>EmbeddedInterview

What is sysfs and how do you add attributes?

MediumLinux Kernel & Device Drivers

Short answer: Sysfs (/sys) exposes the kernel's device model as a directory tree: each device is a directory, and each attribute is a file holding one value (in text). Drivers add attributes with DEVICE_ATTR_RW(name) plus name_show()/name_store() functions, group them, and attach the group through the driver's .dev_groups field so they are created and removed together with the device (no race with user space).

static ssize_t gain_show(struct device *dev, struct device_attribute *attr, char *buf)
{
    struct mydev *d = dev_get_drvdata(dev);
    return sysfs_emit(buf, "%u\n", d->gain);
}

static ssize_t gain_store(struct device *dev, struct device_attribute *attr,
                          const char *buf, size_t count)
{
    struct mydev *d = dev_get_drvdata(dev);
    unsigned int val;
    int ret = kstrtouint(buf, 0, &val);
    if (ret) return ret;
    if (val > 7) return -EINVAL;
    mutex_lock(&d->lock);
    d->gain = val;
    mydev_apply_gain(d);
    mutex_unlock(&d->lock);
    return count;
}
static DEVICE_ATTR_RW(gain);

static struct attribute *mydev_attrs[] = { &dev_attr_gain.attr, NULL };
ATTRIBUTE_GROUPS(mydev);                     /* defines mydev_groups */

static struct platform_driver mydev_driver = {
    .driver = { .name = "mydev", .of_match_table = mydev_of_match, .dev_groups = mydev_groups },
    .probe = mydev_probe,
};

Use: cat /sys/bus/platform/devices/40010000.mydev/gain, echo 3 > .../gain.

Rules

  • One value per file; text format; sysfs_emit() in show functions (bounds-safe).
  • Attributes are ABI: document them in Documentation/ABI/ and do not change them casually.
  • Validate input in store and return count on success or a negative error.
  • DEVICE_ATTR_RO / _WO for read-only/write-only; binary attributes for blobs (e.g. EEPROM contents).
  • For debug-only data, use debugfs instead (next question).