# INN timer code and time overflows

Russ Allbery rra at stanford.edu
Tue Oct 3 08:57:45 UTC 2000

```Heath Kehoe <heath.kehoe at intermec.com> writes:

> It won't work, unless it's actually checking for the overflow condition.

> If the difference is a large negative value you will wind up with
> something that looks like a positive value.  If you know that it
> overflowed, you can take the 2's-complement of that value which (when
> interpreted as unsigned) will be the absolute value of the difference.
> Similarly for large positive differences, only you don't need to
> complement the result; just interpret it as an unsigned value.

What it's doing is:

(tv.tv_sec - base.tv_sec) * 1000 + (tv.tv_usec - base.tv_usec) / 1000

The first multiplication is going to overflow an unsigned long, which is
probably what time_t is, on a 32-bit platform.  If that doesn't overflow
it, the return value (in the code before I just rewrote it) was an int, so
the implicit cast will.

I'm pretty sure the cast takes modulo 2^32.  I don't know what
multiplication does.  I hazily recall that unsigned arithmetic in C is
basically normal arithmetic done with "infinite" size numbers and then
reduced modulo 2^(sizeof(type) * 8).  If that's the case, it may actually
end up working....

Anyway, I decided that if figuring out if it was working right was making
my head hurt, it was using the wrong algorithm.  What happens now is that
each time the timer code prints out a summary, it resets the base struct
timeval to the current time at that moment at the same time.  All times
are then computed relative to the last time the summary was printed.  This
requires that all timers be stopped when TMRmainloophook is called, but
that was already a stated assumption of the original code and I'm pretty
sure that's the case in the current code.

I think it has the advantage of being a lot easier to follow.  (Need to go
update the comments again; I forgot to make it clear that all timers
really do need to be stopped when TMRmainloophook is called now.)

At some point, I'll add some additional sanity checks to this code to warn
if things are called in the wrong order, but I'm waiting until I've added
the hooks to use the new error reporting mechanisms to innd, since that's
the right way to handle it and that way I don't have to go back and change
it again later.

--
Russ Allbery (rra at stanford.edu)             <http://www.eyrie.org/~eagle/>

```