Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

sched/x86: Fix overflow in cyc2ns_offset

When a machine boots up, the TSC generally gets reset. However,
when kexec is used to boot into a kernel, the TSC value would be
carried over from the previous kernel. The computation of
cycns_offset in set_cyc2ns_scale is prone to an overflow, if the
machine has been up more than 208 days prior to the kexec. The
overflow happens when we multiply *scale, even though there is
enough room to store the final answer.

We fix this issue by decomposing tsc_now into the quotient and
remainder of division by CYC2NS_SCALE_FACTOR and then performing
the multiplication separately on the two components.

Refactor code to share the calculation with the previous
fix in __cycles_2_ns().

Signed-off-by: Salman Qazi <sqazi@google.com>
Acked-by: John Stultz <john.stultz@linaro.org>
Acked-by: Peter Zijlstra <a.p.zijlstra@chello.nl>
Cc: Paul Turner <pjt@google.com>
Cc: john stultz <johnstul@us.ibm.com>
Link: http://lkml.kernel.org/r/20120310004027.19291.88460.stgit@dungbeetle.mtv.corp.google.com
Signed-off-by: Ingo Molnar <mingo@elte.hu>

authored by

Salman Qazi and committed by
Ingo Molnar
9993bc63 47258cf3

+17 -7
+2 -6
arch/x86/include/asm/timer.h
··· 57 57 58 58 static inline unsigned long long __cycles_2_ns(unsigned long long cyc) 59 59 { 60 - unsigned long long quot; 61 - unsigned long long rem; 62 60 int cpu = smp_processor_id(); 63 61 unsigned long long ns = per_cpu(cyc2ns_offset, cpu); 64 - quot = (cyc >> CYC2NS_SCALE_FACTOR); 65 - rem = cyc & ((1ULL << CYC2NS_SCALE_FACTOR) - 1); 66 - ns += quot * per_cpu(cyc2ns, cpu) + 67 - ((rem * per_cpu(cyc2ns, cpu)) >> CYC2NS_SCALE_FACTOR); 62 + ns += mult_frac(cyc, per_cpu(cyc2ns, cpu), 63 + (1UL << CYC2NS_SCALE_FACTOR)); 68 64 return ns; 69 65 } 70 66
+2 -1
arch/x86/kernel/tsc.c
··· 620 620 621 621 if (cpu_khz) { 622 622 *scale = (NSEC_PER_MSEC << CYC2NS_SCALE_FACTOR)/cpu_khz; 623 - *offset = ns_now - (tsc_now * *scale >> CYC2NS_SCALE_FACTOR); 623 + *offset = ns_now - mult_frac(tsc_now, *scale, 624 + (1UL << CYC2NS_SCALE_FACTOR)); 624 625 } 625 626 626 627 sched_clock_idle_wakeup_event(0);
+13
include/linux/kernel.h
··· 85 85 } \ 86 86 ) 87 87 88 + /* 89 + * Multiplies an integer by a fraction, while avoiding unnecessary 90 + * overflow or loss of precision. 91 + */ 92 + #define mult_frac(x, numer, denom)( \ 93 + { \ 94 + typeof(x) quot = (x) / (denom); \ 95 + typeof(x) rem = (x) % (denom); \ 96 + (quot * (numer)) + ((rem * (numer)) / (denom)); \ 97 + } \ 98 + ) 99 + 100 + 88 101 #define _RET_IP_ (unsigned long)__builtin_return_address(0) 89 102 #define _THIS_IP_ ({ __label__ __here; __here: (unsigned long)&&__here; }) 90 103