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