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