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