Драйвер ядра i2c - привязка между sysfs kobject и i2c_client - PullRequest
0 голосов
/ 25 февраля 2019

Я работаю над драйвером ядра I2C и хотел бы предоставить интерфейс файла sysfs в новой папке - / sys / devices / MySensor.Однако, когда я делаю это, я не знаю, как связать клиента i2c с новым kobject.

Следовательно, когда вызываются функции моего атрибута устройства, переданный объект устройства не позволяет мне получитьзарегистрированный клиент i2c.

Я объявляю свой атрибут следующим образом:

static ssize_t my_sensor_do_something(struct device *dev, struct device_attribute *attr, char *buf)

{
    struct i2c_client *client;
    struct my_sensor_data *data;
    int size = 0;

    client = to_i2c_client(dev);

    my_sensor_dbgmsg("Client Address:0x%02x\n", client->addr);

    data = i2c_get_clientdata(client);

    return 0
}
static DEVICE_ATTR(do_something, S_IRUGO, my_sensor_do_something, NULL);

static struct attribute *my_sensor_attributes[] = {
    &dev_attr_do_something.attr,
    NULL
};

static const struct attribute_group my_sensor_attr_group = {
    .attrs = my_sensor_attributes,
};

Затем в моей функции зонда создайте мою подпапку

struct device *my_dev = root_device_register("my_sensor");
err = sysfs_create_group(&my_dev->kobj, &my_sensor_attr_group);

Подпапка иФайл do_something создается в / sys / kernel /, однако при вызове do_something () попытка получить клиент I2C завершается неудачно - client-> addr равен 0, а i2c_get_client_data возвращает ноль.

Для справки, i2cустройство определено в дереве устройств, и я могу успешно добавить атрибуты устройства в существующую папку

err = sysfs_create_group(client->dev.kobj, &my_sensor_attr_group);
/sys/bus/i2c/devices/i2c-7/7-004c/

Извинения, если этот вопрос является расплывчатым или недостаточно подробным.Я относительно новичок в этом.

Кто-нибудь знает, что мне не хватает, когда я создаю новую папку sysfs, чтобы связать это с моим зарегистрированным клиентом i2c?

Спасибо

1 Ответ

0 голосов
/ 26 февраля 2019

Вы можете поставить client на my_dev во время инициализации.

dev_set_drvdata(my_dev, client);

Затем в функции my_sensor_do_something используйте dev_get_drvdata, чтобы вывести client out

client = dev_get_drvdata(dev);

Полный пример выглядит следующим образом

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>

static ssize_t my_sensor_do_something(struct device *dev,
                                  struct device_attribute *attr, char *buf)
{
    struct i2c_client *client;
    void *data;

    client = dev_get_drvdata(dev);
    data = i2c_get_clientdata(client);
    pr_info("Client Address:0x%02x Data:%p\n", client->addr, data);

    return 0;
}

static DEVICE_ATTR(do_something, 0444, my_sensor_do_something, NULL);

static struct attribute *my_sensor_attributes[] = {
    &dev_attr_do_something.attr,
    NULL
};

static const struct attribute_group my_sensor_attr_group = {
    .attrs = my_sensor_attributes,
};

static struct device *my_dev;
static void my_sensor_create(struct i2c_client *client)
{
    int err;

    my_dev = root_device_register("my_sensor");
    dev_set_drvdata(my_dev, client);
    err = sysfs_create_group(&my_dev->kobj, &my_sensor_attr_group);
    if (err)
            pr_info("sysfs_create_group failure.\n");
}

struct test_device {
    struct i2c_client *client;
};

static int test_i2c_probe(struct i2c_client *client,
                      const struct i2c_device_id *id)
{
    struct test_device *dev;

    dev = kzalloc(sizeof(struct test_device), GFP_KERNEL);
    if (dev == NULL)
            return -ENOMEM;

    dev->client = client;
    i2c_set_clientdata(client, dev);
    my_sensor_create(client);

    return 0;
}

static int test_i2c_remove(struct i2c_client *client)
{
    struct test_client *dev = i2c_get_clientdata(client);

    if (my_dev)
            root_device_unregister(my_dev);

    kfree(dev);
    return 0;
}

static const struct i2c_device_id test_i2c_id[] = {
    {"test_i2c_client", 0},
    {}
};

static struct i2c_driver test_i2c_driver = {
    .driver   = { .name = "test_i2c_client", },
    .probe    = test_i2c_probe,
    .remove   = test_i2c_remove,
    .id_table = test_i2c_id,
};

static int __init test_i2c_init_driver(void)
{
    return i2c_add_driver(&test_i2c_driver);
}

static void __exit test_i2c_exit_driver(void)
{
    i2c_del_driver(&test_i2c_driver);
}

module_init(test_i2c_init_driver);
module_exit(test_i2c_exit_driver);

MODULE_LICENSE("GPL");
...