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