Re: [PATCH 1/3] tools/power turbostat: avoid segfault referencing fd_instr_count_percpu
From: Len Brown
Date: Tue Nov 25 2025 - 14:11:42 EST
not your fault, but looking at this code, it seems that
get_instr_count_fd(base_cpu)
assumes that 0 is an invalid FD. Fine, but based on that you'd think
we'd use zero for invalid
and non-zero for valid as return for the function call...
On Tue, Nov 18, 2025 at 10:58 AM David Arcari <darcari@xxxxxxxxxx> wrote:
>
> The problem is that fd_instr_count_percpu is allocated based on
> the value of has_aperf. If has_aperf=0 then fd_instr_count_percpu
> remains NULL. However, get_instr_count_fd() is called from
> turbostat_init() based on the value of has_aperf_access.
>
> On some VM systems has_aperf can be 0, while has_aperf_access can be
> 1. In order to resolve the issue simply check for to see if
> fd_instr_count_percpu is NULL and return -1 if it is. Accordingly,
> the has_aperf_access check can be removed from turbostat_init.
>
> Signed-off-by: David Arcari <darcari@xxxxxxxxxx>
> Cc: Len Brown <lenb@xxxxxxxxxx>
> Cc: linux-kernel@xxxxxxxxxxxxxxx
> ---
> tools/power/x86/turbostat/turbostat.c | 5 ++++-
> 1 file changed, 4 insertions(+), 1 deletion(-)
>
> diff --git a/tools/power/x86/turbostat/turbostat.c b/tools/power/x86/turbostat/turbostat.c
> index f2512d78bcbd..584b0f7f9067 100644
> --- a/tools/power/x86/turbostat/turbostat.c
> +++ b/tools/power/x86/turbostat/turbostat.c
> @@ -2463,6 +2463,9 @@ static long open_perf_counter(int cpu, unsigned int type, unsigned int config, i
>
> int get_instr_count_fd(int cpu)
> {
> + if (!fd_instr_count_percpu)
> + return -1;
> +
> if (fd_instr_count_percpu[cpu])
> return fd_instr_count_percpu[cpu];
>
> @@ -10027,7 +10030,7 @@ void turbostat_init()
> for_all_cpus(get_cpu_type, ODD_COUNTERS);
> for_all_cpus(get_cpu_type, EVEN_COUNTERS);
>
> - if (BIC_IS_ENABLED(BIC_IPC) && has_aperf_access && get_instr_count_fd(base_cpu) != -1)
> + if (BIC_IS_ENABLED(BIC_IPC) && get_instr_count_fd(base_cpu) != -1)
> BIC_PRESENT(BIC_IPC);
>
> /*
> --
> 2.51.0
>
>
--
Len Brown, Intel Open Source Technology Center