1 /*
2  * Copyright (c) 2018, Nordic Semiconductor ASA
3  * Copyright 2024 NXP
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/drivers/counter.h>
9 #include <zephyr/ztest.h>
10 #include <zephyr/kernel.h>
11 #include <zephyr/logging/log.h>
12 LOG_MODULE_REGISTER(test);
13 
14 static struct k_sem top_cnt_sem;
15 static volatile uint32_t top_cnt;
16 static struct k_sem alarm_cnt_sem;
17 static volatile uint32_t alarm_cnt;
18 
19 static void top_handler(const struct device *dev, void *user_data);
20 
21 void *exp_user_data = (void *)199;
22 
23 struct counter_alarm_cfg cntr_alarm_cfg;
24 struct counter_alarm_cfg cntr_alarm_cfg2;
25 
26 #define DEVICE_DT_GET_AND_COMMA(node_id) DEVICE_DT_GET(node_id),
27 /* Generate a list of devices for all instances of the "compat" */
28 #define DEVS_FOR_DT_COMPAT(compat) \
29 	DT_FOREACH_STATUS_OKAY(compat, DEVICE_DT_GET_AND_COMMA)
30 
31 static const struct device *const devices[] = {
32 #ifdef CONFIG_COUNTER_NRF_TIMER
33 	DEVS_FOR_DT_COMPAT(nordic_nrf_timer)
34 #endif
35 #ifdef CONFIG_COUNTER_NRF_RTC
36 	DEVS_FOR_DT_COMPAT(nordic_nrf_rtc)
37 #endif
38 #ifdef CONFIG_COUNTER_TIMER_MAX32
39 #define ADI_MAX32_COUNTER_DEV(idx) \
40 	DEVICE_DT_GET(DT_INST(idx, adi_max32_counter)),
41 #define DT_DRV_COMPAT adi_max32_counter
42 	DT_INST_FOREACH_STATUS_OKAY(ADI_MAX32_COUNTER_DEV)
43 #undef DT_DRV_COMPAT
44 #undef ADI_MAX32_COUNTER_DEV
45 #endif
46 #ifdef CONFIG_COUNTER_TIMER_STM32
47 #define STM32_COUNTER_DEV(idx) \
48 	DEVICE_DT_GET(DT_INST(idx, st_stm32_counter)),
49 #define DT_DRV_COMPAT st_stm32_counter
50 	DT_INST_FOREACH_STATUS_OKAY(STM32_COUNTER_DEV)
51 #undef DT_DRV_COMPAT
52 #undef STM32_COUNTER_DEV
53 #endif
54 #ifdef CONFIG_COUNTER_NATIVE_SIM
55 	DEVICE_DT_GET(DT_NODELABEL(counter0)),
56 #endif
57 #ifdef CONFIG_COUNTER_INFINEON_CAT1
58 	DEVICE_DT_GET(DT_NODELABEL(counter0_0)),
59 #endif
60 	/* NOTE: there is no trailing comma, as the DEVS_FOR_DT_COMPAT
61 	 * handles it.
62 	 */
63 	DEVS_FOR_DT_COMPAT(arm_cmsdk_timer)
64 	DEVS_FOR_DT_COMPAT(arm_cmsdk_dtimer)
65 	DEVS_FOR_DT_COMPAT(microchip_xec_timer)
66 	DEVS_FOR_DT_COMPAT(nxp_imx_epit)
67 	DEVS_FOR_DT_COMPAT(nxp_imx_gpt)
68 #ifdef CONFIG_COUNTER_MCUX_TPM
69 	DEVS_FOR_DT_COMPAT(nxp_tpm_timer)
70 #endif
71 	DEVS_FOR_DT_COMPAT(renesas_smartbond_timer)
72 #ifdef CONFIG_COUNTER_MCUX_CTIMER
73 	DEVS_FOR_DT_COMPAT(nxp_lpc_ctimer)
74 #endif
75 #ifdef CONFIG_COUNTER_MCUX_RTC
76 	DEVS_FOR_DT_COMPAT(nxp_rtc)
77 #endif
78 #ifdef CONFIG_COUNTER_MCUX_QTMR
79 	DEVS_FOR_DT_COMPAT(nxp_imx_tmr)
80 #endif
81 #ifdef CONFIG_COUNTER_NXP_MRT
82 	DEVS_FOR_DT_COMPAT(nxp_mrt_channel)
83 #endif
84 #ifdef CONFIG_COUNTER_MCUX_LPC_RTC_1HZ
85 	DEVS_FOR_DT_COMPAT(nxp_lpc_rtc)
86 #endif
87 #ifdef CONFIG_COUNTER_MCUX_LPC_RTC_HIGHRES
88 	DEVS_FOR_DT_COMPAT(nxp_lpc_rtc_highres)
89 #endif
90 #ifdef CONFIG_COUNTER_GECKO_RTCC
91 	DEVS_FOR_DT_COMPAT(silabs_gecko_rtcc)
92 #endif
93 #ifdef CONFIG_COUNTER_RTC_STM32
94 	DEVS_FOR_DT_COMPAT(st_stm32_rtc)
95 #endif
96 #ifdef CONFIG_COUNTER_GECKO_STIMER
97 	DEVS_FOR_DT_COMPAT(silabs_gecko_stimer)
98 #endif
99 #ifdef CONFIG_COUNTER_NXP_PIT
100 	DEVS_FOR_DT_COMPAT(nxp_pit_channel)
101 #endif
102 #ifdef CONFIG_COUNTER_XLNX_AXI_TIMER
103 	DEVS_FOR_DT_COMPAT(xlnx_xps_timer_1_00_a)
104 #endif
105 #ifdef CONFIG_COUNTER_TMR_ESP32
106 	DEVS_FOR_DT_COMPAT(espressif_esp32_timer)
107 #endif
108 #ifdef CONFIG_COUNTER_TMR_RTC_ESP32
109 	DEVS_FOR_DT_COMPAT(espressif_esp32_rtc_timer)
110 #endif
111 #ifdef CONFIG_COUNTER_NXP_S32_SYS_TIMER
112 	DEVS_FOR_DT_COMPAT(nxp_s32_sys_timer)
113 #endif
114 #ifdef CONFIG_COUNTER_TIMER_GD32
115 	DEVS_FOR_DT_COMPAT(gd_gd32_timer)
116 #endif
117 #ifdef CONFIG_COUNTER_TIMER_RPI_PICO
118 	DEVS_FOR_DT_COMPAT(raspberrypi_pico_timer)
119 #endif
120 #ifdef CONFIG_COUNTER_RTC_MAX32
121 	DEVS_FOR_DT_COMPAT(adi_max32_rtc_counter)
122 #endif
123 #ifdef CONFIG_COUNTER_AMBIQ
124 	DEVS_FOR_DT_COMPAT(ambiq_counter)
125 #endif
126 #ifdef CONFIG_COUNTER_MCUX_LPTMR
127 	DEVS_FOR_DT_COMPAT(nxp_lptmr)
128 #endif
129 #ifdef CONFIG_COUNTER_RENESAS_RZ_GTM
130 	DEVS_FOR_DT_COMPAT(renesas_rz_gtm_counter)
131 #endif
132 };
133 
134 static const struct device *const period_devs[] = {
135 #ifdef CONFIG_COUNTER_MCUX_RTC
136 	DEVS_FOR_DT_COMPAT(nxp_rtc)
137 #endif
138 #ifdef CONFIG_COUNTER_MCUX_LPC_RTC
139 	DEVS_FOR_DT_COMPAT(nxp_lpc_rtc)
140 #endif
141 #ifdef CONFIG_COUNTER_RTC_STM32
142 	DEVS_FOR_DT_COMPAT(st_stm32_rtc)
143 #endif
144 #ifdef CONFIG_COUNTER_RTC_MAX32
145 	DEVS_FOR_DT_COMPAT(adi_max32_rtc_counter)
146 #endif
147 };
148 
149 typedef void (*counter_test_func_t)(const struct device *dev);
150 typedef bool (*counter_capability_func_t)(const struct device *dev);
151 
get_counter_period_us(const struct device * dev)152 static inline uint32_t get_counter_period_us(const struct device *dev)
153 {
154 	for (int i = 0; i < ARRAY_SIZE(period_devs); i++) {
155 		if (period_devs[i] == dev) {
156 			return (USEC_PER_SEC * 2U);
157 		}
158 	}
159 
160 	/* if more counter drivers exist other than RTC,
161 	 * the test value set to 20000 by default
162 	 */
163 	return 20000;
164 }
165 
counter_setup_instance(const struct device * dev)166 static void counter_setup_instance(const struct device *dev)
167 {
168 	k_sem_reset(&alarm_cnt_sem);
169 	if (!k_is_user_context()) {
170 		alarm_cnt = 0;
171 	}
172 }
173 
counter_tear_down_instance(const struct device * dev)174 static void counter_tear_down_instance(const struct device *dev)
175 {
176 	int err;
177 	struct counter_top_cfg top_cfg = {
178 		.callback = NULL,
179 		.user_data = NULL,
180 		.flags = 0
181 	};
182 
183 	top_cfg.ticks = counter_get_max_top_value(dev);
184 	err = counter_set_top_value(dev, &top_cfg);
185 	if (err == -ENOTSUP) {
186 		/* If resetting is not support, attempt without reset. */
187 		top_cfg.flags = COUNTER_TOP_CFG_DONT_RESET;
188 		err = counter_set_top_value(dev, &top_cfg);
189 
190 	}
191 	zassert_true((err == 0) || (err == -ENOTSUP),
192 			"%s: Setting top value to default failed", dev->name);
193 
194 	err = counter_stop(dev);
195 	zassert_equal(0, err, "%s: Counter failed to stop", dev->name);
196 
197 }
198 
test_all_instances(counter_test_func_t func,counter_capability_func_t capability_check)199 static void test_all_instances(counter_test_func_t func,
200 				counter_capability_func_t capability_check)
201 {
202 	int devices_skipped = 0;
203 
204 	zassert_true(ARRAY_SIZE(devices) > 0, "No device found");
205 	for (int i = 0; i < ARRAY_SIZE(devices); i++) {
206 		counter_setup_instance(devices[i]);
207 		if ((capability_check == NULL) ||
208 		     capability_check(devices[i])) {
209 			TC_PRINT("Testing %s\n", devices[i]->name);
210 			func(devices[i]);
211 		} else {
212 			TC_PRINT("Skipped for %s\n", devices[i]->name);
213 			devices_skipped++;
214 		}
215 		counter_tear_down_instance(devices[i]);
216 		/* Allow logs to be printed. */
217 		k_sleep(K_MSEC(100));
218 	}
219 	if (devices_skipped == ARRAY_SIZE(devices)) {
220 		ztest_test_skip();
221 	}
222 }
223 
set_top_value_capable(const struct device * dev)224 static bool set_top_value_capable(const struct device *dev)
225 {
226 	struct counter_top_cfg cfg = {
227 		.ticks = counter_get_top_value(dev) - 1
228 	};
229 	int err;
230 
231 	err = counter_set_top_value(dev, &cfg);
232 	if (err == -ENOTSUP) {
233 		return false;
234 	}
235 
236 	cfg.ticks++;
237 	err = counter_set_top_value(dev, &cfg);
238 	if (err == -ENOTSUP) {
239 		return false;
240 	}
241 
242 	return true;
243 }
244 
top_handler(const struct device * dev,void * user_data)245 static void top_handler(const struct device *dev, void *user_data)
246 {
247 	zassert_true(user_data == exp_user_data,
248 			"%s: Unexpected callback", dev->name);
249 	if (IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS)) {
250 		top_cnt++;
251 
252 		return;
253 	}
254 
255 	k_sem_give(&top_cnt_sem);
256 }
257 
test_set_top_value_with_alarm_instance(const struct device * dev)258 static void test_set_top_value_with_alarm_instance(const struct device *dev)
259 {
260 	int err;
261 	uint32_t cnt;
262 	uint32_t top_value;
263 	uint32_t counter_period_us;
264 	uint32_t top_handler_cnt;
265 	struct counter_top_cfg top_cfg = {
266 		.callback = top_handler,
267 		.user_data = exp_user_data,
268 		.flags = 0
269 	};
270 
271 	k_sem_reset(&top_cnt_sem);
272 	top_cnt = 0;
273 
274 	counter_period_us = get_counter_period_us(dev);
275 	top_cfg.ticks = counter_us_to_ticks(dev, counter_period_us);
276 	err = counter_start(dev);
277 	zassert_equal(0, err, "%s: Counter failed to start", dev->name);
278 
279 	k_busy_wait(5000);
280 
281 	err = counter_get_value(dev, &cnt);
282 	zassert_true(err == 0, "%s: Counter read failed (err: %d)", dev->name,
283 		     err);
284 	if (counter_is_counting_up(dev)) {
285 		err = (cnt > 0) ? 0 : 1;
286 	} else {
287 		top_value = counter_get_top_value(dev);
288 		err = (cnt < top_value) ? 0 : 1;
289 	}
290 	zassert_true(err == 0, "%s: Counter should progress", dev->name);
291 
292 	err = counter_set_top_value(dev, &top_cfg);
293 	zassert_equal(0, err, "%s: Counter failed to set top value (err: %d)",
294 			dev->name, err);
295 
296 	k_busy_wait(5.2*counter_period_us);
297 
298 	top_handler_cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
299 		top_cnt : k_sem_count_get(&top_cnt_sem);
300 	zassert_true(top_handler_cnt == 5U,
301 			"%s: Unexpected number of turnarounds (%d).",
302 			dev->name, top_handler_cnt);
303 }
304 
ZTEST(counter_basic,test_set_top_value_with_alarm)305 ZTEST(counter_basic, test_set_top_value_with_alarm)
306 {
307 	test_all_instances(test_set_top_value_with_alarm_instance,
308 			   set_top_value_capable);
309 }
310 
test_set_top_value_without_alarm_instance(const struct device * dev)311 static void test_set_top_value_without_alarm_instance(const struct device *dev)
312 {
313 	int err;
314 	uint32_t cnt;
315 	uint32_t top_value;
316 	uint32_t counter_period_us;
317 	struct counter_top_cfg top_cfg = {
318 		.callback = NULL,
319 		.user_data = NULL,
320 		.flags = 0
321 	};
322 
323 	counter_period_us = get_counter_period_us(dev);
324 	top_cfg.ticks = counter_us_to_ticks(dev, counter_period_us);
325 	err = counter_start(dev);
326 	zassert_equal(0, err, "%s: Counter failed to start", dev->name);
327 
328 	k_busy_wait(5000);
329 
330 	err = counter_get_value(dev, &cnt);
331 	zassert_true(err == 0, "%s: Counter read failed (err: %d)", dev->name,
332 		     err);
333 	if (counter_is_counting_up(dev)) {
334 		err = (cnt > 0) ? 0 : 1;
335 	} else {
336 		top_value = counter_get_top_value(dev);
337 		err = (cnt < top_value) ? 0 : 1;
338 	}
339 	zassert_true(err == 0, "%s: Counter should progress", dev->name);
340 
341 	err = counter_set_top_value(dev, &top_cfg);
342 	zassert_equal(0, err, "%s: Counter failed to set top value (err: %d)",
343 			dev->name, err);
344 
345 	zassert_true(counter_get_top_value(dev) == top_cfg.ticks,
346 			"%s: new top value not in use.",
347 			dev->name);
348 }
349 
ZTEST_USER(counter_no_callback,test_set_top_value_without_alarm)350 ZTEST_USER(counter_no_callback, test_set_top_value_without_alarm)
351 {
352 	test_all_instances(test_set_top_value_without_alarm_instance,
353 			   set_top_value_capable);
354 }
355 
alarm_handler(const struct device * dev,uint8_t chan_id,uint32_t counter,void * user_data)356 static void alarm_handler(const struct device *dev, uint8_t chan_id,
357 			  uint32_t counter,
358 			  void *user_data)
359 {
360 	/* Arbitrary limit for alarm processing - time between hw expiration
361 	 * and read-out from counter in the handler.
362 	 */
363 	static const uint64_t processing_limit_us = 1000;
364 	uint32_t now;
365 	int err;
366 	uint32_t top;
367 	uint32_t diff;
368 
369 	err = counter_get_value(dev, &now);
370 	zassert_true(err == 0, "%s: Counter read failed (err: %d)",
371 		     dev->name, err);
372 
373 	top = counter_get_top_value(dev);
374 	if (counter_is_counting_up(dev)) {
375 		diff =  (now < counter) ?
376 			(now + top - counter) : (now - counter);
377 	} else {
378 		diff = (now > counter) ?
379 			(counter + top - now) : (counter - now);
380 	}
381 
382 	zassert_true(diff <= counter_us_to_ticks(dev, processing_limit_us),
383 			"Unexpected distance between reported alarm value(%u) "
384 			"and actual counter value (%u), top:%d (processing "
385 			"time limit (%d us) might be exceeded?",
386 			counter, now, top, processing_limit_us);
387 
388 	if (user_data) {
389 		zassert_true(&cntr_alarm_cfg == user_data,
390 			"%s: Unexpected callback", dev->name);
391 	}
392 
393 	if (IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS)) {
394 		alarm_cnt++;
395 		return;
396 	}
397 	zassert_true(k_is_in_isr(), "%s: Expected interrupt context",
398 			dev->name);
399 	k_sem_give(&alarm_cnt_sem);
400 }
401 
test_single_shot_alarm_instance(const struct device * dev,bool set_top)402 static void test_single_shot_alarm_instance(const struct device *dev, bool set_top)
403 {
404 	int err;
405 	uint32_t ticks;
406 	uint32_t cnt;
407 	uint32_t counter_period_us;
408 	struct counter_top_cfg top_cfg = {
409 		.callback = top_handler,
410 		.user_data = exp_user_data,
411 		.flags = 0
412 	};
413 
414 	counter_period_us = get_counter_period_us(dev);
415 	ticks = counter_us_to_ticks(dev, counter_period_us);
416 	top_cfg.ticks = ticks;
417 
418 	cntr_alarm_cfg.flags = 0;
419 	cntr_alarm_cfg.callback = alarm_handler;
420 	cntr_alarm_cfg.user_data = &cntr_alarm_cfg;
421 
422 	k_sem_reset(&alarm_cnt_sem);
423 	alarm_cnt = 0;
424 
425 	if (counter_get_num_of_channels(dev) < 1U) {
426 		/* Counter does not support any alarm */
427 		return;
428 	}
429 
430 	err = counter_start(dev);
431 	zassert_equal(0, err, "%s: Counter failed to start", dev->name);
432 
433 	if (set_top) {
434 		err = counter_set_top_value(dev, &top_cfg);
435 
436 		zassert_equal(0, err,
437 			     "%s: Counter failed to set top value", dev->name);
438 
439 		cntr_alarm_cfg.ticks = ticks + 1;
440 		err = counter_set_channel_alarm(dev, 0, &cntr_alarm_cfg);
441 		zassert_equal(-EINVAL, err,
442 			      "%s: Counter should return error because ticks"
443 			      " exceeded the limit set alarm", dev->name);
444 		cntr_alarm_cfg.ticks = ticks - 1;
445 	}
446 
447 	cntr_alarm_cfg.ticks = ticks;
448 	err = counter_set_channel_alarm(dev, 0, &cntr_alarm_cfg);
449 	zassert_equal(0, err, "%s: Counter set alarm failed (err: %d)",
450 			dev->name, err);
451 
452 	k_busy_wait(2*(uint32_t)counter_ticks_to_us(dev, ticks));
453 
454 	cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
455 		alarm_cnt : k_sem_count_get(&alarm_cnt_sem);
456 	zassert_equal(1, cnt, "%s: Expecting alarm callback", dev->name);
457 
458 	k_busy_wait(1.5*counter_ticks_to_us(dev, ticks));
459 	cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
460 		alarm_cnt : k_sem_count_get(&alarm_cnt_sem);
461 	zassert_equal(1, cnt, "%s: Expecting alarm callback", dev->name);
462 
463 	err = counter_cancel_channel_alarm(dev, 0);
464 	zassert_equal(0, err, "%s: Counter disabling alarm failed", dev->name);
465 
466 	top_cfg.ticks = counter_get_max_top_value(dev);
467 	top_cfg.callback = NULL;
468 	top_cfg.user_data = NULL;
469 	err = counter_set_top_value(dev, &top_cfg);
470 	if (err == -ENOTSUP) {
471 		/* If resetting is not support, attempt without reset. */
472 		top_cfg.flags = COUNTER_TOP_CFG_DONT_RESET;
473 		err = counter_set_top_value(dev, &top_cfg);
474 
475 	}
476 	zassert_true((err == 0) || (err == -ENOTSUP),
477 			"%s: Setting top value to default failed", dev->name);
478 
479 	err = counter_stop(dev);
480 	zassert_equal(0, err, "%s: Counter failed to stop", dev->name);
481 }
482 
test_single_shot_alarm_notop_instance(const struct device * dev)483 void test_single_shot_alarm_notop_instance(const struct device *dev)
484 {
485 	test_single_shot_alarm_instance(dev, false);
486 }
487 
test_single_shot_alarm_top_instance(const struct device * dev)488 void test_single_shot_alarm_top_instance(const struct device *dev)
489 {
490 	test_single_shot_alarm_instance(dev, true);
491 }
492 
single_channel_alarm_capable(const struct device * dev)493 static bool single_channel_alarm_capable(const struct device *dev)
494 {
495 	return (counter_get_num_of_channels(dev) > 0);
496 }
497 
single_channel_alarm_and_custom_top_capable(const struct device * dev)498 static bool single_channel_alarm_and_custom_top_capable(const struct device *dev)
499 {
500 	return single_channel_alarm_capable(dev) &&
501 		set_top_value_capable(dev);
502 }
503 
ZTEST(counter_basic,test_single_shot_alarm_notop)504 ZTEST(counter_basic, test_single_shot_alarm_notop)
505 {
506 	test_all_instances(test_single_shot_alarm_notop_instance,
507 			   single_channel_alarm_capable);
508 }
509 
ZTEST(counter_basic,test_single_shot_alarm_top)510 ZTEST(counter_basic, test_single_shot_alarm_top)
511 {
512 	test_all_instances(test_single_shot_alarm_top_instance,
513 			   single_channel_alarm_and_custom_top_capable);
514 }
515 
516 static void *clbk_data[10];
517 
alarm_handler2(const struct device * dev,uint8_t chan_id,uint32_t counter,void * user_data)518 static void alarm_handler2(const struct device *dev, uint8_t chan_id,
519 			   uint32_t counter,
520 			   void *user_data)
521 {
522 	if (IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS)) {
523 		clbk_data[alarm_cnt] = user_data;
524 		alarm_cnt++;
525 
526 		return;
527 	}
528 
529 	clbk_data[k_sem_count_get(&alarm_cnt_sem)] = user_data;
530 	k_sem_give(&alarm_cnt_sem);
531 }
532 
533 /*
534  * Two alarms set. First alarm is absolute, second relative. Because
535  * setting of both alarms is delayed it is expected that second alarm
536  * will expire first (relative to the time called) while first alarm
537  * will expire after next wrap around.
538  */
test_multiple_alarms_instance(const struct device * dev)539 static void test_multiple_alarms_instance(const struct device *dev)
540 {
541 	int err;
542 	uint32_t ticks;
543 	uint32_t cnt;
544 	uint32_t counter_period_us;
545 	struct counter_top_cfg top_cfg = {
546 		.callback = top_handler,
547 		.user_data = exp_user_data,
548 		.flags = 0
549 	};
550 
551 	counter_period_us = get_counter_period_us(dev);
552 	ticks = counter_us_to_ticks(dev, counter_period_us);
553 
554 	err = counter_get_value(dev, &(top_cfg.ticks));
555 	zassert_equal(0, err, "%s: Counter get value failed", dev->name);
556 	top_cfg.ticks += ticks;
557 
558 	cntr_alarm_cfg.flags = COUNTER_ALARM_CFG_ABSOLUTE;
559 	cntr_alarm_cfg.ticks = counter_us_to_ticks(dev, 2000);
560 	cntr_alarm_cfg.callback = alarm_handler2;
561 	cntr_alarm_cfg.user_data = &cntr_alarm_cfg;
562 
563 	cntr_alarm_cfg2.flags = 0;
564 	cntr_alarm_cfg2.ticks = counter_us_to_ticks(dev, 2000);
565 	cntr_alarm_cfg2.callback = alarm_handler2;
566 	cntr_alarm_cfg2.user_data = &cntr_alarm_cfg2;
567 
568 	k_sem_reset(&alarm_cnt_sem);
569 	alarm_cnt = 0;
570 
571 	if (counter_get_num_of_channels(dev) < 2U) {
572 		/* Counter does not support two alarms */
573 		return;
574 	}
575 
576 	err = counter_start(dev);
577 	zassert_equal(0, err, "%s: Counter failed to start", dev->name);
578 
579 	if (set_top_value_capable(dev)) {
580 		err = counter_set_top_value(dev, &top_cfg);
581 		zassert_equal(0, err, "%s: Counter failed to set top value", dev->name);
582 	} else {
583 		/* Counter does not support top value, do not run this test
584 		 * as it might take a long time to wrap and trigger the alarm
585 		 * resulting in test failures.
586 		 */
587 		return;
588 	}
589 
590 	k_busy_wait(3*(uint32_t)counter_ticks_to_us(dev, cntr_alarm_cfg.ticks));
591 
592 	err = counter_set_channel_alarm(dev, 0, &cntr_alarm_cfg);
593 	zassert_equal(0, err, "%s: Counter set alarm failed", dev->name);
594 
595 	err = counter_set_channel_alarm(dev, 1, &cntr_alarm_cfg2);
596 	zassert_equal(0, err, "%s: Counter set alarm failed", dev->name);
597 
598 	k_busy_wait(1.2 * counter_ticks_to_us(dev, ticks * 2U));
599 
600 	cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
601 		alarm_cnt : k_sem_count_get(&alarm_cnt_sem);
602 	zassert_equal(2, cnt,
603 			"%s: Invalid number of callbacks %d (expected: %d)",
604 			dev->name, cnt, 2);
605 
606 	zassert_equal(&cntr_alarm_cfg2, clbk_data[0],
607 			"%s: Expected different order or callbacks",
608 			dev->name);
609 	zassert_equal(&cntr_alarm_cfg, clbk_data[1],
610 			"%s: Expected different order or callbacks",
611 			dev->name);
612 
613 	/* tear down */
614 	err = counter_cancel_channel_alarm(dev, 0);
615 	zassert_equal(0, err, "%s: Counter disabling alarm failed", dev->name);
616 
617 	err = counter_cancel_channel_alarm(dev, 1);
618 	zassert_equal(0, err, "%s: Counter disabling alarm failed", dev->name);
619 }
620 
multiple_channel_alarm_capable(const struct device * dev)621 static bool multiple_channel_alarm_capable(const struct device *dev)
622 {
623 	return (counter_get_num_of_channels(dev) > 1);
624 }
625 
ZTEST(counter_basic,test_multiple_alarms)626 ZTEST(counter_basic, test_multiple_alarms)
627 {
628 	test_all_instances(test_multiple_alarms_instance,
629 			   multiple_channel_alarm_capable);
630 }
631 
test_all_channels_instance(const struct device * dev)632 static void test_all_channels_instance(const struct device *dev)
633 {
634 	int err;
635 	const int n = 10;
636 	int nchan = 0;
637 	bool limit_reached = false;
638 	struct counter_alarm_cfg alarm_cfgs;
639 	uint32_t ticks;
640 	uint32_t cnt;
641 	uint32_t counter_period_us;
642 
643 	counter_period_us = get_counter_period_us(dev);
644 	ticks = counter_us_to_ticks(dev, counter_period_us);
645 
646 	alarm_cfgs.flags = 0;
647 	alarm_cfgs.ticks = ticks;
648 	alarm_cfgs.callback = alarm_handler2;
649 	alarm_cfgs.user_data = NULL;
650 
651 	err = counter_start(dev);
652 	zassert_equal(0, err, "%s: Counter failed to start", dev->name);
653 
654 	for (int i = 0; i < n; i++) {
655 		err = counter_set_channel_alarm(dev, i, &alarm_cfgs);
656 		if ((err == 0) && !limit_reached) {
657 			nchan++;
658 		} else if (err == -ENOTSUP) {
659 			limit_reached = true;
660 		} else {
661 			zassert_equal(0, 1,
662 			   "%s: Unexpected error on setting alarm", dev->name);
663 		}
664 	}
665 
666 	k_busy_wait(1.5*counter_ticks_to_us(dev, ticks));
667 	cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
668 		alarm_cnt : k_sem_count_get(&alarm_cnt_sem);
669 	zassert_equal(nchan, cnt,
670 			"%s: Expecting alarm callback", dev->name);
671 
672 	for (int i = 0; i < nchan; i++) {
673 		err = counter_cancel_channel_alarm(dev, i);
674 		zassert_equal(0, err,
675 			"%s: Unexpected error on disabling alarm", dev->name);
676 	}
677 
678 	for (int i = nchan; i < n; i++) {
679 		err = counter_cancel_channel_alarm(dev, i);
680 		zassert_equal(-ENOTSUP, err,
681 			"%s: Unexpected error on disabling alarm", dev->name);
682 	}
683 }
684 
ZTEST(counter_basic,test_all_channels)685 ZTEST(counter_basic, test_all_channels)
686 {
687 	test_all_instances(test_all_channels_instance,
688 			   single_channel_alarm_capable);
689 }
690 
test_valid_function_without_alarm(const struct device * dev)691 static void test_valid_function_without_alarm(const struct device *dev)
692 {
693 	int err;
694 	uint32_t ticks;
695 	uint32_t ticks_expected;
696 	uint32_t tick_current;
697 	uint32_t ticks_tol;
698 	uint32_t wait_for_us;
699 	uint32_t freq = counter_get_frequency(dev);
700 
701 	/* For timers which cannot count to at least 2 ms before overflow
702 	 * the test is skipped by test_all_instances function because sufficient
703 	 * accuracy of the test cannot be achieved.
704 	 */
705 
706 	zassert_true(freq != 0, "%s: counter could not get frequency", dev->name);
707 
708 	/* Set time of counting based on counter frequency to
709 	 * ensure convenient run time and accuracy of the test.
710 	 */
711 	if (freq < 1000) {
712 		/* Ensure to have 1 tick for 1 sec clock */
713 		wait_for_us = 1100000;
714 		ticks_expected = counter_us_to_ticks(dev, wait_for_us);
715 	} else if (freq < 1000000) {
716 		/* Calculate wait time for convenient ticks count */
717 		ticks_expected = 1000;
718 		wait_for_us = (ticks_expected * 1000000) / freq;
719 	} else {
720 		/* Wait long enough for high frequency clocks to minimize
721 		 * impact of latencies and k_busy_wait function accuracy.
722 		 */
723 		wait_for_us = 1000;
724 		ticks_expected = counter_us_to_ticks(dev, wait_for_us);
725 	}
726 
727 	/* Set 10% or 2 ticks tolerance, whichever is greater */
728 	ticks_tol = ticks_expected / 10;
729 	ticks_tol = ticks_tol < 2 ? 2 : ticks_tol;
730 
731 	if (!counter_is_counting_up(dev)) {
732 		ticks_expected = counter_get_top_value(dev) - ticks_expected;
733 	}
734 
735 	err = counter_start(dev);
736 	zassert_equal(0, err, "%s: counter failed to start", dev->name);
737 
738 	/* counter might not start from 0, use current value as offset */
739 	counter_get_value(dev, &tick_current);
740 	ticks_expected += tick_current;
741 
742 	k_busy_wait(wait_for_us);
743 
744 	err = counter_get_value(dev, &ticks);
745 
746 	zassert_equal(0, err, "%s: could not get counter value", dev->name);
747 	zassert_between_inclusive(
748 		ticks, ticks_expected > ticks_tol ? ticks_expected - ticks_tol : 0,
749 		ticks_expected + ticks_tol, "%s: counter ticks not in tolerance", dev->name);
750 
751 	/* ticks count is always within ticks_tol for RTC, therefor
752 	 * check, if ticks are greater than 0.
753 	 */
754 	zassert_true((ticks > 0), "%s: counter did not count", dev->name);
755 
756 	err = counter_stop(dev);
757 	zassert_equal(0, err, "%s: counter failed to stop", dev->name);
758 }
759 
ms_period_capable(const struct device * dev)760 static bool ms_period_capable(const struct device *dev)
761 {
762 	uint32_t freq_khz;
763 	uint32_t max_time_ms;
764 
765 	/* Assume 2 ms counter periode can be set for frequency below 1 kHz*/
766 	if (counter_get_frequency(dev) < 1000) {
767 		return true;
768 	}
769 
770 	freq_khz = counter_get_frequency(dev) / 1000;
771 	max_time_ms = counter_get_top_value(dev) / freq_khz;
772 
773 	if (max_time_ms >= 2) {
774 		return true;
775 	}
776 
777 	return false;
778 }
779 
ZTEST(counter_basic,test_valid_function_without_alarm)780 ZTEST(counter_basic, test_valid_function_without_alarm)
781 {
782 	test_all_instances(test_valid_function_without_alarm, ms_period_capable);
783 }
784 
785 /**
786  * Test validates if alarm set too late (current tick or current tick + 1)
787  * results in callback being called.
788  */
test_late_alarm_instance(const struct device * dev)789 static void test_late_alarm_instance(const struct device *dev)
790 {
791 	int err;
792 	uint32_t cnt;
793 	uint32_t tick_us = (uint32_t)counter_ticks_to_us(dev, 1);
794 	uint32_t guard = counter_us_to_ticks(dev, 200);
795 	struct counter_alarm_cfg alarm_cfg = {
796 		.callback = alarm_handler,
797 		.flags = COUNTER_ALARM_CFG_ABSOLUTE |
798 			 COUNTER_ALARM_CFG_EXPIRE_WHEN_LATE,
799 		.user_data = NULL
800 	};
801 
802 	err = counter_set_guard_period(dev, guard,
803 					COUNTER_GUARD_PERIOD_LATE_TO_SET);
804 	zassert_equal(0, err, "%s: Unexpected error", dev->name);
805 
806 	err = counter_start(dev);
807 	zassert_equal(0, err, "%s: Unexpected error", dev->name);
808 
809 	k_busy_wait(2*tick_us);
810 
811 	alarm_cfg.ticks = 0;
812 	err = counter_set_channel_alarm(dev, 0, &alarm_cfg);
813 	zassert_equal(-ETIME, err, "%s: Unexpected error (%d)", dev->name, err);
814 
815 	/* wait couple of ticks */
816 	k_busy_wait(5*tick_us);
817 
818 	cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
819 		alarm_cnt : k_sem_count_get(&alarm_cnt_sem);
820 	zassert_equal(1, cnt,
821 			"%s: Expected %d callbacks, got %d\n",
822 			dev->name, 1, cnt);
823 
824 	err = counter_get_value(dev, &(alarm_cfg.ticks));
825 	zassert_true(err == 0, "%s: Counter read failed (err: %d)", dev->name,
826 		     err);
827 
828 	err = counter_set_channel_alarm(dev, 0, &alarm_cfg);
829 	zassert_equal(-ETIME, err, "%s: Failed to set an alarm (err: %d)",
830 			dev->name, err);
831 
832 	/* wait to ensure that tick+1 timeout will expire. */
833 	k_busy_wait(3*tick_us);
834 
835 	cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
836 		alarm_cnt : k_sem_count_get(&alarm_cnt_sem);
837 	zassert_equal(2, cnt,
838 			"%s: Expected %d callbacks, got %d\n",
839 			dev->name, 2, cnt);
840 }
841 
test_late_alarm_error_instance(const struct device * dev)842 static void test_late_alarm_error_instance(const struct device *dev)
843 {
844 	int err;
845 	uint32_t tick_us = (uint32_t)counter_ticks_to_us(dev, 1);
846 	uint32_t guard = counter_us_to_ticks(dev, 200);
847 	struct counter_alarm_cfg alarm_cfg = {
848 		.callback = alarm_handler,
849 		.flags = COUNTER_ALARM_CFG_ABSOLUTE,
850 		.user_data = NULL
851 	};
852 
853 	err = counter_set_guard_period(dev, guard,
854 					COUNTER_GUARD_PERIOD_LATE_TO_SET);
855 	zassert_equal(0, err, "%s: Unexpected error", dev->name);
856 
857 	err = counter_start(dev);
858 	zassert_equal(0, err, "%s: Unexpected error", dev->name);
859 
860 	k_busy_wait(2*tick_us);
861 
862 	alarm_cfg.ticks = 0;
863 	err = counter_set_channel_alarm(dev, 0, &alarm_cfg);
864 	zassert_equal(-ETIME, err,
865 			"%s: Failed to detect late setting (err: %d)",
866 			dev->name, err);
867 
868 	err = counter_get_value(dev, &(alarm_cfg.ticks));
869 	zassert_true(err == 0, "%s: Counter read failed (err: %d)", dev->name,
870 		     err);
871 
872 	err = counter_set_channel_alarm(dev, 0, &alarm_cfg);
873 	zassert_equal(-ETIME, err,
874 			"%s: Counter failed to detect late setting (err: %d)",
875 			dev->name, err);
876 }
877 
late_detection_capable(const struct device * dev)878 static bool late_detection_capable(const struct device *dev)
879 {
880 	uint32_t guard = counter_get_guard_period(dev,
881 					COUNTER_GUARD_PERIOD_LATE_TO_SET);
882 	int err = counter_set_guard_period(dev, guard,
883 					COUNTER_GUARD_PERIOD_LATE_TO_SET);
884 
885 	if (err == -ENOTSUP) {
886 		return false;
887 	}
888 
889 	if (single_channel_alarm_capable(dev) == false) {
890 		return false;
891 	}
892 
893 	return true;
894 }
895 
ZTEST(counter_basic,test_late_alarm)896 ZTEST(counter_basic, test_late_alarm)
897 {
898 	test_all_instances(test_late_alarm_instance, late_detection_capable);
899 }
900 
ZTEST(counter_basic,test_late_alarm_error)901 ZTEST(counter_basic, test_late_alarm_error)
902 {
903 	test_all_instances(test_late_alarm_error_instance,
904 			   late_detection_capable);
905 }
906 
test_short_relative_alarm_instance(const struct device * dev)907 static void test_short_relative_alarm_instance(const struct device *dev)
908 {
909 	int err;
910 	uint32_t cnt;
911 	uint32_t tick_us = (uint32_t)counter_ticks_to_us(dev, 1);
912 	struct counter_alarm_cfg alarm_cfg = {
913 		.callback = alarm_handler,
914 		.flags = 0,
915 		.user_data = NULL
916 	};
917 
918 	/* for timers with very short ticks, counter_ticks_to_us() returns 0 */
919 	tick_us = tick_us == 0 ? 1 : tick_us;
920 
921 	err = counter_start(dev);
922 	zassert_equal(0, err, "%s: Unexpected error", dev->name);
923 
924 	if (IS_ENABLED(CONFIG_COUNTER_NRF_RTC)) {
925 		k_busy_wait(1000);
926 	}
927 
928 	alarm_cfg.ticks = 1;
929 
930 	for (int i = 0; i < 100; ++i) {
931 		err = counter_set_channel_alarm(dev, 0, &alarm_cfg);
932 		zassert_equal(0, err,
933 				"%s: Failed to set an alarm (err: %d)",
934 				dev->name, err);
935 
936 		/* wait to ensure that tick+1 timeout will expire. */
937 		k_busy_wait(3*tick_us);
938 
939 		cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
940 			alarm_cnt : k_sem_count_get(&alarm_cnt_sem);
941 		zassert_equal(i + 1, cnt,
942 				"%s: Expected %d callbacks, got %d\n",
943 				dev->name, i + 1, cnt);
944 	}
945 }
946 
947 /* Function checks if relative alarm set for 1 tick will expire. If handler is
948  * not called within near future it indicates that driver do not support it and
949  * more extensive testing is skipped.
950  */
short_relative_capable(const struct device * dev)951 static bool short_relative_capable(const struct device *dev)
952 {
953 	struct counter_alarm_cfg alarm_cfg = {
954 		.callback = alarm_handler,
955 		.flags = 0,
956 		.user_data = NULL,
957 		.ticks = 1
958 	};
959 	int err;
960 	uint32_t cnt;
961 	bool ret;
962 
963 	if (single_channel_alarm_capable(dev) == false) {
964 		return false;
965 	}
966 
967 	err = counter_start(dev);
968 	if (err != 0) {
969 		ret = false;
970 		goto end;
971 	}
972 
973 	k_sem_reset(&alarm_cnt_sem);
974 	alarm_cnt = 0;
975 	err = counter_set_channel_alarm(dev, 0, &alarm_cfg);
976 	if (err != 0) {
977 		ret = false;
978 		goto end;
979 	}
980 
981 	k_busy_wait(counter_ticks_to_us(dev, 10));
982 	cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
983 			alarm_cnt : k_sem_count_get(&alarm_cnt_sem);
984 	if (cnt == 1) {
985 		ret = true;
986 	} else {
987 		ret = false;
988 		(void)counter_cancel_channel_alarm(dev, 0);
989 	}
990 
991 end:
992 	k_sem_reset(&alarm_cnt_sem);
993 	alarm_cnt = 0;
994 	counter_stop(dev);
995 	k_busy_wait(1000);
996 
997 	return ret;
998 }
999 
ZTEST(counter_basic,test_short_relative_alarm)1000 ZTEST(counter_basic, test_short_relative_alarm)
1001 {
1002 	test_all_instances(test_short_relative_alarm_instance,
1003 			short_relative_capable);
1004 }
1005 
1006 /* Test checks if cancelled alarm does not get triggered when new alarm is
1007  * configured at the point where previous alarm was about to expire.
1008  */
test_cancelled_alarm_does_not_expire_instance(const struct device * dev)1009 static void test_cancelled_alarm_does_not_expire_instance(const struct device *dev)
1010 {
1011 	int err;
1012 	uint32_t cnt;
1013 	uint32_t us = 1000;
1014 	uint32_t ticks = counter_us_to_ticks(dev, us);
1015 	uint32_t top = counter_get_top_value(dev);
1016 
1017 	us = (uint32_t)counter_ticks_to_us(dev, ticks);
1018 
1019 	struct counter_alarm_cfg alarm_cfg = {
1020 		.callback = alarm_handler,
1021 		.flags = COUNTER_ALARM_CFG_ABSOLUTE,
1022 		.user_data = NULL
1023 	};
1024 
1025 	err = counter_start(dev);
1026 	zassert_equal(0, err, "%s: Unexpected error", dev->name);
1027 
1028 
1029 	for (int i = 0; i < us/2; ++i) {
1030 		err = counter_get_value(dev, &(alarm_cfg.ticks));
1031 		zassert_true(err == 0, "%s: Counter read failed (err: %d)",
1032 			     dev->name, err);
1033 
1034 		alarm_cfg.ticks	+= ticks;
1035 		alarm_cfg.ticks = alarm_cfg.ticks % top;
1036 		err = counter_set_channel_alarm(dev, 0, &alarm_cfg);
1037 		zassert_equal(0, err, "%s: Failed to set an alarm (err: %d)",
1038 				dev->name, err);
1039 
1040 		err = counter_cancel_channel_alarm(dev, 0);
1041 		zassert_equal(0, err, "%s: Failed to cancel an alarm (err: %d)",
1042 				dev->name, err);
1043 
1044 		k_busy_wait(us/2 + i);
1045 
1046 		alarm_cfg.ticks = alarm_cfg.ticks + 2*ticks;
1047 		alarm_cfg.ticks = alarm_cfg.ticks % top;
1048 		err = counter_set_channel_alarm(dev, 0, &alarm_cfg);
1049 		zassert_equal(0, err, "%s: Failed to set an alarm (err: %d)",
1050 				dev->name, err);
1051 
1052 		/* wait to ensure that tick+1 timeout will expire. */
1053 		k_busy_wait(us);
1054 
1055 		err = counter_cancel_channel_alarm(dev, 0);
1056 		zassert_equal(0, err, "%s: Failed to cancel an alarm (err: %d)",
1057 					dev->name, err);
1058 
1059 		cnt = IS_ENABLED(CONFIG_ZERO_LATENCY_IRQS) ?
1060 			alarm_cnt : k_sem_count_get(&alarm_cnt_sem);
1061 		zassert_equal(0, cnt,
1062 				"%s: Expected %d callbacks, got %d (i:%d)\n",
1063 				dev->name, 0, cnt, i);
1064 	}
1065 }
1066 
reliable_cancel_capable(const struct device * dev)1067 static bool reliable_cancel_capable(const struct device *dev)
1068 {
1069 	/* Test performed only for NRF_RTC instances. Other probably will fail.
1070 	 */
1071 #if defined(CONFIG_COUNTER_NRF_RTC) || defined(CONFIG_COUNTER_NRF_TIMER)
1072 	return true;
1073 #endif
1074 #ifdef CONFIG_COUNTER_TIMER_STM32
1075 	if (single_channel_alarm_capable(dev)) {
1076 		return true;
1077 	}
1078 #endif
1079 #ifdef CONFIG_COUNTER_TIMER_MAX32
1080 	if (single_channel_alarm_capable(dev)) {
1081 		return true;
1082 	}
1083 #endif
1084 #ifdef CONFIG_COUNTER_TIMER_GD32
1085 	if (single_channel_alarm_capable(dev)) {
1086 		return true;
1087 	}
1088 #endif
1089 #ifdef CONFIG_COUNTER_NATIVE_SIM
1090 	if (dev == DEVICE_DT_GET(DT_NODELABEL(counter0))) {
1091 		return true;
1092 	}
1093 #endif
1094 #ifdef CONFIG_COUNTER_AMBIQ
1095 	if (single_channel_alarm_capable(dev)) {
1096 		return true;
1097 	}
1098 #endif
1099 #ifdef CONFIG_COUNTER_NXP_S32_SYS_TIMER
1100 	if (single_channel_alarm_capable(dev)) {
1101 		return true;
1102 	}
1103 #endif
1104 #ifdef CONFIG_COUNTER_MCUX_RTC
1105 	if (single_channel_alarm_capable(dev)) {
1106 		return true;
1107 	}
1108 #endif
1109 #ifdef CONFIG_COUNTER_RENESAS_RZ_GTM
1110 	if (single_channel_alarm_capable(dev)) {
1111 		return true;
1112 	}
1113 #endif
1114 	return false;
1115 }
1116 
ZTEST(counter_basic,test_cancelled_alarm_does_not_expire)1117 ZTEST(counter_basic, test_cancelled_alarm_does_not_expire)
1118 {
1119 	test_all_instances(test_cancelled_alarm_does_not_expire_instance,
1120 			reliable_cancel_capable);
1121 }
1122 
counter_setup(void)1123 static void *counter_setup(void)
1124 {
1125 	int i;
1126 
1127 	/* Give required clocks some time to stabilize. In particular, nRF SoCs
1128 	 * need such delay for the Xtal LF clock source to start and for this
1129 	 * test to use the correct timing.
1130 	 */
1131 	k_busy_wait(USEC_PER_MSEC * 300);
1132 
1133 	k_sem_init(&top_cnt_sem, 0, UINT_MAX);
1134 	k_object_access_grant(&top_cnt_sem, k_current_get());
1135 
1136 	k_sem_init(&alarm_cnt_sem, 0, UINT_MAX);
1137 	k_object_access_grant(&alarm_cnt_sem, k_current_get());
1138 
1139 	for (i = 0; i < ARRAY_SIZE(devices); i++) {
1140 		zassert_true(device_is_ready(devices[i]),
1141 			     "Device %s is not ready", devices[i]->name);
1142 		k_object_access_grant(devices[i], k_current_get());
1143 	}
1144 
1145 	return NULL;
1146 }
1147 
1148 /* Uses callbacks, run in supervisor mode */
1149 ZTEST_SUITE(counter_basic, NULL, counter_setup, NULL, NULL, NULL);
1150 
1151 /* No callbacks, run in usermode */
1152 ZTEST_SUITE(counter_no_callback, NULL, counter_setup, NULL, NULL, NULL);
1153