#include <cpu/irq.h>
#include <cpu/power.h> // cpu_relax()
-#include <kern/preempt.h> // proc_decQuantun()
+#include <kern/proc_p.h> // proc_decQuantun()
/*
* Include platform-specific binding code if we're hosted.
hptime_t now, prev = timer_hw_hpread();
hptime_t delta;
- for(;;)
+ for (;;)
{
now = timer_hw_hpread();
/*
- * We rely on hptime_t being unsigned here to
- * reduce the modulo to an AND in the common
- * case of TIMER_HW_CNT.
+ * The timer counter may wrap here and "prev" can become
+ * greater than "now". So, be sure to always evaluate a
+ * coherent timer difference:
+ *
+ * 0 prev now TIMER_HW_CNT
+ * |_____|_______________|_____|
+ * ^^^^^^^^^^^^^^^
+ * delta = now - prev
+ *
+ * 0 now prev TIMER_HW_CNT
+ * |_____|_______________|_____|
+ * ^^^^^ ^^^^^
+ * delta = (TIMER_HW_CNT - prev) + now
+ *
+ * NOTE: TIMER_HW_CNT can be any value, not necessarily a power
+ * of 2. For this reason the "%" operator is not suitable for
+ * the generic case.
*/
- delta = (now - prev) % TIMER_HW_CNT;
+ delta = (now < prev) ? ((hptime_t)TIMER_HW_CNT - prev + now) :
+ (now - prev);
if (delta >= delay)
break;
delay -= delta;
TIMER_STROBE_ON;
- /* Perform hw IRQ handling */
- timer_hw_irq();
-
/* Update the master ms counter */
++_clock;
timer_poll(&timers_queue);
#endif
+ /* Perform hw IRQ handling */
+ timer_hw_irq();
+
TIMER_STROBE_OFF;
}