Refine and fix the delay loop calculation

The current delay loop calculation is still from revision 1 of flashrom,
and since then it had a logic bug which caused all delays to be twice as
long as intended.

Fix the delay duration.

Protect against delay loop overflows.

Detect a non-working delay loop.

Change the delay loop itself to ensure clever compiler optimizers won't
eliminate it (as happens with clang/llvm in the current code). Some
people suggested machine-specific asm, but the empty asm statement with
the loop counter as register/memory input has the benefit of being
perfectly cross-platform and working in gcc and clang.

If time goes backwards (catastrophical NTP time difference, manual
time change), timing measurements were shot because the new-old time
subtraction yielded negative numbers which weren't handled correctly
because the variable is unsigned. Work around that issue (a fix is
mathematically impossible).

If time goes forward too fast, pick the biggest possible timing
measurement with a guaranteed overflow avoidance for all timing

Check four times if the calculated timing is at most 10% too fast. This
addresses OS scheduler interactions, e.g. being scheduled out during
measurement which inflates measurements.

If the timing looks like garbage, recalculate the timer values up to
four times before giving up.

Avoid division by zero in rare cases where timing measurements for a 250
ms delay returned 0 us elapsed.

Corresponding to flashrom svn r990.

Signed-off-by: Carl-Daniel Hailfinger <>
Acked-by: Maciej Pijanka <>
1 file changed