1 /*
2  * Copyright (c) 2016 Linaro Limited.
3  * Copyright (c) 2020 Teslabs Engineering S.L.
4  * Copyright (c) 2023 Nobleo Technology
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #define DT_DRV_COMPAT st_stm32_pwm
10 
11 #include <errno.h>
12 
13 #include <soc.h>
14 #include <stm32_ll_rcc.h>
15 #include <stm32_ll_tim.h>
16 #include <zephyr/drivers/pwm.h>
17 #include <zephyr/drivers/pinctrl.h>
18 #include <zephyr/drivers/reset.h>
19 #include <zephyr/device.h>
20 #include <zephyr/kernel.h>
21 #include <zephyr/init.h>
22 
23 #include <zephyr/drivers/clock_control/stm32_clock_control.h>
24 #include <zephyr/dt-bindings/pwm/stm32_pwm.h>
25 
26 #include <zephyr/logging/log.h>
27 #include <zephyr/irq.h>
28 
29 LOG_MODULE_REGISTER(pwm_stm32, CONFIG_PWM_LOG_LEVEL);
30 
31 /* L0 series MCUs only have 16-bit timers and don't have below macro defined */
32 #ifndef IS_TIM_32B_COUNTER_INSTANCE
33 #define IS_TIM_32B_COUNTER_INSTANCE(INSTANCE) (0)
34 #endif
35 
36 #ifdef CONFIG_PWM_CAPTURE
37 
38 /**
39  * @brief Capture state when in 4-channel support mode
40  */
41 enum capture_state {
42 	CAPTURE_STATE_IDLE = 0,
43 	CAPTURE_STATE_WAIT_FOR_UPDATE_EVENT = 1,
44 	CAPTURE_STATE_WAIT_FOR_PULSE_START = 2,
45 	CAPTURE_STATE_WAIT_FOR_PERIOD_END = 3
46 };
47 
48 /** Return the complimentary channel number
49  * that is used to capture the end of the pulse.
50  */
51 static const uint32_t complimentary_channel[] = {0, 2, 1, 4, 3};
52 
53 struct pwm_stm32_capture_data {
54 	pwm_capture_callback_handler_t callback;
55 	void *user_data;
56 	uint32_t period;
57 	uint32_t pulse;
58 	uint32_t overflows;
59 	uint8_t skip_irq;
60 	bool capture_period;
61 	bool capture_pulse;
62 	bool continuous;
63 	uint8_t channel;
64 
65 	/* only used when four_channel_capture_support */
66 	enum capture_state state;
67 };
68 
69 /* When PWM capture is done by resetting the counter with UIF then the
70  * first capture is always nonsense, second is nonsense when polarity changed
71  * This is not the case when using four-channel-support.
72  */
73 #define SKIPPED_PWM_CAPTURES 2u
74 
75 #endif /*CONFIG_PWM_CAPTURE*/
76 
77 /** PWM data. */
78 struct pwm_stm32_data {
79 	/** Timer clock (Hz). */
80 	uint32_t tim_clk;
81 	/* Reset controller device configuration */
82 	const struct reset_dt_spec reset;
83 #ifdef CONFIG_PWM_CAPTURE
84 	struct pwm_stm32_capture_data capture;
85 #endif /* CONFIG_PWM_CAPTURE */
86 };
87 
88 /** PWM configuration. */
89 struct pwm_stm32_config {
90 	TIM_TypeDef *timer;
91 	uint32_t prescaler;
92 	uint32_t countermode;
93 	struct stm32_pclken pclken;
94 	const struct pinctrl_dev_config *pcfg;
95 #ifdef CONFIG_PWM_CAPTURE
96 	void (*irq_config_func)(const struct device *dev);
97 	const bool four_channel_capture_support;
98 #endif /* CONFIG_PWM_CAPTURE */
99 };
100 
101 /** Maximum number of timer channels : some stm32 soc have 6 else only 4 */
102 #if defined(LL_TIM_CHANNEL_CH6)
103 #define TIMER_HAS_6CH 1
104 #define TIMER_MAX_CH 6u
105 #else
106 #define TIMER_HAS_6CH 0
107 #define TIMER_MAX_CH 4u
108 #endif
109 
110 /** Channel to LL mapping. */
111 static const uint32_t ch2ll[TIMER_MAX_CH] = {
112 	LL_TIM_CHANNEL_CH1, LL_TIM_CHANNEL_CH2,
113 	LL_TIM_CHANNEL_CH3, LL_TIM_CHANNEL_CH4,
114 #if TIMER_HAS_6CH
115 	LL_TIM_CHANNEL_CH5, LL_TIM_CHANNEL_CH6
116 #endif
117 };
118 
119 /** Some stm32 mcus have complementary channels : 3 or 4 */
120 static const uint32_t ch2ll_n[] = {
121 #if defined(LL_TIM_CHANNEL_CH1N)
122 	LL_TIM_CHANNEL_CH1N,
123 	LL_TIM_CHANNEL_CH2N,
124 	LL_TIM_CHANNEL_CH3N,
125 #if defined(LL_TIM_CHANNEL_CH4N)
126 /** stm32g4x and stm32u5x have 4 complementary channels */
127 	LL_TIM_CHANNEL_CH4N,
128 #endif /* LL_TIM_CHANNEL_CH4N */
129 #endif /* LL_TIM_CHANNEL_CH1N */
130 };
131 /** Maximum number of complemented timer channels is ARRAY_SIZE(ch2ll_n)*/
132 
133 /** Channel to compare set function mapping. */
134 static void (*const set_timer_compare[TIMER_MAX_CH])(TIM_TypeDef *,
135 						     uint32_t) = {
136 	LL_TIM_OC_SetCompareCH1, LL_TIM_OC_SetCompareCH2,
137 	LL_TIM_OC_SetCompareCH3, LL_TIM_OC_SetCompareCH4,
138 #if TIMER_HAS_6CH
139 	LL_TIM_OC_SetCompareCH5, LL_TIM_OC_SetCompareCH6
140 #endif
141 };
142 
143 /** Channel to capture get function mapping. */
144 #if !defined(CONFIG_SOC_SERIES_STM32F4X) && \
145 	!defined(CONFIG_SOC_SERIES_STM32G4X) && \
146 	!defined(CONFIG_SOC_SERIES_STM32MP1X)
147 static uint32_t __maybe_unused (*const get_channel_capture[])(const TIM_TypeDef *) = {
148 #else
149 static uint32_t __maybe_unused (*const get_channel_capture[])(TIM_TypeDef *) = {
150 #endif
151 	LL_TIM_IC_GetCaptureCH1, LL_TIM_IC_GetCaptureCH2,
152 	LL_TIM_IC_GetCaptureCH3, LL_TIM_IC_GetCaptureCH4
153 };
154 
155 
156 /** Channel to enable capture interrupt mapping. */
157 static void __maybe_unused (*const enable_capture_interrupt[])(TIM_TypeDef *) = {
158 	LL_TIM_EnableIT_CC1, LL_TIM_EnableIT_CC2,
159 	LL_TIM_EnableIT_CC3, LL_TIM_EnableIT_CC4
160 };
161 
162 /** Channel to disable capture interrupt mapping. */
163 static void __maybe_unused (*const disable_capture_interrupt[])(TIM_TypeDef *) = {
164 	LL_TIM_DisableIT_CC1, LL_TIM_DisableIT_CC2,
165 	LL_TIM_DisableIT_CC3, LL_TIM_DisableIT_CC4
166 };
167 
168 /** Channel to is capture active flag mapping. */
169 #if !defined(CONFIG_SOC_SERIES_STM32F4X) && \
170 	!defined(CONFIG_SOC_SERIES_STM32G4X) && \
171 	!defined(CONFIG_SOC_SERIES_STM32MP1X)
172 static uint32_t __maybe_unused (*const is_capture_active[])(const TIM_TypeDef *) = {
173 #else
174 static uint32_t __maybe_unused (*const is_capture_active[])(TIM_TypeDef *) = {
175 #endif
176 	LL_TIM_IsActiveFlag_CC1, LL_TIM_IsActiveFlag_CC2,
177 	LL_TIM_IsActiveFlag_CC3, LL_TIM_IsActiveFlag_CC4
178 };
179 
180 /** Channel to clearing capture flag mapping. */
181 static void __maybe_unused (*const clear_capture_interrupt[])(TIM_TypeDef *) = {
182 	LL_TIM_ClearFlag_CC1, LL_TIM_ClearFlag_CC2,
183 	LL_TIM_ClearFlag_CC3, LL_TIM_ClearFlag_CC4
184 };
185 
186 /**
187  * Obtain LL polarity from PWM flags.
188  *
189  * @param flags PWM flags.
190  *
191  * @return LL polarity.
192  */
get_polarity(pwm_flags_t flags)193 static uint32_t get_polarity(pwm_flags_t flags)
194 {
195 	if ((flags & PWM_POLARITY_MASK) == PWM_POLARITY_NORMAL) {
196 		return LL_TIM_OCPOLARITY_HIGH;
197 	}
198 
199 	return LL_TIM_OCPOLARITY_LOW;
200 }
201 
202 /**
203  * @brief  Check if LL counter mode is center-aligned.
204  *
205  * @param  ll_countermode LL counter mode.
206  *
207  * @return `true` when center-aligned, otherwise `false`.
208  */
is_center_aligned(const uint32_t ll_countermode)209 static inline bool is_center_aligned(const uint32_t ll_countermode)
210 {
211 	return ((ll_countermode == LL_TIM_COUNTERMODE_CENTER_DOWN) ||
212 		(ll_countermode == LL_TIM_COUNTERMODE_CENTER_UP) ||
213 		(ll_countermode == LL_TIM_COUNTERMODE_CENTER_UP_DOWN));
214 }
215 
216 /**
217  * Obtain timer clock speed.
218  *
219  * @param pclken  Timer clock control subsystem.
220  * @param tim_clk Where computed timer clock will be stored.
221  *
222  * @return 0 on success, error code otherwise.
223  */
get_tim_clk(const struct stm32_pclken * pclken,uint32_t * tim_clk)224 static int get_tim_clk(const struct stm32_pclken *pclken, uint32_t *tim_clk)
225 {
226 	int r;
227 	const struct device *clk;
228 	uint32_t bus_clk, apb_psc;
229 
230 	clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
231 
232 	r = clock_control_get_rate(clk, (clock_control_subsys_t)pclken,
233 				   &bus_clk);
234 	if (r < 0) {
235 		return r;
236 	}
237 
238 #if defined(CONFIG_SOC_SERIES_STM32H7X)
239 	if (pclken->bus == STM32_CLOCK_BUS_APB1) {
240 		apb_psc = STM32_D2PPRE1;
241 	} else {
242 		apb_psc = STM32_D2PPRE2;
243 	}
244 #else
245 	if (pclken->bus == STM32_CLOCK_BUS_APB1) {
246 #if defined(CONFIG_SOC_SERIES_STM32MP1X)
247 		apb_psc = (uint32_t)(READ_BIT(RCC->APB1DIVR, RCC_APB1DIVR_APB1DIV));
248 #else
249 		apb_psc = STM32_APB1_PRESCALER;
250 #endif
251 	}
252 #if !defined(CONFIG_SOC_SERIES_STM32C0X) && !defined(CONFIG_SOC_SERIES_STM32F0X) &&                \
253 	!defined(CONFIG_SOC_SERIES_STM32G0X)
254 	else {
255 #if defined(CONFIG_SOC_SERIES_STM32MP1X)
256 		apb_psc = (uint32_t)(READ_BIT(RCC->APB2DIVR, RCC_APB2DIVR_APB2DIV));
257 #else
258 		apb_psc = STM32_APB2_PRESCALER;
259 #endif
260 	}
261 #endif
262 #endif
263 
264 #if defined(RCC_DCKCFGR_TIMPRE) || defined(RCC_DCKCFGR1_TIMPRE) || \
265 	defined(RCC_CFGR_TIMPRE)
266 	/*
267 	 * There are certain series (some F4, F7 and H7) that have the TIMPRE
268 	 * bit to control the clock frequency of all the timers connected to
269 	 * APB1 and APB2 domains.
270 	 *
271 	 * Up to a certain threshold value of APB{1,2} prescaler, timer clock
272 	 * equals to HCLK. This threshold value depends on TIMPRE setting
273 	 * (2 if TIMPRE=0, 4 if TIMPRE=1). Above threshold, timer clock is set
274 	 * to a multiple of the APB domain clock PCLK{1,2} (2 if TIMPRE=0, 4 if
275 	 * TIMPRE=1).
276 	 */
277 
278 	if (LL_RCC_GetTIMPrescaler() == LL_RCC_TIM_PRESCALER_TWICE) {
279 		/* TIMPRE = 0 */
280 		if (apb_psc <= 2u) {
281 			LL_RCC_ClocksTypeDef clocks;
282 
283 			LL_RCC_GetSystemClocksFreq(&clocks);
284 			*tim_clk = clocks.HCLK_Frequency;
285 		} else {
286 			*tim_clk = bus_clk * 2u;
287 		}
288 	} else {
289 		/* TIMPRE = 1 */
290 		if (apb_psc <= 4u) {
291 			LL_RCC_ClocksTypeDef clocks;
292 
293 			LL_RCC_GetSystemClocksFreq(&clocks);
294 			*tim_clk = clocks.HCLK_Frequency;
295 		} else {
296 			*tim_clk = bus_clk * 4u;
297 		}
298 	}
299 #else
300 	/*
301 	 * If the APB prescaler equals 1, the timer clock frequencies
302 	 * are set to the same frequency as that of the APB domain.
303 	 * Otherwise, they are set to twice (×2) the frequency of the
304 	 * APB domain.
305 	 */
306 	if (apb_psc == 1u) {
307 		*tim_clk = bus_clk;
308 	} else {
309 		*tim_clk = bus_clk * 2u;
310 	}
311 #endif
312 
313 	return 0;
314 }
315 
pwm_stm32_set_cycles(const struct device * dev,uint32_t channel,uint32_t period_cycles,uint32_t pulse_cycles,pwm_flags_t flags)316 static int pwm_stm32_set_cycles(const struct device *dev, uint32_t channel,
317 				uint32_t period_cycles, uint32_t pulse_cycles,
318 				pwm_flags_t flags)
319 {
320 	const struct pwm_stm32_config *cfg = dev->config;
321 
322 	uint32_t ll_channel;
323 	uint32_t current_ll_channel; /* complementary output if used */
324 	uint32_t negative_ll_channel;
325 
326 	if (channel < 1u || channel > TIMER_MAX_CH) {
327 		LOG_ERR("Invalid channel (%d)", channel);
328 		return -EINVAL;
329 	}
330 
331 	/*
332 	 * Non 32-bit timers count from 0 up to the value in the ARR register
333 	 * (16-bit). Thus period_cycles cannot be greater than UINT16_MAX + 1.
334 	 */
335 	if (!IS_TIM_32B_COUNTER_INSTANCE(cfg->timer) &&
336 	    (period_cycles > UINT16_MAX + 1)) {
337 		return -ENOTSUP;
338 	}
339 
340 #ifdef CONFIG_PWM_CAPTURE
341 	if (LL_TIM_IsEnabledIT_CC1(cfg->timer) || LL_TIM_IsEnabledIT_CC2(cfg->timer) ||
342 	    LL_TIM_IsEnabledIT_CC3(cfg->timer) || LL_TIM_IsEnabledIT_CC4(cfg->timer)) {
343 		LOG_ERR("Cannot set PWM output, capture in progress");
344 		return -EBUSY;
345 	}
346 #endif /* CONFIG_PWM_CAPTURE */
347 
348 	ll_channel = ch2ll[channel - 1u];
349 
350 	if (channel <= ARRAY_SIZE(ch2ll_n)) {
351 		negative_ll_channel = ch2ll_n[channel - 1u];
352 	} else {
353 		negative_ll_channel = 0;
354 	}
355 
356 	/* in LL_TIM_CC_DisableChannel and LL_TIM_CC_IsEnabledChannel,
357 	 * the channel param could be the complementary one
358 	 */
359 	if ((flags & STM32_PWM_COMPLEMENTARY_MASK) == STM32_PWM_COMPLEMENTARY) {
360 		if (!negative_ll_channel) {
361 			/* setting a flag on a channel that has not this capability */
362 			LOG_ERR("Channel %d has NO complementary output", channel);
363 			return -EINVAL;
364 		}
365 		current_ll_channel = negative_ll_channel;
366 	} else {
367 		current_ll_channel = ll_channel;
368 	}
369 
370 	if (period_cycles == 0u) {
371 		LL_TIM_CC_DisableChannel(cfg->timer, current_ll_channel);
372 		return 0;
373 	}
374 
375 	if (cfg->countermode == LL_TIM_COUNTERMODE_UP) {
376 		/* remove 1 period cycle, accounts for 1 extra low cycle */
377 		period_cycles -= 1U;
378 	} else if (cfg->countermode == LL_TIM_COUNTERMODE_DOWN) {
379 		/* remove 1 pulse cycle, accounts for 1 extra high cycle */
380 		pulse_cycles -= 1U;
381 		/* remove 1 period cycle, accounts for 1 extra low cycle */
382 		period_cycles -= 1U;
383 	} else if (is_center_aligned(cfg->countermode)) {
384 		pulse_cycles /= 2U;
385 		period_cycles /= 2U;
386 	} else {
387 		return -ENOTSUP;
388 	}
389 
390 	if (!LL_TIM_CC_IsEnabledChannel(cfg->timer, current_ll_channel)) {
391 		LL_TIM_OC_InitTypeDef oc_init;
392 
393 		LL_TIM_OC_StructInit(&oc_init);
394 
395 		oc_init.OCMode = LL_TIM_OCMODE_PWM1;
396 
397 #if defined(LL_TIM_CHANNEL_CH1N)
398 		/* the flags holds the STM32_PWM_COMPLEMENTARY information */
399 		if ((flags & STM32_PWM_COMPLEMENTARY_MASK) == STM32_PWM_COMPLEMENTARY) {
400 			oc_init.OCNState = LL_TIM_OCSTATE_ENABLE;
401 			oc_init.OCNPolarity = get_polarity(flags);
402 
403 			/* inherit the polarity of the positive output */
404 			oc_init.OCState = LL_TIM_CC_IsEnabledChannel(cfg->timer, ll_channel)
405 						  ? LL_TIM_OCSTATE_ENABLE
406 						  : LL_TIM_OCSTATE_DISABLE;
407 			oc_init.OCPolarity = LL_TIM_OC_GetPolarity(cfg->timer, ll_channel);
408 		} else {
409 			oc_init.OCState = LL_TIM_OCSTATE_ENABLE;
410 			oc_init.OCPolarity = get_polarity(flags);
411 
412 			/* inherit the polarity of the negative output */
413 			if (negative_ll_channel) {
414 				oc_init.OCNState =
415 					LL_TIM_CC_IsEnabledChannel(cfg->timer, negative_ll_channel)
416 						? LL_TIM_OCSTATE_ENABLE
417 						: LL_TIM_OCSTATE_DISABLE;
418 				oc_init.OCNPolarity =
419 					LL_TIM_OC_GetPolarity(cfg->timer, negative_ll_channel);
420 			}
421 		}
422 #else /* LL_TIM_CHANNEL_CH1N */
423 
424 		oc_init.OCState = LL_TIM_OCSTATE_ENABLE;
425 		oc_init.OCPolarity = get_polarity(flags);
426 #endif /* LL_TIM_CHANNEL_CH1N */
427 		oc_init.CompareValue = pulse_cycles;
428 
429 #ifdef CONFIG_PWM_CAPTURE
430 		if (IS_TIM_SLAVE_INSTANCE(cfg->timer)) {
431 			LL_TIM_SetSlaveMode(cfg->timer,
432 					LL_TIM_SLAVEMODE_DISABLED);
433 			LL_TIM_SetTriggerInput(cfg->timer, LL_TIM_TS_ITR0);
434 			LL_TIM_DisableMasterSlaveMode(cfg->timer);
435 		}
436 #endif /* CONFIG_PWM_CAPTURE */
437 
438 		/* in LL_TIM_OC_Init, the channel is always the non-complementary */
439 		if (LL_TIM_OC_Init(cfg->timer, ll_channel, &oc_init) != SUCCESS) {
440 			LOG_ERR("Could not initialize timer channel output");
441 			return -EIO;
442 		}
443 
444 		LL_TIM_EnableARRPreload(cfg->timer);
445 		/* in LL_TIM_OC_EnablePreload, the channel is always the non-complementary */
446 		LL_TIM_OC_EnablePreload(cfg->timer, ll_channel);
447 		LL_TIM_SetAutoReload(cfg->timer, period_cycles);
448 		LL_TIM_GenerateEvent_UPDATE(cfg->timer);
449 	} else {
450 		/* in LL_TIM_OC_SetPolarity, the channel could be the complementary one */
451 		LL_TIM_OC_SetPolarity(cfg->timer, current_ll_channel, get_polarity(flags));
452 		set_timer_compare[channel - 1u](cfg->timer, pulse_cycles);
453 		LL_TIM_SetAutoReload(cfg->timer, period_cycles);
454 	}
455 
456 	return 0;
457 }
458 
459 #ifdef CONFIG_PWM_CAPTURE
init_capture_channels(const struct device * dev,uint32_t channel,pwm_flags_t flags)460 static int init_capture_channels(const struct device *dev, uint32_t channel,
461 				pwm_flags_t flags)
462 {
463 	const struct pwm_stm32_config *cfg = dev->config;
464 	bool is_inverted = (flags & PWM_POLARITY_MASK) == PWM_POLARITY_INVERTED;
465 	LL_TIM_IC_InitTypeDef ic;
466 
467 	LL_TIM_IC_StructInit(&ic);
468 	ic.ICPrescaler = TIM_ICPSC_DIV1;
469 	ic.ICFilter = LL_TIM_IC_FILTER_FDIV1;
470 
471 	/* Setup main channel */
472 	ic.ICActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI;
473 	ic.ICPolarity = is_inverted ? LL_TIM_IC_POLARITY_FALLING : LL_TIM_IC_POLARITY_RISING;
474 
475 	if (LL_TIM_IC_Init(cfg->timer, ch2ll[channel - 1], &ic) != SUCCESS) {
476 		LOG_ERR("Could not initialize main channel for PWM capture");
477 		return -EIO;
478 	}
479 
480 	/* Setup complimentary channel */
481 	ic.ICActiveInput = LL_TIM_ACTIVEINPUT_INDIRECTTI;
482 	ic.ICPolarity = is_inverted ? LL_TIM_IC_POLARITY_RISING : LL_TIM_IC_POLARITY_FALLING;
483 
484 	if (LL_TIM_IC_Init(cfg->timer, ch2ll[complimentary_channel[channel] - 1], &ic) != SUCCESS) {
485 		LOG_ERR("Could not initialize complimentary channel for PWM capture");
486 		return -EIO;
487 	}
488 
489 	return 0;
490 }
491 
pwm_stm32_configure_capture(const struct device * dev,uint32_t channel,pwm_flags_t flags,pwm_capture_callback_handler_t cb,void * user_data)492 static int pwm_stm32_configure_capture(const struct device *dev,
493 				       uint32_t channel, pwm_flags_t flags,
494 				       pwm_capture_callback_handler_t cb,
495 				       void *user_data)
496 {
497 	/*
498 	 * Capture is implemented in two different ways, depending on the
499 	 * four-channel-capture-support setting in the node.
500 	 *  - Two Channel Support:
501 	 *	Only two channels (1 and 2) are available for capture. It uses
502 	 *	the slave mode controller to reset the counter on each edge.
503 	 *  - Four Channel Support:
504 	 *	All four channels are available for capture. Instead of the
505 	 *	slave mode controller it uses the ISR to reset the counter.
506 	 *	This is slightly less accurate, but still within acceptable
507 	 *	bounds.
508 	 */
509 
510 	const struct pwm_stm32_config *cfg = dev->config;
511 	struct pwm_stm32_data *data = dev->data;
512 	struct pwm_stm32_capture_data *cpt = &data->capture;
513 	int ret;
514 
515 	if (!cfg->four_channel_capture_support) {
516 		if ((channel != 1u) && (channel != 2u)) {
517 			LOG_ERR("PWM capture only supported on first two channels");
518 			return -ENOTSUP;
519 		}
520 	} else {
521 		if ((channel < 1u) || (channel > 4u)) {
522 			LOG_ERR("PWM capture only exists on channels 1, 2, 3 and 4.");
523 			return -ENOTSUP;
524 		}
525 	}
526 
527 	if (LL_TIM_IsEnabledIT_CC1(cfg->timer) || LL_TIM_IsEnabledIT_CC2(cfg->timer) ||
528 	    LL_TIM_IsEnabledIT_CC3(cfg->timer) || LL_TIM_IsEnabledIT_CC4(cfg->timer)) {
529 		LOG_ERR("PWM capture already in progress");
530 		return -EBUSY;
531 	}
532 
533 	if (!(flags & PWM_CAPTURE_TYPE_MASK)) {
534 		LOG_ERR("No PWM capture type specified");
535 		return -EINVAL;
536 	}
537 
538 	if (!cfg->four_channel_capture_support && !IS_TIM_SLAVE_INSTANCE(cfg->timer)) {
539 		/* slave mode is only used when not in four channel mode */
540 		LOG_ERR("Timer does not support slave mode for PWM capture");
541 		return -ENOTSUP;
542 	}
543 
544 	cpt->callback = cb; /* even if the cb is reset, this is not an error */
545 	cpt->user_data = user_data;
546 	cpt->capture_period = (flags & PWM_CAPTURE_TYPE_PERIOD) ? true : false;
547 	cpt->capture_pulse = (flags & PWM_CAPTURE_TYPE_PULSE) ? true : false;
548 	cpt->continuous = (flags & PWM_CAPTURE_MODE_CONTINUOUS) ? true : false;
549 
550 	/* Prevents faulty behavior while making changes */
551 	LL_TIM_SetSlaveMode(cfg->timer, LL_TIM_SLAVEMODE_DISABLED);
552 
553 	ret = init_capture_channels(dev, channel, flags);
554 	if (ret < 0) {
555 		return ret;
556 	}
557 
558 	if (!cfg->four_channel_capture_support) {
559 		if (channel == 1u) {
560 			LL_TIM_SetTriggerInput(cfg->timer, LL_TIM_TS_TI1FP1);
561 		} else {
562 			LL_TIM_SetTriggerInput(cfg->timer, LL_TIM_TS_TI2FP2);
563 		}
564 		LL_TIM_SetSlaveMode(cfg->timer, LL_TIM_SLAVEMODE_RESET);
565 	}
566 
567 	LL_TIM_EnableARRPreload(cfg->timer);
568 	if (!IS_TIM_32B_COUNTER_INSTANCE(cfg->timer)) {
569 		LL_TIM_SetAutoReload(cfg->timer, 0xffffu);
570 	} else {
571 		LL_TIM_SetAutoReload(cfg->timer, 0xffffffffu);
572 	}
573 	LL_TIM_EnableUpdateEvent(cfg->timer);
574 
575 	return 0;
576 }
577 
pwm_stm32_enable_capture(const struct device * dev,uint32_t channel)578 static int pwm_stm32_enable_capture(const struct device *dev, uint32_t channel)
579 {
580 	const struct pwm_stm32_config *cfg = dev->config;
581 	struct pwm_stm32_data *data = dev->data;
582 	struct pwm_stm32_capture_data *cpt = &data->capture;
583 
584 	if (!cfg->four_channel_capture_support) {
585 		if ((channel != 1u) && (channel != 2u)) {
586 			LOG_ERR("PWM capture only supported on first two channels");
587 			return -ENOTSUP;
588 		}
589 	} else {
590 		if ((channel < 1u) || (channel > 4u)) {
591 			LOG_ERR("PWM capture only exists on channels 1, 2, 3 and 4.");
592 			return -ENOTSUP;
593 		}
594 	}
595 
596 	if (LL_TIM_IsEnabledIT_CC1(cfg->timer) || LL_TIM_IsEnabledIT_CC2(cfg->timer) ||
597 	    LL_TIM_IsEnabledIT_CC3(cfg->timer) || LL_TIM_IsEnabledIT_CC4(cfg->timer)) {
598 		LOG_ERR("PWM capture already active");
599 		return -EBUSY;
600 	}
601 
602 	if (!data->capture.callback) {
603 		LOG_ERR("PWM capture not configured");
604 		return -EINVAL;
605 	}
606 
607 	cpt->channel = channel;
608 	cpt->state = CAPTURE_STATE_WAIT_FOR_PULSE_START;
609 	data->capture.skip_irq = cfg->four_channel_capture_support ?  0 : SKIPPED_PWM_CAPTURES;
610 	data->capture.overflows = 0u;
611 
612 	clear_capture_interrupt[channel - 1](cfg->timer);
613 	LL_TIM_ClearFlag_UPDATE(cfg->timer);
614 
615 	LL_TIM_SetUpdateSource(cfg->timer, LL_TIM_UPDATESOURCE_COUNTER);
616 
617 	enable_capture_interrupt[channel - 1](cfg->timer);
618 
619 	LL_TIM_CC_EnableChannel(cfg->timer, ch2ll[channel - 1]);
620 	LL_TIM_CC_EnableChannel(cfg->timer, ch2ll[complimentary_channel[channel] - 1]);
621 	LL_TIM_EnableIT_UPDATE(cfg->timer);
622 	LL_TIM_GenerateEvent_UPDATE(cfg->timer);
623 
624 	return 0;
625 }
626 
pwm_stm32_disable_capture(const struct device * dev,uint32_t channel)627 static int pwm_stm32_disable_capture(const struct device *dev, uint32_t channel)
628 {
629 	const struct pwm_stm32_config *cfg = dev->config;
630 
631 	if (!cfg->four_channel_capture_support) {
632 		if ((channel != 1u) && (channel != 2u)) {
633 			LOG_ERR("PWM capture only supported on first two channels");
634 			return -ENOTSUP;
635 		}
636 	} else {
637 		if ((channel < 1u) || (channel > 4u)) {
638 			LOG_ERR("PWM capture only exists on channels 1, 2, 3 and 4.");
639 			return -ENOTSUP;
640 		}
641 	}
642 
643 	LL_TIM_SetUpdateSource(cfg->timer, LL_TIM_UPDATESOURCE_REGULAR);
644 
645 	disable_capture_interrupt[channel - 1](cfg->timer);
646 
647 	LL_TIM_DisableIT_UPDATE(cfg->timer);
648 	LL_TIM_CC_DisableChannel(cfg->timer, ch2ll[channel - 1]);
649 	LL_TIM_CC_DisableChannel(cfg->timer, ch2ll[complimentary_channel[channel] - 1]);
650 
651 	return 0;
652 }
653 
pwm_stm32_isr(const struct device * dev)654 static void pwm_stm32_isr(const struct device *dev)
655 {
656 	const struct pwm_stm32_config *cfg = dev->config;
657 	struct pwm_stm32_data *data = dev->data;
658 	struct pwm_stm32_capture_data *cpt = &data->capture;
659 	int status = 0;
660 
661 	if (cpt->skip_irq != 0u) {
662 		if (LL_TIM_IsActiveFlag_UPDATE(cfg->timer)) {
663 			LL_TIM_ClearFlag_UPDATE(cfg->timer);
664 		}
665 
666 		if (LL_TIM_IsActiveFlag_CC1(cfg->timer)
667 				|| LL_TIM_IsActiveFlag_CC2(cfg->timer)
668 				|| LL_TIM_IsActiveFlag_CC3(cfg->timer)
669 				|| LL_TIM_IsActiveFlag_CC4(cfg->timer)) {
670 			LL_TIM_ClearFlag_CC1(cfg->timer);
671 			LL_TIM_ClearFlag_CC2(cfg->timer);
672 			LL_TIM_ClearFlag_CC3(cfg->timer);
673 			LL_TIM_ClearFlag_CC4(cfg->timer);
674 			cpt->skip_irq--;
675 		}
676 
677 		return;
678 	}
679 
680 	if (LL_TIM_IsActiveFlag_UPDATE(cfg->timer)) {
681 		LL_TIM_ClearFlag_UPDATE(cfg->timer);
682 		if (cfg->four_channel_capture_support &&
683 				cpt->state == CAPTURE_STATE_WAIT_FOR_UPDATE_EVENT) {
684 			/* Special handling of UPDATE event in case it's triggered */
685 			cpt->state = CAPTURE_STATE_WAIT_FOR_PERIOD_END;
686 		} else {
687 			cpt->overflows++;
688 		}
689 	}
690 
691 	if (!cfg->four_channel_capture_support) {
692 		if (is_capture_active[cpt->channel - 1](cfg->timer) ||
693 		    is_capture_active[complimentary_channel[cpt->channel] - 1](cfg->timer)) {
694 			clear_capture_interrupt[cpt->channel - 1](cfg->timer);
695 			clear_capture_interrupt
696 					[complimentary_channel[cpt->channel] - 1](cfg->timer);
697 
698 			cpt->period = get_channel_capture[cpt->channel - 1](cfg->timer);
699 			cpt->pulse = get_channel_capture
700 					[complimentary_channel[cpt->channel] - 1](cfg->timer);
701 		}
702 	} else {
703 		if (cpt->state == CAPTURE_STATE_WAIT_FOR_PULSE_START &&
704 		    is_capture_active[cpt->channel - 1](cfg->timer)) {
705 			/* Reset the counter manually instead of automatically by HW
706 			 * This sets the pulse-start at 0 and makes the pulse-end
707 			 * and period related to that number. Sure we loose some
708 			 * accuracy but it's within acceptable range.
709 			 *
710 			 * This is done through an UPDATE event to also reset
711 			 * the prescalar. This could look like an overflow event
712 			 * and might therefore require special handling.
713 			 */
714 			cpt->state = CAPTURE_STATE_WAIT_FOR_UPDATE_EVENT;
715 			LL_TIM_GenerateEvent_UPDATE(cfg->timer);
716 
717 		} else if ((cpt->state == CAPTURE_STATE_WAIT_FOR_UPDATE_EVENT ||
718 				cpt->state == CAPTURE_STATE_WAIT_FOR_PERIOD_END) &&
719 			    is_capture_active[cpt->channel - 1](cfg->timer)) {
720 			cpt->state = CAPTURE_STATE_IDLE;
721 			/* The end of the period. Both capture channels should now contain
722 			 * the timer value when the pulse and period ended respectively.
723 			 */
724 			cpt->pulse = get_channel_capture[complimentary_channel[cpt->channel] - 1]
725 					(cfg->timer);
726 			cpt->period = get_channel_capture[cpt->channel - 1](cfg->timer);
727 		}
728 
729 		clear_capture_interrupt[cpt->channel - 1](cfg->timer);
730 
731 		if (cpt->state != CAPTURE_STATE_IDLE) {
732 			/* Still waiting for a complete capture */
733 			return;
734 		}
735 	}
736 
737 	if (cpt->overflows) {
738 		LOG_ERR("counter overflow during PWM capture");
739 		status = -ERANGE;
740 	}
741 
742 	if (!cpt->continuous) {
743 		pwm_stm32_disable_capture(dev, cpt->channel);
744 	} else {
745 		cpt->overflows = 0u;
746 		cpt->state = CAPTURE_STATE_WAIT_FOR_PULSE_START;
747 	}
748 
749 	if (cpt->callback != NULL) {
750 		cpt->callback(dev, cpt->channel, cpt->capture_period ? cpt->period : 0u,
751 				cpt->capture_pulse ? cpt->pulse : 0u, status, cpt->user_data);
752 	}
753 }
754 
755 #endif /* CONFIG_PWM_CAPTURE */
756 
pwm_stm32_get_cycles_per_sec(const struct device * dev,uint32_t channel,uint64_t * cycles)757 static int pwm_stm32_get_cycles_per_sec(const struct device *dev,
758 					uint32_t channel, uint64_t *cycles)
759 {
760 	struct pwm_stm32_data *data = dev->data;
761 	const struct pwm_stm32_config *cfg = dev->config;
762 
763 	*cycles = (uint64_t)(data->tim_clk / (cfg->prescaler + 1));
764 
765 	return 0;
766 }
767 
768 static const struct pwm_driver_api pwm_stm32_driver_api = {
769 	.set_cycles = pwm_stm32_set_cycles,
770 	.get_cycles_per_sec = pwm_stm32_get_cycles_per_sec,
771 #ifdef CONFIG_PWM_CAPTURE
772 	.configure_capture = pwm_stm32_configure_capture,
773 	.enable_capture = pwm_stm32_enable_capture,
774 	.disable_capture = pwm_stm32_disable_capture,
775 #endif /* CONFIG_PWM_CAPTURE */
776 };
777 
pwm_stm32_init(const struct device * dev)778 static int pwm_stm32_init(const struct device *dev)
779 {
780 	struct pwm_stm32_data *data = dev->data;
781 	const struct pwm_stm32_config *cfg = dev->config;
782 
783 	int r;
784 	const struct device *clk;
785 	LL_TIM_InitTypeDef init;
786 
787 	/* enable clock and store its speed */
788 	clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
789 
790 	if (!device_is_ready(clk)) {
791 		LOG_ERR("clock control device not ready");
792 		return -ENODEV;
793 	}
794 
795 	r = clock_control_on(clk, (clock_control_subsys_t)&cfg->pclken);
796 	if (r < 0) {
797 		LOG_ERR("Could not initialize clock (%d)", r);
798 		return r;
799 	}
800 
801 	r = get_tim_clk(&cfg->pclken, &data->tim_clk);
802 	if (r < 0) {
803 		LOG_ERR("Could not obtain timer clock (%d)", r);
804 		return r;
805 	}
806 
807 	/* Reset timer to default state using RCC */
808 	(void)reset_line_toggle_dt(&data->reset);
809 
810 	/* configure pinmux */
811 	r = pinctrl_apply_state(cfg->pcfg, PINCTRL_STATE_DEFAULT);
812 	if (r < 0) {
813 		LOG_ERR("PWM pinctrl setup failed (%d)", r);
814 		return r;
815 	}
816 
817 	/* initialize timer */
818 	LL_TIM_StructInit(&init);
819 
820 	init.Prescaler = cfg->prescaler;
821 	init.CounterMode = cfg->countermode;
822 	init.Autoreload = 0u;
823 	init.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
824 
825 	if (LL_TIM_Init(cfg->timer, &init) != SUCCESS) {
826 		LOG_ERR("Could not initialize timer");
827 		return -EIO;
828 	}
829 
830 #if !defined(CONFIG_SOC_SERIES_STM32L0X) && !defined(CONFIG_SOC_SERIES_STM32L1X)
831 	/* enable outputs and counter */
832 	if (IS_TIM_BREAK_INSTANCE(cfg->timer)) {
833 		LL_TIM_EnableAllOutputs(cfg->timer);
834 	}
835 #endif
836 
837 	LL_TIM_EnableCounter(cfg->timer);
838 
839 #ifdef CONFIG_PWM_CAPTURE
840 	cfg->irq_config_func(dev);
841 #endif /* CONFIG_PWM_CAPTURE */
842 
843 	return 0;
844 }
845 
846 #define PWM(index) DT_INST_PARENT(index)
847 
848 #ifdef CONFIG_PWM_CAPTURE
849 #define IRQ_CONNECT_AND_ENABLE_BY_NAME(index, name)				\
850 {										\
851 	IRQ_CONNECT(DT_IRQ_BY_NAME(PWM(index), name, irq),			\
852 			DT_IRQ_BY_NAME(PWM(index), name, priority),		\
853 			pwm_stm32_isr, DEVICE_DT_INST_GET(index), 0);		\
854 	irq_enable(DT_IRQ_BY_NAME(PWM(index), name, irq));			\
855 }
856 
857 #define IRQ_CONNECT_AND_ENABLE_DEFAULT(index)					\
858 {										\
859 	IRQ_CONNECT(DT_IRQN(PWM(index)),					\
860 			DT_IRQ(PWM(index), priority),				\
861 			pwm_stm32_isr, DEVICE_DT_INST_GET(index), 0);		\
862 	irq_enable(DT_IRQN(PWM(index)));					\
863 }
864 
865 #define IRQ_CONFIG_FUNC(index)                                                  \
866 static void pwm_stm32_irq_config_func_##index(const struct device *dev)		\
867 {										\
868 	COND_CODE_1(DT_IRQ_HAS_NAME(PWM(index), cc),				\
869 		(IRQ_CONNECT_AND_ENABLE_BY_NAME(index, cc)),			\
870 		(IRQ_CONNECT_AND_ENABLE_DEFAULT(index))				\
871 	);									\
872 }
873 #define CAPTURE_INIT(index)                                                                        \
874 	.irq_config_func = pwm_stm32_irq_config_func_##index,                                      \
875 	.four_channel_capture_support = DT_INST_PROP(index, four_channel_capture_support)
876 #else
877 #define IRQ_CONFIG_FUNC(index)
878 #define CAPTURE_INIT(index)
879 #endif /* CONFIG_PWM_CAPTURE */
880 
881 #define DT_INST_CLK(index, inst)                                               \
882 	{                                                                      \
883 		.bus = DT_CLOCKS_CELL(PWM(index), bus),				\
884 		.enr = DT_CLOCKS_CELL(PWM(index), bits)				\
885 	}
886 
887 
888 #define PWM_DEVICE_INIT(index)                                                 \
889 	static struct pwm_stm32_data pwm_stm32_data_##index = {		       \
890 		.reset = RESET_DT_SPEC_GET(PWM(index)),			       \
891 	};								       \
892 									       \
893 	IRQ_CONFIG_FUNC(index)						       \
894 									       \
895 	PINCTRL_DT_INST_DEFINE(index);					       \
896 									       \
897 	static const struct pwm_stm32_config pwm_stm32_config_##index = {      \
898 		.timer = (TIM_TypeDef *)DT_REG_ADDR(PWM(index)),	       \
899 		.prescaler = DT_PROP(PWM(index), st_prescaler),		       \
900 		.countermode = DT_PROP(PWM(index), st_countermode),	       \
901 		.pclken = DT_INST_CLK(index, timer),                           \
902 		.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(index),		       \
903 		CAPTURE_INIT(index)					       \
904 	};                                                                     \
905 									       \
906 	DEVICE_DT_INST_DEFINE(index, &pwm_stm32_init, NULL,                    \
907 			    &pwm_stm32_data_##index,                           \
908 			    &pwm_stm32_config_##index, POST_KERNEL,            \
909 			    CONFIG_PWM_INIT_PRIORITY,                          \
910 			    &pwm_stm32_driver_api);
911 
912 DT_INST_FOREACH_STATUS_OKAY(PWM_DEVICE_INIT)
913