Daily Archives: 2014-08-31

VoCore: Driver Attribute

I need to export flash factory id to user space, but current m25p80.c do not support that. My old blog has get that id, and output it into log.
Now move a little forward, show it in user space.

We can get the id by cat its interface.

cat /sys/devices/10000000.palmbus/10000b00.spi/spi_master/spi32766/spi32766.0/factory_id
D16330-6417232123

The code is simple, need to change two parts of the source.
First add attribute to m25p80.c

static ssize_t m25p_factory_id_show(struct device *dev,
    struct device_attribute *attr, char *buf)
{
    const struct spi_device *spi = to_spi_device(dev);
    u8          code[5], id[8];

    code[0] = OPCODE_FACTORY_ID;
    if(spi_write_then_read(spi, &code, 5, id, 8) < 0)
        return sprintf(buf, "\n");
    return sprintf(buf, "%02X%02X%02X-%02X%02X%02X%02X%02X\n",
        id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7]);
}

static DEVICE_ATTR(factory_id, S_IRUGO, m25p_factory_id_show, NULL);

DEVICE_ATTR is used to declare attribute, it has four parameters:
factory_id is the name, that is also the attribute file name in sys folder.
S_IRUGO is the file access privilege, S_IRUGO = r--r--r--
m25p_factory_id_show is a callback once user call standard read through factory_id(that sys attribute interface file).
NULL is a callback for standard write, but we do not need that for current usage, so it is null.

OPCODE_FACTORY_ID is 0x4b, that is from datasheet. Looks like every SPI flash chip has that interface and a factory id, so why not make it as a public attribute?

Now, the attribute interface is ready.
We put the following code into m25p_probe(before return), so once the driver is ready, this attribute will show in the sys folder.

    device_create_file(&spi->dev, &dev_attr_factory_id);

Also will commit a patch to openwrt.org, need some time learn how to do that. 🙂