Re: [RFC Patch v2 1/3] i2c debug counters as sysfs attributes

Joe Perches
2021-12-03T05:54:33Z

On Thu, 2021-12-02 at 18:37 -0800, Sui Chen wrote:
> This change adds a few example I2C debug counters as sysfs attributes:
> - ber_cnt (bus error count)
> - nack_cnt (NACK count)
> - rec_fail_cnt, rec_succ_cnt (recovery failure/success count)
> - timeout_cnt (timeout count)
> - i2c_speed (bus frequency)
> - tx_complete_cnt (transaction completed, including both as an initiator
> and as a target)
>
> The function i2c_adapter_create_stats_folder creates a stats directory
> in the device's sysfs directory to hold the debug counters. The platform
> drivers are responsible for instantiating the counters in the stats
> directory if applicable.
[]
> diff --git a/drivers/i2c/i2c-dev.c b/drivers/i2c/i2c-dev.c
[]
> +void i2c_adapter_create_stats_folder(struct i2c_adapter* adapter) {
> + adapter->stats = kzalloc(sizeof(struct i2c_adapter_stats), GFP_KERNEL);

unchecked alloc, could fail.

> + adapter->stats->kobj = kobject_create_and_add("stats", &adapter->dev.kobj);;
> +}
> +
> +void i2c_adapter_stats_register_counter(struct i2c_adapter* adapter,
> + const char* counter_name, void* data_source) {
> + int ret;
> + if (adapter->stats == NULL) {
> + i2c_adapter_create_stats_folder(adapter);
> + }

So all of these adapter->stats dereferences could oops.

> + if (!strcmp(counter_name, "ber_cnt")) {
> + adapter->stats->ber_cnt = data_source;
> + ret = sysfs_create_file(adapter->stats->kobj, &dev_attr_ber_cnt.attr);
> + } else if (!strcmp(counter_name, "nack_cnt")) {
> + adapter->stats->nack_cnt = data_source;
> + ret = sysfs_create_file(adapter->stats->kobj, &dev_attr_nack_cnt.attr);
> + } else if (!strcmp(counter_name, "rec_succ_cnt")) {
> + adapter->stats->rec_succ_cnt = data_source;
> + ret = sysfs_create_file(adapter->stats->kobj, &dev_attr_rec_succ_cnt.attr);
> + } else if (!strcmp(counter_name, "rec_fail_cnt")) {
> + adapter->stats->rec_fail_cnt = data_source;
> + ret = sysfs_create_file(adapter->stats->kobj, &dev_attr_rec_fail_cnt.attr);
> + } else if (!strcmp(counter_name, "timeout_cnt")) {
> + adapter->stats->timeout_cnt = data_source;
> + ret = sysfs_create_file(adapter->stats->kobj, &dev_attr_timeout_cnt.attr);
> + } else if (!strcmp(counter_name, "i2c_speed")) {
> + adapter->stats->i2c_speed = data_source;
> + ret = sysfs_create_file(adapter->stats->kobj, &dev_attr_i2c_speed.attr);
> + } else if (!strcmp(counter_name, "tx_complete_cnt")) {
> + adapter->stats->tx_complete_cnt = data_source;
> + ret = sysfs_create_file(adapter->stats->kobj, &dev_attr_tx_complete_cnt.attr);
> + }

and if none of the strcmp comparisons match, ret is uninitialized.

> +
> + if (ret) {
> + printk("Failed to create sysfs file for %s", counter_name);

pr_<level> and should have a terminating newline