Re: something about jiffies wraparound overflow

From: lk
Date: Tue Dec 27 2005 - 03:52:19 EST


As you mentioned the code for comparison:
> /* code 2*/
> unsigned long timeout = jiffies + HZ/2;

the code has no problem with jiffies wrapping around
as long as the values are compared in a right way.
For a 32 bit platform the counter wraps around only once every 50 day
when the value of HZ 1000. so if your code is prepared to face this event
it will work fine.

> 2.Is there any other possibilities for the "code 2" to overflow
> except the jiffies overflow?
No.

The better option would be to use the inline macros:

> #define time_after(a,b) \
> (typecheck(unsigned long, a) && \
> typecheck(unsigned long, b) && \
> ((long)(b) - (long)(a) < 0))
> #define time_before(a,b) time_after(b,a)
>
> #define time_after_eq(a,b) \
> (typecheck(unsigned long, a) && \
> typecheck(unsigned long, b) && \
> ((long)(a) - (long)(b) >= 0))
> #define time_before_eq(a,b) time_after_eq(b,a)
>
> But I cannot understand it has some differences comparing with the
> following code.
> 1.why the macros of time_after can solve the jiffies
> wraparound problem?

As it is clear that time_after evaluates true,
when a, as a snapshot of jiffies, represents a time after b,

These inlines deals with the timer wrapping correctly, because
if the timer wrap changes in the future , you won't have to alter the driver
code.
Typechecks are performed at the compiled time, that variables are of the
same type.
the code works by first converting the values to unsigned long, subtracting
them and then comparing the result.
so it is the safe way and most encoraged..

If you need to know the difference
between two instances of jiffies in a safe way, you can use the same trick:
diff = (long)t2 - (long)t1;.


regards
lk.


-
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/