1 /*
2  * Copyright (c) 2021, 2025 NXP
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT nxp_os_timer
8 
9 #include <limits.h>
10 
11 #include <zephyr/init.h>
12 #include <zephyr/drivers/timer/system_timer.h>
13 #include <zephyr/drivers/timer/nxp_os_timer.h>
14 #include <zephyr/irq.h>
15 #include <zephyr/sys_clock.h>
16 #include <zephyr/spinlock.h>
17 #include <zephyr/drivers/counter.h>
18 #include <zephyr/pm/pm.h>
19 #include <zephyr/drivers/reset.h>
20 #include "fsl_ostimer.h"
21 #if !defined(CONFIG_SOC_FAMILY_MCXN) && !defined(CONFIG_SOC_FAMILY_MCXA)
22 #include "fsl_power.h"
23 #endif
24 #include <soc.h>
25 
26 #define CYC_PER_TICK                                                                               \
27 	((uint32_t)((uint64_t)sys_clock_hw_cycles_per_sec() /                                      \
28 		    (uint64_t)CONFIG_SYS_CLOCK_TICKS_PER_SEC))
29 #define CYC_PER_US ((uint32_t)((uint64_t)sys_clock_hw_cycles_per_sec() / (uint64_t)USEC_PER_SEC))
30 #define MAX_CYC    INT_MAX
31 #define MAX_TICKS  ((MAX_CYC - CYC_PER_TICK) / CYC_PER_TICK)
32 #define MIN_DELAY  CONFIG_MCUX_OS_TIMER_MIN_DELAY
33 
34 static struct k_spinlock lock;
35 static uint64_t last_count;
36 static OSTIMER_Type *base = (OSTIMER_Type *)DT_INST_REG_ADDR(0);
37 /* Total cycles of the timer compensated to include the time lost in "sleep/deep sleep" modes.
38  * This maintains the timer count to account for the case if the OS Timer is reset in
39  * certain deep sleep modes and the time elapsed when it is powered off.
40  */
41 static uint64_t cyc_sys_compensated;
42 #if DT_NODE_HAS_STATUS_OKAY(DT_NODELABEL(standby)) && CONFIG_PM
43 /* This is the counter device used when OS timer is not available in standby mode. */
44 static const struct device *counter_dev =
45 	DEVICE_DT_GET_OR_NULL(DT_INST_PHANDLE(0, deep_sleep_counter));
46 /* Indicates if the counter is running. */
47 static bool counter_running;
48 static uint32_t counter_max_val;
49 #endif
50 /* Indicates we received a call with ticks set to wait forever */
51 static bool wait_forever;
52 /* Incase of counter overflow, track the remaining ticks left */
53 static uint32_t counter_remaining_ticks;
54 
mcux_lpc_ostick_get_compensated_timer_value(void)55 static uint64_t mcux_lpc_ostick_get_compensated_timer_value(void)
56 {
57 	return (OSTIMER_GetCurrentTimerValue(base) + cyc_sys_compensated);
58 }
59 
mcux_os_timer_set_next_tick_match(void)60 void mcux_os_timer_set_next_tick_match(void)
61 {
62 	uint64_t adjustment = CYC_PER_TICK < MIN_DELAY ? 2 * CYC_PER_TICK : CYC_PER_TICK;
63 	uint64_t next_tick_cycles_match = last_count + adjustment;
64 
65 	OSTIMER_SetMatchValue(base, next_tick_cycles_match, NULL);
66 }
67 
mcux_os_timer_calc_elapsed_ticks(uint64_t current_cycles)68 static uint32_t mcux_os_timer_calc_elapsed_ticks(uint64_t current_cycles)
69 {
70 	uint64_t elapsed_cycles = current_cycles - last_count;
71 	uint32_t elapsed_ticks = (uint32_t)elapsed_cycles / CYC_PER_TICK;
72 	return elapsed_ticks;
73 }
74 
mcux_lpc_ostick_isr(const void * arg)75 void mcux_lpc_ostick_isr(const void *arg)
76 {
77 	ARG_UNUSED(arg);
78 
79 	k_spinlock_key_t key = k_spin_lock(&lock);
80 
81 	/* Clear interrupt flag by writing 1. */
82 	base->OSEVENT_CTRL &= ~OSTIMER_OSEVENT_CTRL_OSTIMER_INTENA_MASK;
83 
84 	uint64_t now = mcux_lpc_ostick_get_compensated_timer_value();
85 	uint32_t elapsed_ticks = mcux_os_timer_calc_elapsed_ticks(now);
86 
87 	last_count = now;
88 
89 	if (!IS_ENABLED(CONFIG_TICKLESS_KERNEL)) {
90 		mcux_os_timer_set_next_tick_match();
91 	}
92 
93 	k_spin_unlock(&lock, key);
94 
95 	sys_clock_announce(IS_ENABLED(CONFIG_TICKLESS_KERNEL) ? elapsed_ticks : 1);
96 }
97 
98 #if DT_NODE_HAS_STATUS_OKAY(DT_NODELABEL(standby)) && CONFIG_PM
99 
100 static struct counter_top_cfg top_cfg = {0};
101 static struct counter_alarm_cfg alarm_cfg = {0};
102 
103 /* The OS Timer is disabled in certain low power modes and cannot wakeup the system
104  * on timeout. This function will be called by the low power code to allow the
105  * OS Timer to save off the count if needed and also start a wakeup counter
106  * that would wakeup the system from deep power down modes.
107  */
mcux_lpc_ostick_set_counter_timeout(int32_t curr_timeout)108 static uint32_t mcux_lpc_ostick_set_counter_timeout(int32_t curr_timeout)
109 {
110 	uint32_t ticks;
111 
112 	if (counter_dev == NULL) {
113 		return 1;
114 	}
115 
116 	/* Check if we should use the remaining ticks from a prior overflow */
117 	if (counter_remaining_ticks) {
118 		ticks = counter_remaining_ticks;
119 	} else {
120 		ticks = counter_us_to_ticks(counter_dev, curr_timeout);
121 		counter_remaining_ticks = ticks;
122 	}
123 
124 	/* Check if the counter overflows */
125 	if (ticks > counter_max_val) {
126 		counter_remaining_ticks -= counter_max_val;
127 	} else {
128 		counter_remaining_ticks = 0;
129 	}
130 	ticks = CLAMP(ticks, 1, counter_max_val);
131 
132 	top_cfg.ticks = ticks;
133 	alarm_cfg.ticks = ticks;
134 	/* short circuit conditional logic, if top value doesn't work, we try alarm */
135 	if (counter_set_top_value(counter_dev, &top_cfg) != 0 &&
136 	    counter_set_channel_alarm(counter_dev, 0, &alarm_cfg) != 0) {
137 		return 1;
138 	}
139 
140 	/* Counter is set to wakeup the system after the requested time */
141 	if (counter_start(counter_dev) != 0) {
142 		return 1;
143 	}
144 	counter_running = true;
145 
146 	if (IS_ENABLED(CONFIG_MCUX_OS_TIMER_PM_POWERED_OFF)) {
147 		/* Capture the current timer value for cases where it loses its state
148 		 * in low power modes.
149 		 */
150 		cyc_sys_compensated += OSTIMER_GetCurrentTimerValue(base);
151 	}
152 
153 	return 0;
154 }
155 
156 /* After exit from certain low power modes where the OS Timer was disabled, the
157  * current tick value should be updated to account for the period when the OS Timer
158  * was disabled. Also in certain cases, the OS Timer might lose its state and needs
159  * to be reinitialized.
160  */
mcux_lpc_ostick_compensate_system_timer(void)161 static uint32_t mcux_lpc_ostick_compensate_system_timer(void)
162 {
163 	uint32_t slept_time_ticks;
164 	uint32_t slept_time_us;
165 
166 	if (!counter_dev) {
167 		return 1;
168 	}
169 
170 	if (!counter_running) {
171 		return 0;
172 	}
173 
174 	counter_stop(counter_dev);
175 	counter_running = false;
176 	counter_get_value(counter_dev, &slept_time_ticks);
177 
178 	if (!(counter_is_counting_up(counter_dev))) {
179 		slept_time_ticks = counter_get_top_value(counter_dev) - slept_time_ticks;
180 	}
181 	slept_time_us = counter_ticks_to_us(counter_dev, slept_time_ticks);
182 	cyc_sys_compensated += CYC_PER_US * slept_time_us;
183 
184 	if (IS_ENABLED(CONFIG_MCUX_OS_TIMER_PM_POWERED_OFF)) {
185 		/* Reset the OS Timer to a known state */
186 		const struct reset_dt_spec reset = RESET_DT_SPEC_INST_GET_OR(0, {0});
187 
188 		if (reset.dev != NULL) {
189 			reset_line_toggle_dt(&reset);
190 		}
191 		/* Reactivate os_timer for cases where it loses its state */
192 		OSTIMER_Init(base);
193 	}
194 
195 	/* Announce the time slept to the kernel*/
196 	mcux_lpc_ostick_isr(NULL);
197 
198 	return 0;
199 }
200 
mcux_os_timer_set_lp_counter_timeout(void)201 static void mcux_os_timer_set_lp_counter_timeout(void)
202 {
203 	uint64_t timeout;
204 
205 	/* OS Timer may not be able to wakeup in certain low power modes.
206 	 * For these cases, we start a counter that can wakeup
207 	 * from low power modes.
208 	 */
209 	if (pm_state_next_get(0)->state != PM_STATE_STANDBY) {
210 		return;
211 	}
212 
213 	if (wait_forever) {
214 		timeout = UINT32_MAX;
215 	} else if (counter_remaining_ticks) {
216 		timeout = counter_remaining_ticks;
217 	} else {
218 		/* Check the amount of time left and switch to a counter
219 		 * that is active in this power mode.
220 		 */
221 		timeout = base->MATCH_L;
222 		timeout |= (uint64_t)(base->MATCH_H) << 32;
223 		timeout = OSTIMER_GrayToDecimal(timeout);
224 		timeout -= OSTIMER_GetCurrentTimerValue(base);
225 		/* Round up to the next tick boundary */
226 		timeout += (CYC_PER_TICK - 1);
227 		/* Convert to microseconds and round up to the next value */
228 		timeout = (((timeout / CYC_PER_TICK) * CYC_PER_TICK) * CYC_PER_US);
229 	}
230 
231 	mcux_lpc_ostick_set_counter_timeout(timeout);
232 }
233 #else
234 #define mcux_os_timer_set_lp_counter_timeout(...) do { } while (0)
235 #endif
236 
z_nxp_os_timer_ignore_timer_wakeup(void)237 bool z_nxp_os_timer_ignore_timer_wakeup(void)
238 {
239 	return (wait_forever || counter_remaining_ticks);
240 }
241 
sys_clock_set_timeout(int32_t ticks,bool idle)242 void sys_clock_set_timeout(int32_t ticks, bool idle)
243 {
244 	if (!IS_ENABLED(CONFIG_TICKLESS_KERNEL)) {
245 		/* Only for tickless kernel system */
246 		return;
247 	}
248 
249 #if DT_NODE_HAS_STATUS_OKAY(DT_NODELABEL(standby)) && CONFIG_PM
250 	/* We intercept calls from idle with a 0 tick count when PM=y */
251 	if (idle && (ticks == 0)) {
252 		mcux_os_timer_set_lp_counter_timeout();
253 		/* A low power counter has been started. No need to
254 		 * go further, simply return
255 		 */
256 		return;
257 	}
258 	/* When using a counter for certain low power modes, set this flag when the requested
259 	 * delay is forever. This is to keep track of wakeup sources in case of counter overflows.
260 	 */
261 	wait_forever = (ticks == SYS_CLOCK_MAX_WAIT);
262 #else
263 	ARG_UNUSED(idle);
264 #endif
265 	ticks = ticks == K_TICKS_FOREVER ? MAX_TICKS : ticks;
266 	ticks = CLAMP(ticks - 1, 0, (int32_t)MAX_TICKS);
267 
268 	k_spinlock_key_t key = k_spin_lock(&lock);
269 	uint64_t now = mcux_lpc_ostick_get_compensated_timer_value();
270 	uint32_t adj, cyc = ticks * CYC_PER_TICK;
271 
272 	/* Round up to next tick boundary. */
273 	adj = (uint32_t)(now - last_count) + (CYC_PER_TICK - 1);
274 	if (cyc <= MAX_CYC - adj) {
275 		cyc += adj;
276 	} else {
277 		cyc = MAX_CYC;
278 	}
279 	cyc = (cyc / CYC_PER_TICK) * CYC_PER_TICK;
280 
281 	if ((int32_t)(cyc + last_count - now) < MIN_DELAY) {
282 		cyc += CYC_PER_TICK;
283 	}
284 
285 	OSTIMER_SetMatchValue(base, cyc + last_count - cyc_sys_compensated, NULL);
286 
287 	counter_remaining_ticks = 0;
288 
289 	k_spin_unlock(&lock, key);
290 }
291 
sys_clock_elapsed(void)292 uint32_t sys_clock_elapsed(void)
293 {
294 	if (!IS_ENABLED(CONFIG_TICKLESS_KERNEL)) {
295 		/* Always return 0 for tickful kernel system */
296 		return 0;
297 	}
298 
299 	k_spinlock_key_t key = k_spin_lock(&lock);
300 
301 	uint64_t now = mcux_lpc_ostick_get_compensated_timer_value();
302 	uint32_t elapsed_ticks = mcux_os_timer_calc_elapsed_ticks(now);
303 
304 	k_spin_unlock(&lock, key);
305 
306 	return elapsed_ticks;
307 }
308 
sys_clock_cycle_get_32(void)309 uint32_t sys_clock_cycle_get_32(void)
310 {
311 	return (uint32_t)mcux_lpc_ostick_get_compensated_timer_value();
312 }
313 
sys_clock_cycle_get_64(void)314 uint64_t sys_clock_cycle_get_64(void)
315 {
316 	return mcux_lpc_ostick_get_compensated_timer_value();
317 }
318 
sys_clock_idle_exit(void)319 void sys_clock_idle_exit(void)
320 {
321 #if DT_NODE_HAS_STATUS_OKAY(DT_NODELABEL(standby)) && CONFIG_PM
322 	/* The tick should be compensated for states where the
323 	 * OS Timer is disabled
324 	 */
325 	if (pm_state_next_get(0)->state == PM_STATE_STANDBY) {
326 		mcux_lpc_ostick_compensate_system_timer();
327 	}
328 #endif
329 }
330 
sys_clock_driver_init(void)331 static int sys_clock_driver_init(void)
332 {
333 	/* Initialize the OS timer, setting clock configuration. */
334 	OSTIMER_Init(base);
335 
336 	last_count = mcux_lpc_ostick_get_compensated_timer_value();
337 	OSTIMER_SetMatchValue(base, last_count + CYC_PER_TICK, NULL);
338 
339 	/* Configure and enable event timer interrupt */
340 	IRQ_CONNECT(DT_INST_IRQN(0), DT_INST_IRQ(0, priority), mcux_lpc_ostick_isr, NULL, 0);
341 	irq_enable(DT_INST_IRQN(0));
342 
343 /* On some SoC's, OS Timer cannot wakeup from low power mode in standby modes */
344 #if DT_NODE_HAS_STATUS_OKAY(DT_NODELABEL(standby)) && CONFIG_PM
345 	counter_dev = DEVICE_DT_GET_OR_NULL(DT_INST_PHANDLE(0, deep_sleep_counter));
346 	if (NULL != counter_dev) {
347 		counter_max_val = counter_get_max_top_value(counter_dev);
348 	}
349 #endif
350 
351 #if (DT_INST_PROP(0, wakeup_source))
352 	NXP_ENABLE_WAKEUP_SIGNAL(DT_INST_IRQN(0));
353 #endif
354 	return 0;
355 }
356 
357 SYS_INIT(sys_clock_driver_init, PRE_KERNEL_2, CONFIG_SYSTEM_CLOCK_INIT_PRIORITY);
358