# Re: [Xen-devel] [PATCH 00/13] Add VMX TSC scaling support

```On 11/24/15 21:05, Haozhong Zhang wrote:
[...]
> > >
> > >   This bug can be fixed either later by patch 5 which introduces a
> > >   common function hvm_scale_tsc() to scale TSC, or by replacing above
> > >   underlined code with a simplified and inlined version of
> > >   hvm_scale_tsc() as below:
> > >       uint64_t mult, frac;
> > >       mult    = ratio >> 32;
> > >       frac    = ratio & ((1ULL << 32) - 1);
> > >       offset  = host_tsc * mult;
> > >       offset += (host_tsc >> 32) * frac;
> > >       offset += ((host_tsc & ((1ULL << 32) - 1)) * frac) >> 32;
> >
> > I am not sure I understand the last line (or maybe 2 lines)
> >
>
> Just simple math with carefulness to avoid 64-bit integer overflow:
>
> suppose the most significant 32 bits of host_tsc and ratio are tsc_h
> and mult, and the least significant 32 bits of them are tsc_l and
> frac, then
>     host_tsc * ratio * 2^-32
>     = host_tsc * (mult * 2^32 + frac) * 2^-32
>     = host_tsc * mult + (tsc_h * 2^32 + tsc_l) * frac * 2^-32
>     = host_tsc * mult + tsc_h * frac + ((tsc_l * frac) >> 32)
>
> All multiplications in the last line are between 32-bit integers, so none
> of them could overflow 64-bit integers.

Sorry, it should be "All but the first multiplication host_tsc * mult
...". In practice, it should be very rare for the first term to
overflow (considering mult is usually less than 10).

Haozhong

>
> Consider a simple example that host_tsc = 1ULL << 33 and ratio = 0xffffffff.
> Overflow happens in the multiplication of the second term of your formula
> below,
> and all overflowed bits are lost in the next right shift.
>
> Haozhong
>
> > If by 'offset' here you are trying to calculate the scaled version of host
> > TSC then I think it would be
> >
> > (host_tsc * (ratio >> 32)) + ( (host_tsc * (ratio & 0xffffffff)) >> 32 )
> >
> > (sanity check: assuming host_tsc is 8 and the ratio is 1.5 (i.e.
> > 0x180000000) we get 12)
> >
> >
> > -boris

_______________________________________________
Xen-devel mailing list
Xen-devel@xxxxxxxxxxxxx
http://lists.xen.org/xen-devel

```

 Lists.xenproject.org is hosted with RackSpace, monitoring our servers 24x7x365 and backed by RackSpace's Fanatical Support®.