[PATCH v2 1/3] perf/x86/core: Use sysfs_emit() in show() callback function

From: Deepak R Varma
Date: Tue Feb 21 2023 - 09:07:24 EST


As per C99 standard, snprintf() returns the number of bytes that would
be encoded in the destination buffer when it is sufficiently large. This
return value may be different from what the caller is expecting and hence
may lead to potential errors in the program.
Kernel release 2.6.2 introduced scnprintf() & vscnprintf() which precisely
return the actual bytes encoded into the destination buffer.

For the sysfs attribute show() callback functions, which returns the number
of bytes to the user space, a more recent recommendation is to use
sysfs_emit() or sysfs_emit_at() instead of sprintf() family of functions.
This is recorded in the Documentation/filesystems/sysfs.rst Kernel
documentation file.

Issue identified using the coccinelle device_attr_show.cocci script.

Signed-off-by: Deepak R Varma <drv@xxxxxxxxx>
---
Changes in v2:
- Revise patch log message to include details on the potential issues with
current implementation and how the proposal is a better solution.
Feedback provided by Peter Zijlstra <peterz@xxxxxxxxxxxxx>

arch/x86/events/core.c | 8 +++-----
1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/arch/x86/events/core.c b/arch/x86/events/core.c
index 85a63a41c471..27c03e6dcb5d 100644
--- a/arch/x86/events/core.c
+++ b/arch/x86/events/core.c
@@ -1896,9 +1896,7 @@ ssize_t events_hybrid_sysfs_show(struct device *dev,
if (x86_pmu.hybrid_pmu[i].cpu_type & pmu->cpu_type) {
next_str = strchr(str, ';');
if (next_str)
- return snprintf(page, next_str - str + 1, "%s", str);
- else
- return sprintf(page, "%s", str);
+ return sysfs_emit(page, "%s", str);
}
str = strchr(str, ';');
str++;
@@ -2544,7 +2542,7 @@ static ssize_t get_attr_rdpmc(struct device *cdev,
struct device_attribute *attr,
char *buf)
{
- return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
+ return sysfs_emit(buf, "%d\n", x86_pmu.attr_rdpmc);
}

static ssize_t set_attr_rdpmc(struct device *cdev,
@@ -2602,7 +2600,7 @@ static ssize_t max_precise_show(struct device *cdev,
struct device_attribute *attr,
char *buf)
{
- return snprintf(buf, PAGE_SIZE, "%d\n", x86_pmu_max_precise());
+ return sysfs_emit(buf, "%d\n", x86_pmu_max_precise());
}

static DEVICE_ATTR_RO(max_precise);
--
2.34.1