1 /*
2  * Copyright (c) 2021 Kent Hall.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT st_stm32_counter
8 
9 #include <zephyr/drivers/counter.h>
10 #include <zephyr/drivers/clock_control/stm32_clock_control.h>
11 #include <zephyr/drivers/reset.h>
12 #include <zephyr/irq.h>
13 #include <zephyr/sys/atomic.h>
14 
15 #include <stm32_ll_tim.h>
16 #include <stm32_ll_rcc.h>
17 
18 #include <zephyr/logging/log.h>
19 LOG_MODULE_REGISTER(counter_timer_stm32, CONFIG_COUNTER_LOG_LEVEL);
20 
21 /* L0 series MCUs only have 16-bit timers and don't have below macro defined */
22 #ifndef IS_TIM_32B_COUNTER_INSTANCE
23 #define IS_TIM_32B_COUNTER_INSTANCE(INSTANCE) (0)
24 #endif
25 
26 /** Maximum number of timer channels. */
27 #define TIMER_MAX_CH 4U
28 
29 /** Number of channels for timer by index. */
30 #define NUM_CH(timx)					    \
31 	(IS_TIM_CCX_INSTANCE(timx, TIM_CHANNEL_4) ? 4U :    \
32 	 (IS_TIM_CCX_INSTANCE(timx, TIM_CHANNEL_3) ? 3U :   \
33 	  (IS_TIM_CCX_INSTANCE(timx, TIM_CHANNEL_2) ? 2U :  \
34 	   (IS_TIM_CCX_INSTANCE(timx, TIM_CHANNEL_1) ? 1U : \
35 	    0))))
36 
37 /** Channel to compare set function mapping. */
38 static void(*const set_timer_compare[TIMER_MAX_CH])(TIM_TypeDef *,
39 						    uint32_t) = {
40 	LL_TIM_OC_SetCompareCH1, LL_TIM_OC_SetCompareCH2,
41 	LL_TIM_OC_SetCompareCH3, LL_TIM_OC_SetCompareCH4,
42 };
43 
44 /** Channel to compare get function mapping. */
45 #if !defined(CONFIG_SOC_SERIES_STM32MP1X)
46 static uint32_t(*const get_timer_compare[TIMER_MAX_CH])(const TIM_TypeDef *) = {
47 	LL_TIM_OC_GetCompareCH1, LL_TIM_OC_GetCompareCH2,
48 	LL_TIM_OC_GetCompareCH3, LL_TIM_OC_GetCompareCH4,
49 };
50 #else
51 static uint32_t(*const get_timer_compare[TIMER_MAX_CH])(TIM_TypeDef *) = {
52 	LL_TIM_OC_GetCompareCH1, LL_TIM_OC_GetCompareCH2,
53 	LL_TIM_OC_GetCompareCH3, LL_TIM_OC_GetCompareCH4,
54 };
55 #endif
56 /** Channel to interrupt enable function mapping. */
57 static void(*const enable_it[TIMER_MAX_CH])(TIM_TypeDef *) = {
58 	LL_TIM_EnableIT_CC1, LL_TIM_EnableIT_CC2,
59 	LL_TIM_EnableIT_CC3, LL_TIM_EnableIT_CC4,
60 };
61 
62 /** Channel to interrupt enable function mapping. */
63 static void(*const disable_it[TIMER_MAX_CH])(TIM_TypeDef *) = {
64 	LL_TIM_DisableIT_CC1, LL_TIM_DisableIT_CC2,
65 	LL_TIM_DisableIT_CC3, LL_TIM_DisableIT_CC4,
66 };
67 
68 #ifdef CONFIG_ASSERT
69 /** Channel to interrupt enable check function mapping. */
70 #if !defined(CONFIG_SOC_SERIES_STM32MP1X)
71 static uint32_t(*const check_it_enabled[TIMER_MAX_CH])(const TIM_TypeDef *) = {
72 	LL_TIM_IsEnabledIT_CC1, LL_TIM_IsEnabledIT_CC2,
73 	LL_TIM_IsEnabledIT_CC3, LL_TIM_IsEnabledIT_CC4,
74 };
75 #else
76 static uint32_t(*const check_it_enabled[TIMER_MAX_CH])(TIM_TypeDef *) = {
77 	LL_TIM_IsEnabledIT_CC1, LL_TIM_IsEnabledIT_CC2,
78 	LL_TIM_IsEnabledIT_CC3, LL_TIM_IsEnabledIT_CC4,
79 };
80 #endif
81 #endif
82 
83 /** Channel to interrupt flag clear function mapping. */
84 static void(*const clear_it_flag[TIMER_MAX_CH])(TIM_TypeDef *) = {
85 	LL_TIM_ClearFlag_CC1, LL_TIM_ClearFlag_CC2,
86 	LL_TIM_ClearFlag_CC3, LL_TIM_ClearFlag_CC4,
87 };
88 
89 struct counter_stm32_data {
90 	counter_top_callback_t top_cb;
91 	void *top_user_data;
92 	uint32_t guard_period;
93 	atomic_t cc_int_pending;
94 	uint32_t freq;
95 };
96 
97 struct counter_stm32_ch_data {
98 	counter_alarm_callback_t callback;
99 	void *user_data;
100 };
101 
102 struct counter_stm32_config {
103 	struct counter_config_info info;
104 	struct counter_stm32_ch_data *ch_data;
105 	TIM_TypeDef *timer;
106 	uint32_t prescaler;
107 	struct stm32_pclken pclken;
108 	void (*irq_config_func)(const struct device *dev);
109 	uint32_t irqn;
110 	/* Reset controller device configuration */
111 	const struct reset_dt_spec reset;
112 
113 	LOG_INSTANCE_PTR_DECLARE(log);
114 };
115 
counter_stm32_start(const struct device * dev)116 static int counter_stm32_start(const struct device *dev)
117 {
118 	const struct counter_stm32_config *config = dev->config;
119 	TIM_TypeDef *timer = config->timer;
120 
121 	/* enable counter */
122 	LL_TIM_EnableCounter(timer);
123 
124 	return 0;
125 }
126 
counter_stm32_stop(const struct device * dev)127 static int counter_stm32_stop(const struct device *dev)
128 {
129 	const struct counter_stm32_config *config = dev->config;
130 	TIM_TypeDef *timer = config->timer;
131 
132 	/* disable counter */
133 	LL_TIM_DisableCounter(timer);
134 
135 	return 0;
136 }
137 
counter_stm32_get_top_value(const struct device * dev)138 static uint32_t counter_stm32_get_top_value(const struct device *dev)
139 {
140 	const struct counter_stm32_config *config = dev->config;
141 
142 	return LL_TIM_GetAutoReload(config->timer);
143 }
144 
counter_stm32_read(const struct device * dev)145 static uint32_t counter_stm32_read(const struct device *dev)
146 {
147 	const struct counter_stm32_config *config = dev->config;
148 
149 	return LL_TIM_GetCounter(config->timer);
150 }
151 
counter_stm32_get_value(const struct device * dev,uint32_t * ticks)152 static int counter_stm32_get_value(const struct device *dev, uint32_t *ticks)
153 {
154 	*ticks = counter_stm32_read(dev);
155 	return 0;
156 }
157 
counter_stm32_ticks_add(uint32_t val1,uint32_t val2,uint32_t top)158 static uint32_t counter_stm32_ticks_add(uint32_t val1, uint32_t val2, uint32_t top)
159 {
160 	uint32_t to_top;
161 
162 	if (likely(IS_BIT_MASK(top))) {
163 		return (val1 + val2) & top;
164 	}
165 
166 	to_top = top - val1;
167 
168 	return (val2 <= to_top) ? val1 + val2 : val2 - to_top - 1U;
169 }
170 
counter_stm32_ticks_sub(uint32_t val,uint32_t old,uint32_t top)171 static uint32_t counter_stm32_ticks_sub(uint32_t val, uint32_t old, uint32_t top)
172 {
173 	if (likely(IS_BIT_MASK(top))) {
174 		return (val - old) & top;
175 	}
176 
177 	/* if top is not 2^n-1 */
178 	return (val >= old) ? (val - old) : val + top + 1U - old;
179 }
180 
counter_stm32_counter_stm32_set_cc_int_pending(const struct device * dev,uint8_t chan)181 static void counter_stm32_counter_stm32_set_cc_int_pending(const struct device *dev, uint8_t chan)
182 {
183 	const struct counter_stm32_config *config = dev->config;
184 	struct counter_stm32_data *data = dev->data;
185 
186 	atomic_or(&data->cc_int_pending, BIT(chan));
187 	NVIC_SetPendingIRQ(config->irqn);
188 }
189 
counter_stm32_set_cc(const struct device * dev,uint8_t id,const struct counter_alarm_cfg * alarm_cfg)190 static int counter_stm32_set_cc(const struct device *dev, uint8_t id,
191 				const struct counter_alarm_cfg *alarm_cfg)
192 {
193 	const struct counter_stm32_config *config = dev->config;
194 	struct counter_stm32_data *data = dev->data;
195 
196 	__ASSERT_NO_MSG(data->guard_period < counter_stm32_get_top_value(dev));
197 	uint32_t val = alarm_cfg->ticks;
198 	uint32_t flags = alarm_cfg->flags;
199 	bool absolute = flags & COUNTER_ALARM_CFG_ABSOLUTE;
200 	bool irq_on_late;
201 	TIM_TypeDef *timer = config->timer;
202 	uint32_t top = counter_stm32_get_top_value(dev);
203 	int err = 0;
204 	uint32_t prev_val;
205 	uint32_t now;
206 	uint32_t diff;
207 	uint32_t max_rel_val;
208 
209 	__ASSERT(!check_it_enabled[id](timer),
210 		 "Expected that CC interrupt is disabled.");
211 
212 	/* First take care of a risk of an event coming from CC being set to
213 	 * next tick. Reconfigure CC to future (now tick is the furthest
214 	 * future).
215 	 */
216 	now = counter_stm32_read(dev);
217 	prev_val = get_timer_compare[id](timer);
218 	set_timer_compare[id](timer, now);
219 	clear_it_flag[id](timer);
220 
221 	if (absolute) {
222 		max_rel_val = top - data->guard_period;
223 		irq_on_late = flags & COUNTER_ALARM_CFG_EXPIRE_WHEN_LATE;
224 	} else {
225 		/* If relative value is smaller than half of the counter range
226 		 * it is assumed that there is a risk of setting value too late
227 		 * and late detection algorithm must be applied. When late
228 		 * setting is detected, interrupt shall be triggered for
229 		 * immediate expiration of the timer. Detection is performed
230 		 * by limiting relative distance between CC and counter.
231 		 *
232 		 * Note that half of counter range is an arbitrary value.
233 		 */
234 		irq_on_late = val < (top / 2U);
235 		/* limit max to detect short relative being set too late. */
236 		max_rel_val = irq_on_late ? top / 2U : top;
237 		val = counter_stm32_ticks_add(now, val, top);
238 	}
239 
240 	set_timer_compare[id](timer, val);
241 
242 	/* decrement value to detect also case when val == counter_stm32_read(dev). Otherwise,
243 	 * condition would need to include comparing diff against 0.
244 	 */
245 	diff = counter_stm32_ticks_sub(val - 1U, counter_stm32_read(dev), top);
246 	if (diff > max_rel_val) {
247 		if (absolute) {
248 			err = -ETIME;
249 		}
250 
251 		/* Interrupt is triggered always for relative alarm and
252 		 * for absolute depending on the flag.
253 		 */
254 		if (irq_on_late) {
255 			counter_stm32_counter_stm32_set_cc_int_pending(dev, id);
256 		} else {
257 			config->ch_data[id].callback = NULL;
258 		}
259 	} else {
260 		enable_it[id](timer);
261 	}
262 
263 	return err;
264 }
265 
counter_stm32_set_alarm(const struct device * dev,uint8_t chan,const struct counter_alarm_cfg * alarm_cfg)266 static int counter_stm32_set_alarm(const struct device *dev, uint8_t chan,
267 				   const struct counter_alarm_cfg *alarm_cfg)
268 {
269 	const struct counter_stm32_config *config = dev->config;
270 	struct counter_stm32_ch_data *chdata = &config->ch_data[chan];
271 
272 	if (alarm_cfg->ticks >  counter_stm32_get_top_value(dev)) {
273 		return -EINVAL;
274 	}
275 
276 	if (chdata->callback) {
277 		return -EBUSY;
278 	}
279 
280 	chdata->callback = alarm_cfg->callback;
281 	chdata->user_data = alarm_cfg->user_data;
282 
283 	return counter_stm32_set_cc(dev, chan, alarm_cfg);
284 }
285 
counter_stm32_cancel_alarm(const struct device * dev,uint8_t chan)286 static int counter_stm32_cancel_alarm(const struct device *dev, uint8_t chan)
287 {
288 	const struct counter_stm32_config *config = dev->config;
289 
290 	disable_it[chan](config->timer);
291 	config->ch_data[chan].callback = NULL;
292 
293 	return 0;
294 }
295 
counter_stm32_set_top_value(const struct device * dev,const struct counter_top_cfg * cfg)296 static int counter_stm32_set_top_value(const struct device *dev,
297 				       const struct counter_top_cfg *cfg)
298 {
299 	const struct counter_stm32_config *config = dev->config;
300 	TIM_TypeDef *timer = config->timer;
301 	struct counter_stm32_data *data = dev->data;
302 	int err = 0;
303 
304 	for (int i = 0; i < counter_get_num_of_channels(dev); i++) {
305 		/* Overflow can be changed only when all alarms are
306 		 * disabled.
307 		 */
308 		if (config->ch_data[i].callback) {
309 			return -EBUSY;
310 		}
311 	}
312 
313 	LL_TIM_DisableIT_UPDATE(timer);
314 	LL_TIM_SetAutoReload(timer, cfg->ticks);
315 	LL_TIM_ClearFlag_UPDATE(timer);
316 
317 	data->top_cb = cfg->callback;
318 	data->top_user_data = cfg->user_data;
319 
320 	if (!(cfg->flags & COUNTER_TOP_CFG_DONT_RESET)) {
321 		LL_TIM_SetCounter(timer, 0);
322 	} else if (counter_stm32_read(dev) >= cfg->ticks) {
323 		err = -ETIME;
324 		if (cfg->flags & COUNTER_TOP_CFG_RESET_WHEN_LATE) {
325 			LL_TIM_SetCounter(timer, 0);
326 		}
327 	}
328 
329 	if (cfg->callback) {
330 		LL_TIM_EnableIT_UPDATE(timer);
331 	}
332 
333 	return err;
334 }
335 
counter_stm32_get_pending_int(const struct device * dev)336 static uint32_t counter_stm32_get_pending_int(const struct device *dev)
337 {
338 	const struct counter_stm32_config *cfg = dev->config;
339 	uint32_t pending = 0;
340 
341 	switch (counter_get_num_of_channels(dev)) {
342 	case 4U:
343 		pending |= LL_TIM_IsActiveFlag_CC4(cfg->timer);
344 		__fallthrough;
345 	case 3U:
346 		pending |= LL_TIM_IsActiveFlag_CC3(cfg->timer);
347 		__fallthrough;
348 	case 2U:
349 		pending |= LL_TIM_IsActiveFlag_CC2(cfg->timer);
350 		__fallthrough;
351 	case 1U:
352 		pending |= LL_TIM_IsActiveFlag_CC1(cfg->timer);
353 	}
354 
355 	return !!pending;
356 }
357 
358 /**
359  * Obtain timer clock speed.
360  *
361  * @param pclken  Timer clock control subsystem.
362  * @param tim_clk Where computed timer clock will be stored.
363  *
364  * @return 0 on success, error code otherwise.
365  *
366  * This function is ripped from the PWM driver; TODO handle code duplication.
367  */
counter_stm32_get_tim_clk(const struct stm32_pclken * pclken,uint32_t * tim_clk)368 static int counter_stm32_get_tim_clk(const struct stm32_pclken *pclken, uint32_t *tim_clk)
369 {
370 	int r;
371 	const struct device *clk;
372 	uint32_t bus_clk, apb_psc;
373 
374 	clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
375 
376 	if (!device_is_ready(clk)) {
377 		return -ENODEV;
378 	}
379 
380 	r = clock_control_get_rate(clk, (clock_control_subsys_t)pclken,
381 				   &bus_clk);
382 	if (r < 0) {
383 		return r;
384 	}
385 
386 #if defined(CONFIG_SOC_SERIES_STM32WB0X)
387 	/* Timers are clocked by SYSCLK on STM32WB0 */
388 	apb_psc = 1;
389 #elif defined(CONFIG_SOC_SERIES_STM32H7X)
390 	if (pclken->bus == STM32_CLOCK_BUS_APB1) {
391 		apb_psc = STM32_D2PPRE1;
392 	} else {
393 		apb_psc = STM32_D2PPRE2;
394 	}
395 #else
396 	if (pclken->bus == STM32_CLOCK_BUS_APB1) {
397 #if defined(CONFIG_SOC_SERIES_STM32MP1X)
398 		apb_psc = (uint32_t)(READ_BIT(RCC->APB1DIVR, RCC_APB1DIVR_APB1DIV));
399 #else
400 		apb_psc = STM32_APB1_PRESCALER;
401 #endif /* CONFIG_SOC_SERIES_STM32MP1X */
402 	}
403 #if !DT_HAS_COMPAT_STATUS_OKAY(st_stm32f0_rcc)
404 	else {
405 #if defined(CONFIG_SOC_SERIES_STM32MP1X)
406 		apb_psc = (uint32_t)(READ_BIT(RCC->APB2DIVR, RCC_APB2DIVR_APB2DIV));
407 #else
408 		apb_psc = STM32_APB2_PRESCALER;
409 #endif /* CONFIG_SOC_SERIES_STM32MP1X */
410 	}
411 #endif /* ! st_stm32f0_rcc */
412 #endif /* CONFIG_SOC_SERIES_STM32H7X */
413 
414 #if defined(RCC_DCKCFGR_TIMPRE) || defined(RCC_DCKCFGR1_TIMPRE) || \
415 	defined(RCC_CFGR_TIMPRE)
416 	/*
417 	 * There are certain series (some F4, F7 and H7) that have the TIMPRE
418 	 * bit to control the clock frequency of all the timers connected to
419 	 * APB1 and APB2 domains.
420 	 *
421 	 * Up to a certain threshold value of APB{1,2} prescaler, timer clock
422 	 * equals to HCLK. This threshold value depends on TIMPRE setting
423 	 * (2 if TIMPRE=0, 4 if TIMPRE=1). Above threshold, timer clock is set
424 	 * to a multiple of the APB domain clock PCLK{1,2} (2 if TIMPRE=0, 4 if
425 	 * TIMPRE=1).
426 	 */
427 
428 	if (LL_RCC_GetTIMPrescaler() == LL_RCC_TIM_PRESCALER_TWICE) {
429 		/* TIMPRE = 0 */
430 		if (apb_psc <= 2u) {
431 			LL_RCC_ClocksTypeDef clocks;
432 
433 			LL_RCC_GetSystemClocksFreq(&clocks);
434 			*tim_clk = clocks.HCLK_Frequency;
435 		} else {
436 			*tim_clk = bus_clk * 2u;
437 		}
438 	} else {
439 		/* TIMPRE = 1 */
440 		if (apb_psc <= 4u) {
441 			LL_RCC_ClocksTypeDef clocks;
442 
443 			LL_RCC_GetSystemClocksFreq(&clocks);
444 			*tim_clk = clocks.HCLK_Frequency;
445 		} else {
446 			*tim_clk = bus_clk * 4u;
447 		}
448 	}
449 #else
450 	/*
451 	 * If the APB prescaler equals 1, the timer clock frequencies
452 	 * are set to the same frequency as that of the APB domain.
453 	 * Otherwise, they are set to twice (×2) the frequency of the
454 	 * APB domain.
455 	 */
456 	if (apb_psc == 1u) {
457 		*tim_clk = bus_clk;
458 	} else {
459 		*tim_clk = bus_clk * 2u;
460 	}
461 #endif
462 
463 	return 0;
464 }
465 
counter_stm32_init_timer(const struct device * dev)466 static int counter_stm32_init_timer(const struct device *dev)
467 {
468 	const struct counter_stm32_config *cfg = dev->config;
469 	struct counter_stm32_data *data = dev->data;
470 	TIM_TypeDef *timer = cfg->timer;
471 	LL_TIM_InitTypeDef init;
472 	uint32_t tim_clk;
473 	int r;
474 
475 	/* initialize clock and check its speed  */
476 	r = clock_control_on(DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE),
477 			     (clock_control_subsys_t)&cfg->pclken);
478 	if (r < 0) {
479 		LOG_ERR("Could not initialize clock (%d)", r);
480 		return r;
481 	}
482 	r = counter_stm32_get_tim_clk(&cfg->pclken, &tim_clk);
483 	if (r < 0) {
484 		LOG_ERR("Could not obtain timer clock (%d)", r);
485 		return r;
486 	}
487 	data->freq = tim_clk / (cfg->prescaler + 1U);
488 
489 	if (!device_is_ready(cfg->reset.dev)) {
490 		LOG_ERR("reset controller not ready");
491 		return -ENODEV;
492 	}
493 
494 	/* Reset timer to default state using RCC */
495 	(void)reset_line_toggle_dt(&cfg->reset);
496 
497 	/* config/enable IRQ */
498 	cfg->irq_config_func(dev);
499 
500 	/* initialize timer */
501 	LL_TIM_StructInit(&init);
502 
503 	init.Prescaler = cfg->prescaler;
504 	init.CounterMode = LL_TIM_COUNTERMODE_UP;
505 	init.Autoreload = counter_get_max_top_value(dev);
506 	init.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
507 
508 	if (LL_TIM_Init(timer, &init) != SUCCESS) {
509 		LOG_ERR("Could not initialize timer");
510 		return -EIO;
511 	}
512 
513 	return 0;
514 }
515 
counter_stm32_get_guard_period(const struct device * dev,uint32_t flags)516 static uint32_t counter_stm32_get_guard_period(const struct device *dev, uint32_t flags)
517 {
518 	struct counter_stm32_data *data = dev->data;
519 
520 	ARG_UNUSED(flags);
521 	return data->guard_period;
522 }
523 
counter_stm32_set_guard_period(const struct device * dev,uint32_t guard,uint32_t flags)524 static int counter_stm32_set_guard_period(const struct device *dev, uint32_t guard,
525 					  uint32_t flags)
526 {
527 	struct counter_stm32_data *data = dev->data;
528 
529 	ARG_UNUSED(flags);
530 	__ASSERT_NO_MSG(guard < counter_stm32_get_top_value(dev));
531 
532 	data->guard_period = guard;
533 	return 0;
534 }
535 
counter_stm32_get_freq(const struct device * dev)536 static uint32_t counter_stm32_get_freq(const struct device *dev)
537 {
538 	struct counter_stm32_data *data = dev->data;
539 
540 	return data->freq;
541 }
542 
counter_stm32_top_irq_handle(const struct device * dev)543 static void counter_stm32_top_irq_handle(const struct device *dev)
544 {
545 	struct counter_stm32_data *data = dev->data;
546 
547 	counter_top_callback_t cb = data->top_cb;
548 
549 	__ASSERT(cb != NULL, "top event enabled - expecting callback");
550 	cb(dev, data->top_user_data);
551 }
552 
counter_stm32_alarm_irq_handle(const struct device * dev,uint32_t id)553 static void counter_stm32_alarm_irq_handle(const struct device *dev, uint32_t id)
554 {
555 	const struct counter_stm32_config *config = dev->config;
556 	struct counter_stm32_data *data = dev->data;
557 	TIM_TypeDef *timer = config->timer;
558 
559 	struct counter_stm32_ch_data *chdata;
560 	counter_alarm_callback_t cb;
561 
562 	atomic_and(&data->cc_int_pending, ~BIT(id));
563 	disable_it[id](timer);
564 
565 	chdata = &config->ch_data[id];
566 	cb = chdata->callback;
567 	chdata->callback = NULL;
568 
569 	if (cb) {
570 		uint32_t cc_val = get_timer_compare[id](timer);
571 
572 		cb(dev, id, cc_val, chdata->user_data);
573 	}
574 }
575 
576 static DEVICE_API(counter, counter_stm32_driver_api) = {
577 	.start = counter_stm32_start,
578 	.stop = counter_stm32_stop,
579 	.get_value = counter_stm32_get_value,
580 	.set_alarm = counter_stm32_set_alarm,
581 	.cancel_alarm = counter_stm32_cancel_alarm,
582 	.set_top_value = counter_stm32_set_top_value,
583 	.get_pending_int = counter_stm32_get_pending_int,
584 	.get_top_value = counter_stm32_get_top_value,
585 	.get_guard_period = counter_stm32_get_guard_period,
586 	.set_guard_period = counter_stm32_set_guard_period,
587 	.get_freq = counter_stm32_get_freq,
588 };
589 
590 #define TIM_IRQ_HANDLE_CC(timx, cc)						\
591 	do {									\
592 		bool hw_irq = LL_TIM_IsActiveFlag_CC##cc(timer) &&		\
593 			      LL_TIM_IsEnabledIT_CC##cc(timer);			\
594 		if (hw_irq || (data->cc_int_pending & BIT(cc - 1U))) {		\
595 			if (hw_irq) {						\
596 				LL_TIM_ClearFlag_CC##cc(timer);			\
597 			}							\
598 			counter_stm32_alarm_irq_handle(dev, cc - 1U);		\
599 		}								\
600 	} while (0)
601 
counter_stm32_irq_handler(const struct device * dev)602 void counter_stm32_irq_handler(const struct device *dev)
603 {
604 	const struct counter_stm32_config *config = dev->config;
605 	struct counter_stm32_data *data = dev->data;
606 	TIM_TypeDef *timer = config->timer;
607 
608 	/* Capture compare events */
609 	switch (counter_get_num_of_channels(dev)) {
610 	case 4U:
611 		TIM_IRQ_HANDLE_CC(timer, 4);
612 		__fallthrough;
613 	case 3U:
614 		TIM_IRQ_HANDLE_CC(timer, 3);
615 		__fallthrough;
616 	case 2U:
617 		TIM_IRQ_HANDLE_CC(timer, 2);
618 		__fallthrough;
619 	case 1U:
620 		TIM_IRQ_HANDLE_CC(timer, 1);
621 	}
622 
623 	/* TIM Update event */
624 	if (LL_TIM_IsActiveFlag_UPDATE(timer) && LL_TIM_IsEnabledIT_UPDATE(timer)) {
625 		LL_TIM_ClearFlag_UPDATE(timer);
626 		counter_stm32_top_irq_handle(dev);
627 	}
628 }
629 
630 #define TIMER(idx)              DT_INST_PARENT(idx)
631 
632 /** TIMx instance from DT */
633 #define TIM(idx) ((TIM_TypeDef *)DT_REG_ADDR(TIMER(idx)))
634 
635 #define COUNTER_DEVICE_INIT(idx)						  \
636 	BUILD_ASSERT(DT_PROP(TIMER(idx), st_prescaler) <= 0xFFFF,		  \
637 		     "TIMER prescaler out of range");				  \
638 	BUILD_ASSERT(NUM_CH(TIM(idx)) <= TIMER_MAX_CH,				  \
639 		     "TIMER too many channels");				  \
640 										  \
641 	static struct counter_stm32_data counter##idx##_data;			  \
642 	static struct counter_stm32_ch_data counter##idx##_ch_data[TIMER_MAX_CH]; \
643 										  \
644 	static void counter_##idx##_stm32_irq_config(const struct device *dev)	  \
645 	{									  \
646 		IRQ_CONNECT(DT_IRQN(TIMER(idx)),				  \
647 			    DT_IRQ(TIMER(idx), priority),			  \
648 			    counter_stm32_irq_handler,				  \
649 			    DEVICE_DT_INST_GET(idx),				  \
650 			    0);							  \
651 		irq_enable(DT_IRQN(TIMER(idx)));				  \
652 	}									  \
653 										  \
654 	static const struct counter_stm32_config counter##idx##_config = {	  \
655 		.info = {							  \
656 			.max_top_value =					  \
657 				IS_TIM_32B_COUNTER_INSTANCE(TIM(idx)) ?		  \
658 				0xFFFFFFFF : 0x0000FFFF,			  \
659 			.flags = COUNTER_CONFIG_INFO_COUNT_UP,			  \
660 			.channels = NUM_CH(TIM(idx)),				  \
661 		},								  \
662 		.ch_data = counter##idx##_ch_data,				  \
663 		.timer = TIM(idx),						  \
664 		.prescaler = DT_PROP(TIMER(idx), st_prescaler),			  \
665 		.pclken = {							  \
666 			.bus = DT_CLOCKS_CELL(TIMER(idx), bus),			  \
667 			.enr = DT_CLOCKS_CELL(TIMER(idx), bits)			  \
668 		},								  \
669 		.irq_config_func = counter_##idx##_stm32_irq_config,		  \
670 		.irqn = DT_IRQN(TIMER(idx)),					  \
671 		.reset = RESET_DT_SPEC_GET(TIMER(idx)),				  \
672 	};									  \
673 										  \
674 	DEVICE_DT_INST_DEFINE(idx,						  \
675 			      counter_stm32_init_timer,				  \
676 			      NULL,						  \
677 			      &counter##idx##_data,				  \
678 			      &counter##idx##_config,				  \
679 			      PRE_KERNEL_1, CONFIG_COUNTER_INIT_PRIORITY,	  \
680 			      &counter_stm32_driver_api);
681 
682 DT_INST_FOREACH_STATUS_OKAY(COUNTER_DEVICE_INIT)
683