@@ -41,12 +41,53 @@ static struct k_spinlock lock;
4141
4242static u32_t last_load ;
4343
44+ /*
45+ * This local variable holds the amount of SysTick HW cycles elapsed
46+ * and it is updated in z_clock_isr() and z_clock_set_timeout().
47+ *
48+ * Note:
49+ * At an arbitrary point in time the "current" value of the SysTick
50+ * HW timer is calculated as:
51+ *
52+ * t = cycle_counter + elapsed();
53+ */
4454static u32_t cycle_count ;
4555
56+ /*
57+ * This local variable holds the amount of elapsed SysTick HW cycles
58+ * that have been announced to the kernel.
59+ */
4660static u32_t announced_cycles ;
4761
62+ /*
63+ * This local variable holds the amount of elapsed HW cycles due to
64+ * SysTick timer wraps ('overflows') and is used in the calculation
65+ * in elapsed() function, as well as in the updates to cycle_count.
66+ *
67+ * Note:
68+ * Each time cycle_count is updated with the value from overflow_cyc,
69+ * the overflow_cyc must be reset to zero.
70+ */
4871static volatile u32_t overflow_cyc ;
4972
73+ /* This internal function calculates the amount of HW cycles that have
74+ * elapsed since the last time the absolute HW cycles counter has been
75+ * updated. 'cycle_count' may be updated either by the ISR, or when we
76+ * re-program the SysTick.LOAD register, in z_clock_set_timeout().
77+ *
78+ * Additionally, the function updates the 'overflow_cyc' counter, that
79+ * holds the amount of elapsed HW cycles due to (possibly) multiple
80+ * timer wraps (overflows).
81+ *
82+ * Prerequisites:
83+ * - reprogramming of SysTick.LOAD must be clearing the SysTick.COUNTER
84+ * register and the 'overflow_cyc' counter.
85+ * - ISR must be clearing the 'overflow_cyc' counter.
86+ * - no more than one counter-wrap has occurred between
87+ * - the timer reset or the last time the function was called
88+ * - and until the current call of the function is completed.
89+ * - the function is invoked with interrupts disabled.
90+ */
5091static u32_t elapsed (void )
5192{
5293 u32_t val , ctrl1 , ctrl2 ;
@@ -71,6 +112,11 @@ static u32_t elapsed(void)
71112 val = SysTick -> VAL ;
72113 ctrl2 = SysTick -> CTRL ;
73114
115+ /* overflow_cyc is reset to zero by
116+ * - _init()
117+ * - _isr()
118+ * - _set_timeout()
119+ */
74120 overflow_cyc += (ctrl1 & SysTick_CTRL_COUNTFLAG_Msk ) ? last_load : 0 ;
75121 if (val > VAL_ABOUT_TO_WRAP ) {
76122 int wrap = ctrl2 & SysTick_CTRL_COUNTFLAG_Msk ;
0 commit comments