[PATCH] KVM: x86: Use div64_ul instead of do_div

cgel.zte@gmail.com posted 1 patch 4 years, 6 months ago
arch/x86/kvm/lapic.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
[PATCH] KVM: x86: Use div64_ul instead of do_div
Posted by cgel.zte@gmail.com 4 years, 6 months ago
From: Changcheng Deng <deng.changcheng@zte.com.cn>

do_div() does a 64-by-32 division. Here the divisor is an unsigned long
which on some platforms is 64 bit wide. So use div64_ul instead of do_div
to avoid a possible truncation.

Reported-by: Zeal Robot <zealci@zte.com.cn>
Signed-off-by: Changcheng Deng <deng.changcheng@zte.com.cn>
---
 arch/x86/kvm/lapic.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/arch/x86/kvm/lapic.c b/arch/x86/kvm/lapic.c
index c5028e6b0f96..3b629870632c 100644
--- a/arch/x86/kvm/lapic.c
+++ b/arch/x86/kvm/lapic.c
@@ -1707,7 +1707,7 @@ static void start_sw_tscdeadline(struct kvm_lapic *apic)
 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
 
 	ns = (tscdeadline - guest_tsc) * 1000000ULL;
-	do_div(ns, this_tsc_khz);
+	ns = div64_ul(ns, this_tsc_khz);
 
 	if (likely(tscdeadline > guest_tsc) &&
 	    likely(ns > apic->lapic_timer.timer_advance_ns)) {
-- 
2.25.1

Re: [PATCH] KVM: x86: Use div64_ul instead of do_div
Posted by Paolo Bonzini 4 years, 6 months ago
On 12/17/21 09:41, cgel.zte@gmail.com wrote:
> From: Changcheng Deng <deng.changcheng@zte.com.cn>
> 
> do_div() does a 64-by-32 division. Here the divisor is an unsigned long
> which on some platforms is 64 bit wide. So use div64_ul instead of do_div
> to avoid a possible truncation.
> 
> Reported-by: Zeal Robot <zealci@zte.com.cn>
> Signed-off-by: Changcheng Deng <deng.changcheng@zte.com.cn>
> ---
>   arch/x86/kvm/lapic.c | 2 +-
>   1 file changed, 1 insertion(+), 1 deletion(-)
> 
> diff --git a/arch/x86/kvm/lapic.c b/arch/x86/kvm/lapic.c
> index c5028e6b0f96..3b629870632c 100644
> --- a/arch/x86/kvm/lapic.c
> +++ b/arch/x86/kvm/lapic.c
> @@ -1707,7 +1707,7 @@ static void start_sw_tscdeadline(struct kvm_lapic *apic)
>   	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
>   
>   	ns = (tscdeadline - guest_tsc) * 1000000ULL;
> -	do_div(ns, this_tsc_khz);
> +	ns = div64_ul(ns, this_tsc_khz);
>   
>   	if (likely(tscdeadline > guest_tsc) &&
>   	    likely(ns > apic->lapic_timer.timer_advance_ns)) {
> 

You could change this_tsc_khz to u32 instead, it's assigned from a 
32-bit value.

Using div64_ul would be unnecessary and less efficient.

Paolo