Skip to content

Commit a1a7eb8

Browse files
Nikolay Kuratovrostedt
authored andcommitted
ftrace: Avoid potential division by zero in function_stat_show()
Check whether denominator expression x * (x - 1) * 1000 mod {2^32, 2^64} produce zero and skip stddev computation in that case. For now don't care about rec->counter * rec->counter overflow because rec->time * rec->time overflow will likely happen earlier. Cc: stable@vger.kernel.org Cc: Wen Yang <wenyang@linux.alibaba.com> Cc: Mark Rutland <mark.rutland@arm.com> Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com> Link: https://lore.kernel.org/20250206090156.1561783-1-kniv@yandex-team.ru Fixes: e31f793 ("ftrace: Avoid potential division by zero in function profiler") Signed-off-by: Nikolay Kuratov <kniv@yandex-team.ru> Signed-off-by: Steven Rostedt (Google) <rostedt@goodmis.org>
1 parent 3908b6b commit a1a7eb8

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

kernel/trace/ftrace.c

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,7 @@ static int function_stat_show(struct seq_file *m, void *v)
540540
static struct trace_seq s;
541541
unsigned long long avg;
542542
unsigned long long stddev;
543+
unsigned long long stddev_denom;
543544
#endif
544545
guard(mutex)(&ftrace_profile_lock);
545546

@@ -559,23 +560,19 @@ static int function_stat_show(struct seq_file *m, void *v)
559560
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
560561
seq_puts(m, " ");
561562

562-
/* Sample standard deviation (s^2) */
563-
if (rec->counter <= 1)
564-
stddev = 0;
565-
else {
566-
/*
567-
* Apply Welford's method:
568-
* s^2 = 1 / (n * (n-1)) * (n * \Sum (x_i)^2 - (\Sum x_i)^2)
569-
*/
563+
/*
564+
* Variance formula:
565+
* s^2 = 1 / (n * (n-1)) * (n * \Sum (x_i)^2 - (\Sum x_i)^2)
566+
* Maybe Welford's method is better here?
567+
* Divide only by 1000 for ns^2 -> us^2 conversion.
568+
* trace_print_graph_duration will divide by 1000 again.
569+
*/
570+
stddev = 0;
571+
stddev_denom = rec->counter * (rec->counter - 1) * 1000;
572+
if (stddev_denom) {
570573
stddev = rec->counter * rec->time_squared -
571574
rec->time * rec->time;
572-
573-
/*
574-
* Divide only 1000 for ns^2 -> us^2 conversion.
575-
* trace_print_graph_duration will divide 1000 again.
576-
*/
577-
stddev = div64_ul(stddev,
578-
rec->counter * (rec->counter - 1) * 1000);
575+
stddev = div64_ul(stddev, stddev_denom);
579576
}
580577

581578
trace_seq_init(&s);

0 commit comments

Comments
 (0)