Re: [PATCH] ptp: Replace snprintf in show functions with sysfs_emit

From: Joe Perches
Date: Tue Nov 09 2021 - 21:34:41 EST


On Wed, 2021-11-10 at 02:23 +0000, cgel.zte@xxxxxxxxx wrote:
> From: Jing Yao <yao.jing2@xxxxxxxxxx>
>
> coccicheck complains about the use of snprintf() in sysfs show
> functions:
> WARNING use scnprintf or sprintf
>
> Use sysfs_emit instead of scnprintf, snprintf or sprintf makes more
> sense.
[]
> Reported-by: Zeal Robot <zealci@xxxxxxxxxx>
> Signed-off-by: Jing Yao <yao.jing2@xxxxxxxxxx>
[]
> diff --git a/drivers/ptp/ptp_sysfs.c b/drivers/ptp/ptp_sysfs.c
[]
> @@ -86,7 +86,7 @@ static ssize_t extts_fifo_show(struct device *dev,
> if (!qcnt)
> goto out;
>
> - cnt = snprintf(page, PAGE_SIZE, "%u %lld %u\n",
> + cnt = sysfs_emit(page, "%u %lld %u\n",
> event.index, event.t.sec, event.t.nsec);
> out:
> mutex_unlock(&ptp->tsevq_mux);
> @@ -387,7 +387,7 @@ static ssize_t ptp_pin_show(struct device *dev, struct device_attribute *attr,
>
> mutex_unlock(&ptp->pincfg_mux);
>
> - return snprintf(page, PAGE_SIZE, "%u %u\n", func, chan);
> + return sysfs_emit(page, "%u %u\n", func, chan);
> }
>
> static ssize_t ptp_pin_store(struct device *dev, struct device_attribute *attr,

If you are going to try to fix these, please do try to fix all of
the instances in the same file.

So here's a macro definition from that file used multiple times:

static ssize_t var##_show(struct device *dev, \
struct device_attribute *attr, char *page) \
{ \
struct ptp_clock *ptp = dev_get_drvdata(dev); \
return snprintf(page, PAGE_SIZE-1, "%d\n", ptp->info->var); \
} \
static DEVICE_ATTR(name, 0444, var##_show, NULL);

and another function:

static ssize_t n_vclocks_show(struct device *dev,
struct device_attribute *attr, char *page)
{
struct ptp_clock *ptp = dev_get_drvdata(dev);
ssize_t size;

if (mutex_lock_interruptible(&ptp->n_vclocks_mux))
return -ERESTARTSYS;

size = snprintf(page, PAGE_SIZE - 1, "%u\n", ptp->n_vclocks);

mutex_unlock(&ptp->n_vclocks_mux);

return size;
}

and yet another function:

static ssize_t max_vclocks_show(struct device *dev,
struct device_attribute *attr, char *page)
{
struct ptp_clock *ptp = dev_get_drvdata(dev);
ssize_t size;

size = snprintf(page, PAGE_SIZE - 1, "%u\n", ptp->max_vclocks);

return size;
}