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