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