Re: [patch] fix delay_tsc (was Re: delay_tsc(): inefficient delay loop (2.6.16-mm1))

From: Ray Lee
Date: Sun Mar 26 2006 - 19:39:41 EST


On 3/26/06, Chuck Ebbert <76306.1226@xxxxxxxxxxxxxx> wrote:
> On Fri, 24 Mar 2006 09:22:51 -0800, Ray Lee wrote:
> > On 3/24/06, Andreas Mohr <andi@xxxxxxxxxxxxxxxxxxxxxxx> wrote:
> > > + loops += bclock;
> > [...]
> > > - } while ((now-bclock) < loops);
> > > + } while (now < loops);
> >
> > Erm, aren't you introducing an overflow problem here?
> >
> > if loops is 2^32-1, bclock is 1, the old version would execute the
> > proper number of times, the new one will blow out in one tick.
>
> Yes, but the old version has a bug too.
[...]
> If (loops == 100000) and (bclock == 2^32-1) the loop will terminate
> immediately when the low part of the TSC overflows because (now-bclock)
> is a large number.

Er, no, it won't, because (now-bclock) won't be large.

I know thinking about math on a modulo number line such as u8/16/32 is
odd, but it's best if you just always think of "subtraction" to mean
"distance between." (Which is always true in any space or coordinate
system, even with wrap arounds.) This is the same trick used by
Andrew's ring buffers, where you let head and tail wrap around freely,
and only perform the modulo operation at dereferencing.

A simple test program will give you a better feel for what's going on
(I write a lot of these...):

#include <stdio.h>
int main() {
unsigned int a,b,c;
a=-1-1;
b=1000;
c=b-a;
printf("%u - %u = %u\n", b, a, c);
}

ray@issola:~/work/test/overflow$ gcc -o test test.c
ray@issola:~/work/test/overflow$ ./test
1000 - 4294967294 = 1002

So, it wraps appropriately, as odd as that may seem at first blush.

Ray
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/