Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux
1
fork

Configure Feed

Select the types of activity you want to include in your feed.

Merge tag 'pwm/for-6.19-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/ukleinek/linux

Pull pwm updates from Uwe Kleine-König:
"In addition to the usual mix of core cleanups, driver changes, minor
fixes and device tree updates the highlight this cycle is Rust support
for the core and a first Rust driver both provided by Michal
Wilczynski.

Michal wrote about these changes on

https://mwilczynski.dev/posts/bringing-rust-to-the-pwm-subsystem/

which is a nice read"

* tag 'pwm/for-6.19-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/ukleinek/linux: (22 commits)
pwm: rzg2l-gpt: Allow checking period_tick cache value only if sibling channel is enabled
pwm: bcm2835: Make sure the channel is enabled after pwm_request()
pwm: mediatek: Make use of struct_size macro
pwm: mediatek: Remove unneeded semicolon
pwm: airoha: Add support for EN7581 SoC
pwm: mediatek: Convert to waveform API
pwm: max7360: Clean MAX7360 code
pwm: Drop unused function pwm_apply_args()
pwm: Use %u to printf unsigned int pwm_chip::npwm and pwm_chip::id
pwm: Simplify printf to emit chip->npwm in $debugfs/pwm
pwm: th1520: Use module_pwm_platform_driver! macro
pwm: th1520: Fix clippy warning for redundant struct field init
pwm: Fix Rust formatting
dt-bindings: pwm: thead: Add T-HEAD TH1520 PWM controller
pwm: Add Rust driver for T-HEAD TH1520 SoC
rust: pwm: Fix broken intra-doc link
rust: pwm: Drop wrapping of PWM polarity and state
rust: pwm: Add module_pwm_platform_driver! macro
rust: pwm: Add complete abstraction layer
rust: pwm: Add Kconfig and basic data structures
...

+2096 -200
+48
Documentation/devicetree/bindings/pwm/thead,th1520-pwm.yaml
··· 1 + # SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) 2 + %YAML 1.2 3 + --- 4 + $id: http://devicetree.org/schemas/pwm/thead,th1520-pwm.yaml# 5 + $schema: http://devicetree.org/meta-schemas/core.yaml# 6 + 7 + title: T-HEAD TH1520 PWM controller 8 + 9 + maintainers: 10 + - Michal Wilczynski <m.wilczynski@samsung.com> 11 + 12 + allOf: 13 + - $ref: pwm.yaml# 14 + 15 + properties: 16 + compatible: 17 + const: thead,th1520-pwm 18 + 19 + reg: 20 + maxItems: 1 21 + 22 + clocks: 23 + items: 24 + - description: SoC PWM clock 25 + 26 + "#pwm-cells": 27 + const: 3 28 + 29 + required: 30 + - compatible 31 + - reg 32 + - clocks 33 + 34 + unevaluatedProperties: false 35 + 36 + examples: 37 + - | 38 + #include <dt-bindings/clock/thead,th1520-clk-ap.h> 39 + soc { 40 + #address-cells = <2>; 41 + #size-cells = <2>; 42 + pwm@ffec01c000 { 43 + compatible = "thead,th1520-pwm"; 44 + reg = <0xff 0xec01c000 0x0 0x4000>; 45 + clocks = <&clk CLK_PWM>; 46 + #pwm-cells = <3>; 47 + }; 48 + };
+10
MAINTAINERS
··· 20871 20871 F: include/linux/pwm_backlight.h 20872 20872 K: pwm_(config|apply_might_sleep|apply_atomic|ops) 20873 20873 20874 + PWM SUBSYSTEM BINDINGS [RUST] 20875 + M: Michal Wilczynski <m.wilczynski@samsung.com> 20876 + L: linux-pwm@vger.kernel.org 20877 + L: rust-for-linux@vger.kernel.org 20878 + S: Maintained 20879 + F: rust/helpers/pwm.c 20880 + F: rust/kernel/pwm.rs 20881 + 20874 20882 PXA GPIO DRIVER 20875 20883 M: Robert Jarzmik <robert.jarzmik@free.fr> 20876 20884 L: linux-gpio@vger.kernel.org ··· 22301 22293 F: Documentation/devicetree/bindings/mailbox/thead,th1520-mbox.yaml 22302 22294 F: Documentation/devicetree/bindings/net/thead,th1520-gmac.yaml 22303 22295 F: Documentation/devicetree/bindings/pinctrl/thead,th1520-pinctrl.yaml 22296 + F: Documentation/devicetree/bindings/pwm/thead,th1520-pwm.yaml 22304 22297 F: Documentation/devicetree/bindings/reset/thead,th1520-reset.yaml 22305 22298 F: arch/riscv/boot/dts/thead/ 22306 22299 F: drivers/clk/thead/clk-th1520-ap.c ··· 22312 22303 F: drivers/pmdomain/thead/ 22313 22304 F: drivers/power/reset/th1520-aon-reboot.c 22314 22305 F: drivers/power/sequencing/pwrseq-thead-gpu.c 22306 + F: drivers/pwm/pwm_th1520.rs 22315 22307 F: drivers/reset/reset-th1520.c 22316 22308 F: include/dt-bindings/clock/thead,th1520-clk-ap.h 22317 22309 F: include/dt-bindings/power/thead,th1520-power.h
+33
drivers/pwm/Kconfig
··· 63 63 This option enables support for the PWM function found in the Analog 64 64 Devices ADP5585. 65 65 66 + config PWM_AIROHA 67 + tristate "Airoha PWM support" 68 + depends on ARCH_AIROHA || COMPILE_TEST 69 + select REGMAP_MMIO 70 + help 71 + Generic PWM framework driver for Airoha SoC. 72 + 73 + To compile this driver as a module, choose M here: the module 74 + will be called pwm-airoha. 75 + 66 76 config PWM_APPLE 67 77 tristate "Apple SoC PWM support" 68 78 depends on ARCH_APPLE || COMPILE_TEST ··· 758 748 To compile this driver as a module, choose M here: the module 759 749 will be called pwm-tegra. 760 750 751 + config PWM_TH1520 752 + tristate "TH1520 PWM support" 753 + depends on RUST 754 + select RUST_PWM_ABSTRACTIONS 755 + help 756 + This option enables the driver for the PWM controller found on the 757 + T-HEAD TH1520 SoC. 758 + 759 + To compile this driver as a module, choose M here; the module 760 + will be called pwm-th1520. If you are unsure, say N. 761 + 761 762 config PWM_TIECAP 762 763 tristate "ECAP PWM support" 763 764 depends on ARCH_OMAP2PLUS || ARCH_DAVINCI_DA8XX || ARCH_KEYSTONE || ARCH_K3 || COMPILE_TEST ··· 839 818 840 819 To compile this driver as a module, choose M here: the module 841 820 will be called pwm-xilinx. 821 + 822 + config RUST_PWM_ABSTRACTIONS 823 + bool 824 + depends on RUST 825 + help 826 + This option enables the safe Rust abstraction layer for the PWM 827 + subsystem. It provides idiomatic wrappers and traits necessary for 828 + writing PWM controller drivers in Rust. 829 + 830 + The abstractions handle resource management (like memory and reference 831 + counting) and provide safe interfaces to the underlying C core, 832 + allowing driver logic to be written in safe Rust. 842 833 843 834 endif
+2
drivers/pwm/Makefile
··· 2 2 obj-$(CONFIG_PWM) += core.o 3 3 obj-$(CONFIG_PWM_AB8500) += pwm-ab8500.o 4 4 obj-$(CONFIG_PWM_ADP5585) += pwm-adp5585.o 5 + obj-$(CONFIG_PWM_AIROHA) += pwm-airoha.o 5 6 obj-$(CONFIG_PWM_APPLE) += pwm-apple.o 6 7 obj-$(CONFIG_PWM_ARGON_FAN_HAT) += pwm-argon-fan-hat.o 7 8 obj-$(CONFIG_PWM_ATMEL) += pwm-atmel.o ··· 69 68 obj-$(CONFIG_PWM_SUN4I) += pwm-sun4i.o 70 69 obj-$(CONFIG_PWM_SUNPLUS) += pwm-sunplus.o 71 70 obj-$(CONFIG_PWM_TEGRA) += pwm-tegra.o 71 + obj-$(CONFIG_PWM_TH1520) += pwm_th1520.o 72 72 obj-$(CONFIG_PWM_TIECAP) += pwm-tiecap.o 73 73 obj-$(CONFIG_PWM_TIEHRPWM) += pwm-tiehrpwm.o 74 74 obj-$(CONFIG_PWM_TWL) += pwm-twl.o
+4 -4
drivers/pwm/core.c
··· 1608 1608 } 1609 1609 EXPORT_SYMBOL_GPL(pwmchip_put); 1610 1610 1611 - static void pwmchip_release(struct device *pwmchip_dev) 1611 + void pwmchip_release(struct device *pwmchip_dev) 1612 1612 { 1613 1613 struct pwm_chip *chip = pwmchip_from_dev(pwmchip_dev); 1614 1614 1615 1615 kfree(chip); 1616 1616 } 1617 + EXPORT_SYMBOL_GPL(pwmchip_release); 1617 1618 1618 1619 struct pwm_chip *pwmchip_alloc(struct device *parent, unsigned int npwm, size_t sizeof_priv) 1619 1620 { ··· 2697 2696 { 2698 2697 struct pwm_chip *chip = v; 2699 2698 2700 - seq_printf(s, "%s%d: %s/%s, %d PWM device%s\n", 2699 + seq_printf(s, "%s%u: %s/%s, npwm: %u\n", 2701 2700 (char *)s->private, chip->id, 2702 2701 pwmchip_parent(chip)->bus ? pwmchip_parent(chip)->bus->name : "no-bus", 2703 - dev_name(pwmchip_parent(chip)), chip->npwm, 2704 - (chip->npwm != 1) ? "s" : ""); 2702 + dev_name(pwmchip_parent(chip)), chip->npwm); 2705 2703 2706 2704 pwm_dbg_show(chip, s); 2707 2705
+622
drivers/pwm/pwm-airoha.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright 2022 Markus Gothe <markus.gothe@genexis.eu> 4 + * Copyright 2025 Christian Marangi <ansuelsmth@gmail.com> 5 + * 6 + * Limitations: 7 + * - Only 8 concurrent waveform generators are available for 8 combinations of 8 + * duty_cycle and period. Waveform generators are shared between 16 GPIO 9 + * pins and 17 SIPO GPIO pins. 10 + * - Supports only normal polarity. 11 + * - On configuration the currently running period is completed. 12 + * - Minimum supported period is 4 ms 13 + * - Maximum supported period is 1s 14 + */ 15 + 16 + #include <linux/array_size.h> 17 + #include <linux/bitfield.h> 18 + #include <linux/bitmap.h> 19 + #include <linux/err.h> 20 + #include <linux/io.h> 21 + #include <linux/iopoll.h> 22 + #include <linux/math64.h> 23 + #include <linux/mfd/syscon.h> 24 + #include <linux/module.h> 25 + #include <linux/mod_devicetable.h> 26 + #include <linux/platform_device.h> 27 + #include <linux/pwm.h> 28 + #include <linux/regmap.h> 29 + #include <linux/types.h> 30 + 31 + #define AIROHA_PWM_REG_SGPIO_LED_DATA 0x0024 32 + #define AIROHA_PWM_SGPIO_LED_DATA_SHIFT_FLAG BIT(31) 33 + #define AIROHA_PWM_SGPIO_LED_DATA_DATA GENMASK(16, 0) 34 + 35 + #define AIROHA_PWM_REG_SGPIO_CLK_DIVR 0x0028 36 + #define AIROHA_PWM_SGPIO_CLK_DIVR GENMASK(1, 0) 37 + #define AIROHA_PWM_SGPIO_CLK_DIVR_32 FIELD_PREP_CONST(AIROHA_PWM_SGPIO_CLK_DIVR, 3) 38 + #define AIROHA_PWM_SGPIO_CLK_DIVR_16 FIELD_PREP_CONST(AIROHA_PWM_SGPIO_CLK_DIVR, 2) 39 + #define AIROHA_PWM_SGPIO_CLK_DIVR_8 FIELD_PREP_CONST(AIROHA_PWM_SGPIO_CLK_DIVR, 1) 40 + #define AIROHA_PWM_SGPIO_CLK_DIVR_4 FIELD_PREP_CONST(AIROHA_PWM_SGPIO_CLK_DIVR, 0) 41 + 42 + #define AIROHA_PWM_REG_SGPIO_CLK_DLY 0x002c 43 + 44 + #define AIROHA_PWM_REG_SIPO_FLASH_MODE_CFG 0x0030 45 + #define AIROHA_PWM_SERIAL_GPIO_FLASH_MODE BIT(1) 46 + #define AIROHA_PWM_SERIAL_GPIO_MODE_74HC164 BIT(0) 47 + 48 + #define AIROHA_PWM_REG_GPIO_FLASH_PRD_SET(_n) (0x003c + (4 * (_n))) 49 + #define AIROHA_PWM_REG_GPIO_FLASH_PRD_SHIFT(_n) (16 * (_n)) 50 + #define AIROHA_PWM_GPIO_FLASH_PRD_LOW GENMASK(15, 8) 51 + #define AIROHA_PWM_GPIO_FLASH_PRD_HIGH GENMASK(7, 0) 52 + 53 + #define AIROHA_PWM_REG_GPIO_FLASH_MAP(_n) (0x004c + (4 * (_n))) 54 + #define AIROHA_PWM_REG_GPIO_FLASH_MAP_SHIFT(_n) (4 * (_n)) 55 + #define AIROHA_PWM_GPIO_FLASH_EN BIT(3) 56 + #define AIROHA_PWM_GPIO_FLASH_SET_ID GENMASK(2, 0) 57 + 58 + /* Register map is equal to GPIO flash map */ 59 + #define AIROHA_PWM_REG_SIPO_FLASH_MAP(_n) (0x0054 + (4 * (_n))) 60 + 61 + #define AIROHA_PWM_REG_CYCLE_CFG_VALUE(_n) (0x0098 + (4 * (_n))) 62 + #define AIROHA_PWM_REG_CYCLE_CFG_SHIFT(_n) (8 * (_n)) 63 + #define AIROHA_PWM_WAVE_GEN_CYCLE GENMASK(7, 0) 64 + 65 + /* GPIO/SIPO flash map handles 8 pins in one register */ 66 + #define AIROHA_PWM_PINS_PER_FLASH_MAP 8 67 + /* Cycle(Period) registers handles 4 generators in one 32-bit register */ 68 + #define AIROHA_PWM_BUCKET_PER_CYCLE_CFG 4 69 + /* Flash(Duty) producer handles 2 generators in one 32-bit register */ 70 + #define AIROHA_PWM_BUCKET_PER_FLASH_PROD 2 71 + 72 + #define AIROHA_PWM_NUM_BUCKETS 8 73 + /* 74 + * The first 16 GPIO pins, GPIO0-GPIO15, are mapped into 16 PWM channels, 0-15. 75 + * The SIPO GPIO pins are 17 pins which are mapped into 17 PWM channels, 16-32. 76 + * However, we've only got 8 concurrent waveform generators and can therefore 77 + * only use up to 8 different combinations of duty cycle and period at a time. 78 + */ 79 + #define AIROHA_PWM_NUM_GPIO 16 80 + #define AIROHA_PWM_NUM_SIPO 17 81 + #define AIROHA_PWM_MAX_CHANNELS (AIROHA_PWM_NUM_GPIO + AIROHA_PWM_NUM_SIPO) 82 + 83 + struct airoha_pwm_bucket { 84 + /* Concurrent access protected by PWM core */ 85 + int used; 86 + u32 period_ticks; 87 + u32 duty_ticks; 88 + }; 89 + 90 + struct airoha_pwm { 91 + struct regmap *regmap; 92 + 93 + DECLARE_BITMAP(initialized, AIROHA_PWM_MAX_CHANNELS); 94 + 95 + struct airoha_pwm_bucket buckets[AIROHA_PWM_NUM_BUCKETS]; 96 + 97 + /* Cache bucket used by each pwm channel */ 98 + u8 channel_bucket[AIROHA_PWM_MAX_CHANNELS]; 99 + }; 100 + 101 + /* The PWM hardware supports periods between 4 ms and 1 s */ 102 + #define AIROHA_PWM_PERIOD_TICK_NS (4 * NSEC_PER_MSEC) 103 + #define AIROHA_PWM_PERIOD_MAX_NS (1 * NSEC_PER_SEC) 104 + /* It is represented internally as 1/250 s between 1 and 250. Unit is ticks. */ 105 + #define AIROHA_PWM_PERIOD_MIN 1 106 + #define AIROHA_PWM_PERIOD_MAX 250 107 + /* Duty cycle is relative with 255 corresponding to 100% */ 108 + #define AIROHA_PWM_DUTY_FULL 255 109 + 110 + static void airoha_pwm_get_flash_map_addr_and_shift(unsigned int hwpwm, 111 + u32 *addr, u32 *shift) 112 + { 113 + unsigned int offset, hwpwm_bit; 114 + 115 + if (hwpwm >= AIROHA_PWM_NUM_GPIO) { 116 + unsigned int sipohwpwm = hwpwm - AIROHA_PWM_NUM_GPIO; 117 + 118 + offset = sipohwpwm / AIROHA_PWM_PINS_PER_FLASH_MAP; 119 + hwpwm_bit = sipohwpwm % AIROHA_PWM_PINS_PER_FLASH_MAP; 120 + 121 + /* One FLASH_MAP register handles 8 pins */ 122 + *shift = AIROHA_PWM_REG_GPIO_FLASH_MAP_SHIFT(hwpwm_bit); 123 + *addr = AIROHA_PWM_REG_SIPO_FLASH_MAP(offset); 124 + } else { 125 + offset = hwpwm / AIROHA_PWM_PINS_PER_FLASH_MAP; 126 + hwpwm_bit = hwpwm % AIROHA_PWM_PINS_PER_FLASH_MAP; 127 + 128 + /* One FLASH_MAP register handles 8 pins */ 129 + *shift = AIROHA_PWM_REG_GPIO_FLASH_MAP_SHIFT(hwpwm_bit); 130 + *addr = AIROHA_PWM_REG_GPIO_FLASH_MAP(offset); 131 + } 132 + } 133 + 134 + static u32 airoha_pwm_get_period_ticks_from_ns(u32 period_ns) 135 + { 136 + return period_ns / AIROHA_PWM_PERIOD_TICK_NS; 137 + } 138 + 139 + static u32 airoha_pwm_get_duty_ticks_from_ns(u32 period_ns, u32 duty_ns) 140 + { 141 + return mul_u64_u32_div(duty_ns, AIROHA_PWM_DUTY_FULL, period_ns); 142 + } 143 + 144 + static u32 airoha_pwm_get_period_ns_from_ticks(u32 period_tick) 145 + { 146 + return period_tick * AIROHA_PWM_PERIOD_TICK_NS; 147 + } 148 + 149 + static u32 airoha_pwm_get_duty_ns_from_ticks(u32 period_tick, u32 duty_tick) 150 + { 151 + u32 period_ns = period_tick * AIROHA_PWM_PERIOD_TICK_NS; 152 + 153 + /* 154 + * Overflow can't occur in multiplication as duty_tick is just 8 bit 155 + * and period_ns is clamped to AIROHA_PWM_PERIOD_MAX_NS and fit in a 156 + * u64. 157 + */ 158 + return DIV_U64_ROUND_UP(duty_tick * period_ns, AIROHA_PWM_DUTY_FULL); 159 + } 160 + 161 + static int airoha_pwm_get_bucket(struct airoha_pwm *pc, int bucket, 162 + u64 *period_ns, u64 *duty_ns) 163 + { 164 + struct regmap *map = pc->regmap; 165 + u32 period_tick, duty_tick; 166 + unsigned int offset; 167 + u32 shift, val; 168 + int ret; 169 + 170 + offset = bucket / AIROHA_PWM_BUCKET_PER_CYCLE_CFG; 171 + shift = bucket % AIROHA_PWM_BUCKET_PER_CYCLE_CFG; 172 + shift = AIROHA_PWM_REG_CYCLE_CFG_SHIFT(shift); 173 + 174 + ret = regmap_read(map, AIROHA_PWM_REG_CYCLE_CFG_VALUE(offset), &val); 175 + if (ret) 176 + return ret; 177 + 178 + period_tick = FIELD_GET(AIROHA_PWM_WAVE_GEN_CYCLE, val >> shift); 179 + *period_ns = airoha_pwm_get_period_ns_from_ticks(period_tick); 180 + 181 + offset = bucket / AIROHA_PWM_BUCKET_PER_FLASH_PROD; 182 + shift = bucket % AIROHA_PWM_BUCKET_PER_FLASH_PROD; 183 + shift = AIROHA_PWM_REG_GPIO_FLASH_PRD_SHIFT(shift); 184 + 185 + ret = regmap_read(map, AIROHA_PWM_REG_GPIO_FLASH_PRD_SET(offset), 186 + &val); 187 + if (ret) 188 + return ret; 189 + 190 + duty_tick = FIELD_GET(AIROHA_PWM_GPIO_FLASH_PRD_HIGH, val >> shift); 191 + *duty_ns = airoha_pwm_get_duty_ns_from_ticks(period_tick, duty_tick); 192 + 193 + return 0; 194 + } 195 + 196 + static int airoha_pwm_get_generator(struct airoha_pwm *pc, u32 duty_ticks, 197 + u32 period_ticks) 198 + { 199 + int best = -ENOENT, unused = -ENOENT; 200 + u32 duty_ns, best_duty_ns = 0; 201 + u32 best_period_ticks = 0; 202 + unsigned int i; 203 + 204 + duty_ns = airoha_pwm_get_duty_ns_from_ticks(period_ticks, duty_ticks); 205 + 206 + for (i = 0; i < ARRAY_SIZE(pc->buckets); i++) { 207 + struct airoha_pwm_bucket *bucket = &pc->buckets[i]; 208 + u32 bucket_period_ticks = bucket->period_ticks; 209 + u32 bucket_duty_ticks = bucket->duty_ticks; 210 + 211 + /* If found, save an unused bucket to return it later */ 212 + if (!bucket->used) { 213 + unused = i; 214 + continue; 215 + } 216 + 217 + /* We found a matching bucket, exit early */ 218 + if (duty_ticks == bucket_duty_ticks && 219 + period_ticks == bucket_period_ticks) 220 + return i; 221 + 222 + /* 223 + * Unlike duty cycle zero, which can be handled by 224 + * disabling PWM, a generator is needed for full duty 225 + * cycle but it can be reused regardless of period 226 + */ 227 + if (duty_ticks == AIROHA_PWM_DUTY_FULL && 228 + bucket_duty_ticks == AIROHA_PWM_DUTY_FULL) 229 + return i; 230 + 231 + /* 232 + * With an unused bucket available, skip searching for 233 + * a bucket to recycle (closer to the requested period/duty) 234 + */ 235 + if (unused >= 0) 236 + continue; 237 + 238 + /* Ignore bucket with invalid period */ 239 + if (bucket_period_ticks > period_ticks) 240 + continue; 241 + 242 + /* 243 + * Search for a bucket closer to the requested period 244 + * that has the maximal possible period that isn't bigger 245 + * than the requested period. For that period pick the maximal 246 + * duty cycle that isn't bigger than the requested duty_cycle. 247 + */ 248 + if (bucket_period_ticks >= best_period_ticks) { 249 + u32 bucket_duty_ns = airoha_pwm_get_duty_ns_from_ticks(bucket_period_ticks, 250 + bucket_duty_ticks); 251 + 252 + /* Skip bucket that goes over the requested duty */ 253 + if (bucket_duty_ns > duty_ns) 254 + continue; 255 + 256 + if (bucket_duty_ns > best_duty_ns) { 257 + best_period_ticks = bucket_period_ticks; 258 + best_duty_ns = bucket_duty_ns; 259 + best = i; 260 + } 261 + } 262 + } 263 + 264 + /* Return an unused bucket or the best one found (if ever) */ 265 + return unused >= 0 ? unused : best; 266 + } 267 + 268 + static void airoha_pwm_release_bucket_config(struct airoha_pwm *pc, 269 + unsigned int hwpwm) 270 + { 271 + int bucket; 272 + 273 + /* Nothing to clear, PWM channel never used */ 274 + if (!test_bit(hwpwm, pc->initialized)) 275 + return; 276 + 277 + bucket = pc->channel_bucket[hwpwm]; 278 + pc->buckets[bucket].used--; 279 + } 280 + 281 + static int airoha_pwm_apply_bucket_config(struct airoha_pwm *pc, unsigned int bucket, 282 + u32 duty_ticks, u32 period_ticks) 283 + { 284 + u32 mask, shift, val; 285 + u32 offset; 286 + int ret; 287 + 288 + offset = bucket / AIROHA_PWM_BUCKET_PER_CYCLE_CFG; 289 + shift = bucket % AIROHA_PWM_BUCKET_PER_CYCLE_CFG; 290 + shift = AIROHA_PWM_REG_CYCLE_CFG_SHIFT(shift); 291 + 292 + /* Configure frequency divisor */ 293 + mask = AIROHA_PWM_WAVE_GEN_CYCLE << shift; 294 + val = FIELD_PREP(AIROHA_PWM_WAVE_GEN_CYCLE, period_ticks) << shift; 295 + ret = regmap_update_bits(pc->regmap, AIROHA_PWM_REG_CYCLE_CFG_VALUE(offset), 296 + mask, val); 297 + if (ret) 298 + return ret; 299 + 300 + offset = bucket / AIROHA_PWM_BUCKET_PER_FLASH_PROD; 301 + shift = bucket % AIROHA_PWM_BUCKET_PER_FLASH_PROD; 302 + shift = AIROHA_PWM_REG_GPIO_FLASH_PRD_SHIFT(shift); 303 + 304 + /* Configure duty cycle */ 305 + mask = AIROHA_PWM_GPIO_FLASH_PRD_HIGH << shift; 306 + val = FIELD_PREP(AIROHA_PWM_GPIO_FLASH_PRD_HIGH, duty_ticks) << shift; 307 + ret = regmap_update_bits(pc->regmap, AIROHA_PWM_REG_GPIO_FLASH_PRD_SET(offset), 308 + mask, val); 309 + if (ret) 310 + return ret; 311 + 312 + mask = AIROHA_PWM_GPIO_FLASH_PRD_LOW << shift; 313 + val = FIELD_PREP(AIROHA_PWM_GPIO_FLASH_PRD_LOW, 314 + AIROHA_PWM_DUTY_FULL - duty_ticks) << shift; 315 + return regmap_update_bits(pc->regmap, AIROHA_PWM_REG_GPIO_FLASH_PRD_SET(offset), 316 + mask, val); 317 + } 318 + 319 + static int airoha_pwm_consume_generator(struct airoha_pwm *pc, 320 + u32 duty_ticks, u32 period_ticks, 321 + unsigned int hwpwm) 322 + { 323 + bool config_bucket = false; 324 + int bucket, ret; 325 + 326 + /* 327 + * Search for a bucket that already satisfies duty and period 328 + * or an unused one. 329 + * If not found, -ENOENT is returned. 330 + */ 331 + bucket = airoha_pwm_get_generator(pc, duty_ticks, period_ticks); 332 + if (bucket < 0) 333 + return bucket; 334 + 335 + /* Release previous used bucket (if any) */ 336 + airoha_pwm_release_bucket_config(pc, hwpwm); 337 + 338 + if (!pc->buckets[bucket].used) 339 + config_bucket = true; 340 + pc->buckets[bucket].used++; 341 + 342 + if (config_bucket) { 343 + pc->buckets[bucket].period_ticks = period_ticks; 344 + pc->buckets[bucket].duty_ticks = duty_ticks; 345 + ret = airoha_pwm_apply_bucket_config(pc, bucket, 346 + duty_ticks, 347 + period_ticks); 348 + if (ret) { 349 + pc->buckets[bucket].used--; 350 + return ret; 351 + } 352 + } 353 + 354 + return bucket; 355 + } 356 + 357 + static int airoha_pwm_sipo_init(struct airoha_pwm *pc) 358 + { 359 + u32 val; 360 + int ret; 361 + 362 + ret = regmap_clear_bits(pc->regmap, AIROHA_PWM_REG_SIPO_FLASH_MODE_CFG, 363 + AIROHA_PWM_SERIAL_GPIO_MODE_74HC164); 364 + if (ret) 365 + return ret; 366 + 367 + /* Configure shift register chip clock timings, use 32x divisor */ 368 + ret = regmap_write(pc->regmap, AIROHA_PWM_REG_SGPIO_CLK_DIVR, 369 + AIROHA_PWM_SGPIO_CLK_DIVR_32); 370 + if (ret) 371 + return ret; 372 + 373 + /* 374 + * Configure the shift register chip clock delay. This needs 375 + * to be configured based on the chip characteristics when the SoC 376 + * apply the shift register configuration. 377 + * This doesn't affect actual PWM operation and is only specific to 378 + * the shift register chip. 379 + * 380 + * For 74HC164 we set it to 0. 381 + * 382 + * For reference, the actual delay applied is the internal clock 383 + * feed to the SGPIO chip + 1. 384 + * 385 + * From documentation is specified that clock delay should not be 386 + * greater than (AIROHA_PWM_REG_SGPIO_CLK_DIVR / 2) - 1. 387 + */ 388 + ret = regmap_write(pc->regmap, AIROHA_PWM_REG_SGPIO_CLK_DLY, 0); 389 + if (ret) 390 + return ret; 391 + 392 + /* 393 + * It is necessary to explicitly shift out all zeros after muxing 394 + * to initialize the shift register before enabling PWM 395 + * mode because in PWM mode SIPO will not start shifting until 396 + * it needs to output a non-zero value (bit 31 of led_data 397 + * indicates shifting in progress and it must return to zero 398 + * before led_data can be written or PWM mode can be set). 399 + */ 400 + ret = regmap_read_poll_timeout(pc->regmap, AIROHA_PWM_REG_SGPIO_LED_DATA, val, 401 + !(val & AIROHA_PWM_SGPIO_LED_DATA_SHIFT_FLAG), 402 + 10, 200 * USEC_PER_MSEC); 403 + if (ret) 404 + return ret; 405 + 406 + ret = regmap_clear_bits(pc->regmap, AIROHA_PWM_REG_SGPIO_LED_DATA, 407 + AIROHA_PWM_SGPIO_LED_DATA_DATA); 408 + if (ret) 409 + return ret; 410 + ret = regmap_read_poll_timeout(pc->regmap, AIROHA_PWM_REG_SGPIO_LED_DATA, val, 411 + !(val & AIROHA_PWM_SGPIO_LED_DATA_SHIFT_FLAG), 412 + 10, 200 * USEC_PER_MSEC); 413 + if (ret) 414 + return ret; 415 + 416 + /* Set SIPO in PWM mode */ 417 + return regmap_set_bits(pc->regmap, AIROHA_PWM_REG_SIPO_FLASH_MODE_CFG, 418 + AIROHA_PWM_SERIAL_GPIO_FLASH_MODE); 419 + } 420 + 421 + static int airoha_pwm_config_flash_map(struct airoha_pwm *pc, 422 + unsigned int hwpwm, int index) 423 + { 424 + unsigned int addr; 425 + u32 shift; 426 + int ret; 427 + 428 + airoha_pwm_get_flash_map_addr_and_shift(hwpwm, &addr, &shift); 429 + 430 + /* negative index means disable PWM channel */ 431 + if (index < 0) { 432 + /* 433 + * If we need to disable the PWM, we just put low the 434 + * GPIO. No need to setup buckets. 435 + */ 436 + return regmap_clear_bits(pc->regmap, addr, 437 + AIROHA_PWM_GPIO_FLASH_EN << shift); 438 + } 439 + 440 + ret = regmap_update_bits(pc->regmap, addr, 441 + AIROHA_PWM_GPIO_FLASH_SET_ID << shift, 442 + FIELD_PREP(AIROHA_PWM_GPIO_FLASH_SET_ID, index) << shift); 443 + if (ret) 444 + return ret; 445 + 446 + return regmap_set_bits(pc->regmap, addr, AIROHA_PWM_GPIO_FLASH_EN << shift); 447 + } 448 + 449 + static int airoha_pwm_config(struct airoha_pwm *pc, struct pwm_device *pwm, 450 + u32 period_ticks, u32 duty_ticks) 451 + { 452 + unsigned int hwpwm = pwm->hwpwm; 453 + int bucket, ret; 454 + 455 + bucket = airoha_pwm_consume_generator(pc, duty_ticks, period_ticks, 456 + hwpwm); 457 + if (bucket < 0) 458 + return bucket; 459 + 460 + ret = airoha_pwm_config_flash_map(pc, hwpwm, bucket); 461 + if (ret) { 462 + pc->buckets[bucket].used--; 463 + return ret; 464 + } 465 + 466 + __set_bit(hwpwm, pc->initialized); 467 + pc->channel_bucket[hwpwm] = bucket; 468 + 469 + /* 470 + * SIPO are special GPIO attached to a shift register chip. The handling 471 + * of this chip is internal to the SoC that takes care of applying the 472 + * values based on the flash map. To apply a new flash map, it's needed 473 + * to trigger a refresh on the shift register chip. 474 + * If a SIPO is getting configuring , always reinit the shift register 475 + * chip to make sure the correct flash map is applied. 476 + * Skip reconfiguring the shift register if the related hwpwm 477 + * is disabled (as it doesn't need to be mapped). 478 + */ 479 + if (hwpwm >= AIROHA_PWM_NUM_GPIO) { 480 + ret = airoha_pwm_sipo_init(pc); 481 + if (ret) { 482 + airoha_pwm_release_bucket_config(pc, hwpwm); 483 + return ret; 484 + } 485 + } 486 + 487 + return 0; 488 + } 489 + 490 + static void airoha_pwm_disable(struct airoha_pwm *pc, struct pwm_device *pwm) 491 + { 492 + /* Disable PWM and release the bucket */ 493 + airoha_pwm_config_flash_map(pc, pwm->hwpwm, -1); 494 + airoha_pwm_release_bucket_config(pc, pwm->hwpwm); 495 + 496 + __clear_bit(pwm->hwpwm, pc->initialized); 497 + 498 + /* If no SIPO is used, disable the shift register chip */ 499 + if (!bitmap_read(pc->initialized, 500 + AIROHA_PWM_NUM_GPIO, AIROHA_PWM_NUM_SIPO)) 501 + regmap_clear_bits(pc->regmap, AIROHA_PWM_REG_SIPO_FLASH_MODE_CFG, 502 + AIROHA_PWM_SERIAL_GPIO_FLASH_MODE); 503 + } 504 + 505 + static int airoha_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm, 506 + const struct pwm_state *state) 507 + { 508 + struct airoha_pwm *pc = pwmchip_get_drvdata(chip); 509 + u32 period_ticks, duty_ticks; 510 + u32 period_ns, duty_ns; 511 + 512 + if (!state->enabled) { 513 + airoha_pwm_disable(pc, pwm); 514 + return 0; 515 + } 516 + 517 + /* Only normal polarity is supported */ 518 + if (state->polarity == PWM_POLARITY_INVERSED) 519 + return -EINVAL; 520 + 521 + /* Exit early if period is less than minimum supported */ 522 + if (state->period < AIROHA_PWM_PERIOD_TICK_NS) 523 + return -EINVAL; 524 + 525 + /* Clamp period to MAX supported value */ 526 + if (state->period > AIROHA_PWM_PERIOD_MAX_NS) 527 + period_ns = AIROHA_PWM_PERIOD_MAX_NS; 528 + else 529 + period_ns = state->period; 530 + 531 + /* Validate duty to configured period */ 532 + if (state->duty_cycle > period_ns) 533 + duty_ns = period_ns; 534 + else 535 + duty_ns = state->duty_cycle; 536 + 537 + /* Convert period ns to ticks */ 538 + period_ticks = airoha_pwm_get_period_ticks_from_ns(period_ns); 539 + /* Convert period ticks to ns again for cosistent duty tick calculation */ 540 + period_ns = airoha_pwm_get_period_ns_from_ticks(period_ticks); 541 + duty_ticks = airoha_pwm_get_duty_ticks_from_ns(period_ns, duty_ns); 542 + 543 + return airoha_pwm_config(pc, pwm, period_ticks, duty_ticks); 544 + } 545 + 546 + static int airoha_pwm_get_state(struct pwm_chip *chip, struct pwm_device *pwm, 547 + struct pwm_state *state) 548 + { 549 + struct airoha_pwm *pc = pwmchip_get_drvdata(chip); 550 + int ret, hwpwm = pwm->hwpwm; 551 + u32 addr, shift, val; 552 + u8 bucket; 553 + 554 + airoha_pwm_get_flash_map_addr_and_shift(hwpwm, &addr, &shift); 555 + 556 + ret = regmap_read(pc->regmap, addr, &val); 557 + if (ret) 558 + return ret; 559 + 560 + state->enabled = FIELD_GET(AIROHA_PWM_GPIO_FLASH_EN, val >> shift); 561 + if (!state->enabled) 562 + return 0; 563 + 564 + state->polarity = PWM_POLARITY_NORMAL; 565 + 566 + bucket = FIELD_GET(AIROHA_PWM_GPIO_FLASH_SET_ID, val >> shift); 567 + return airoha_pwm_get_bucket(pc, bucket, &state->period, 568 + &state->duty_cycle); 569 + } 570 + 571 + static const struct pwm_ops airoha_pwm_ops = { 572 + .apply = airoha_pwm_apply, 573 + .get_state = airoha_pwm_get_state, 574 + }; 575 + 576 + static int airoha_pwm_probe(struct platform_device *pdev) 577 + { 578 + struct device *dev = &pdev->dev; 579 + struct airoha_pwm *pc; 580 + struct pwm_chip *chip; 581 + int ret; 582 + 583 + chip = devm_pwmchip_alloc(dev, AIROHA_PWM_MAX_CHANNELS, sizeof(*pc)); 584 + if (IS_ERR(chip)) 585 + return PTR_ERR(chip); 586 + 587 + chip->ops = &airoha_pwm_ops; 588 + pc = pwmchip_get_drvdata(chip); 589 + 590 + pc->regmap = device_node_to_regmap(dev_of_node(dev->parent)); 591 + if (IS_ERR(pc->regmap)) 592 + return dev_err_probe(dev, PTR_ERR(pc->regmap), "Failed to get PWM regmap\n"); 593 + 594 + ret = devm_pwmchip_add(dev, chip); 595 + if (ret) 596 + return dev_err_probe(dev, ret, "Failed to add PWM chip\n"); 597 + 598 + return 0; 599 + } 600 + 601 + static const struct of_device_id airoha_pwm_of_match[] = { 602 + { .compatible = "airoha,en7581-pwm" }, 603 + { /* sentinel */ } 604 + }; 605 + MODULE_DEVICE_TABLE(of, airoha_pwm_of_match); 606 + 607 + static struct platform_driver airoha_pwm_driver = { 608 + .driver = { 609 + .name = "pwm-airoha", 610 + .probe_type = PROBE_PREFER_ASYNCHRONOUS, 611 + .of_match_table = airoha_pwm_of_match, 612 + }, 613 + .probe = airoha_pwm_probe, 614 + }; 615 + module_platform_driver(airoha_pwm_driver); 616 + 617 + MODULE_AUTHOR("Lorenzo Bianconi <lorenzo@kernel.org>"); 618 + MODULE_AUTHOR("Markus Gothe <markus.gothe@genexis.eu>"); 619 + MODULE_AUTHOR("Benjamin Larsson <benjamin.larsson@genexis.eu>"); 620 + MODULE_AUTHOR("Christian Marangi <ansuelsmth@gmail.com>"); 621 + MODULE_DESCRIPTION("Airoha EN7581 PWM driver"); 622 + MODULE_LICENSE("GPL");
+3 -25
drivers/pwm/pwm-bcm2835.c
··· 34 34 return pwmchip_get_drvdata(chip); 35 35 } 36 36 37 - static int bcm2835_pwm_request(struct pwm_chip *chip, struct pwm_device *pwm) 38 - { 39 - struct bcm2835_pwm *pc = to_bcm2835_pwm(chip); 40 - u32 value; 41 - 42 - value = readl(pc->base + PWM_CONTROL); 43 - value &= ~(PWM_CONTROL_MASK << PWM_CONTROL_SHIFT(pwm->hwpwm)); 44 - value |= (PWM_MODE << PWM_CONTROL_SHIFT(pwm->hwpwm)); 45 - writel(value, pc->base + PWM_CONTROL); 46 - 47 - return 0; 48 - } 49 - 50 - static void bcm2835_pwm_free(struct pwm_chip *chip, struct pwm_device *pwm) 51 - { 52 - struct bcm2835_pwm *pc = to_bcm2835_pwm(chip); 53 - u32 value; 54 - 55 - value = readl(pc->base + PWM_CONTROL); 56 - value &= ~(PWM_CONTROL_MASK << PWM_CONTROL_SHIFT(pwm->hwpwm)); 57 - writel(value, pc->base + PWM_CONTROL); 58 - } 59 - 60 37 static int bcm2835_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm, 61 38 const struct pwm_state *state) 62 39 { ··· 79 102 /* set polarity */ 80 103 val = readl(pc->base + PWM_CONTROL); 81 104 105 + val &= ~(PWM_CONTROL_MASK << PWM_CONTROL_SHIFT(pwm->hwpwm)); 106 + val |= PWM_MODE << PWM_CONTROL_SHIFT(pwm->hwpwm); 107 + 82 108 if (state->polarity == PWM_POLARITY_NORMAL) 83 109 val &= ~(PWM_POLARITY << PWM_CONTROL_SHIFT(pwm->hwpwm)); 84 110 else ··· 99 119 } 100 120 101 121 static const struct pwm_ops bcm2835_pwm_ops = { 102 - .request = bcm2835_pwm_request, 103 - .free = bcm2835_pwm_free, 104 122 .apply = bcm2835_pwm_apply, 105 123 }; 106 124
+1 -1
drivers/pwm/pwm-max7360.c
··· 75 75 duty_steps = MAX7360_PWM_MAX - 1; 76 76 } 77 77 78 - wfhw->duty_steps = min(MAX7360_PWM_MAX, duty_steps); 78 + wfhw->duty_steps = duty_steps; 79 79 wfhw->enabled = !!wf->period_length_ns; 80 80 81 81 if (wf->period_length_ns && wf->period_length_ns < MAX7360_PWM_PERIOD_NS)
+201 -134
drivers/pwm/pwm-mediatek.c
··· 135 135 num * chip->soc->chanreg_width + offset); 136 136 } 137 137 138 - static void pwm_mediatek_enable(struct pwm_chip *chip, struct pwm_device *pwm) 138 + struct pwm_mediatek_waveform { 139 + u32 enable; 140 + u32 con; 141 + u32 width; 142 + u32 thres; 143 + }; 144 + 145 + static int pwm_mediatek_round_waveform_tohw(struct pwm_chip *chip, struct pwm_device *pwm, 146 + const struct pwm_waveform *wf, void *_wfhw) 139 147 { 140 - struct pwm_mediatek_chip *pc = to_pwm_mediatek_chip(chip); 141 - u32 value; 142 - 143 - value = readl(pc->regs); 144 - value |= BIT(pwm->hwpwm); 145 - writel(value, pc->regs); 146 - } 147 - 148 - static void pwm_mediatek_disable(struct pwm_chip *chip, struct pwm_device *pwm) 149 - { 150 - struct pwm_mediatek_chip *pc = to_pwm_mediatek_chip(chip); 151 - u32 value; 152 - 153 - value = readl(pc->regs); 154 - value &= ~BIT(pwm->hwpwm); 155 - writel(value, pc->regs); 156 - } 157 - 158 - static int pwm_mediatek_config(struct pwm_chip *chip, struct pwm_device *pwm, 159 - u64 duty_ns, u64 period_ns) 160 - { 148 + struct pwm_mediatek_waveform *wfhw = _wfhw; 161 149 struct pwm_mediatek_chip *pc = to_pwm_mediatek_chip(chip); 162 150 u32 clkdiv, enable; 163 - u32 reg_width = PWMDWIDTH, reg_thres = PWMTHRES; 164 151 u64 cnt_period, cnt_duty; 165 152 unsigned long clk_rate; 166 - int ret; 153 + int ret = 0; 167 154 168 - ret = pwm_mediatek_clk_enable(pc, pwm->hwpwm); 169 - if (ret < 0) 170 - return ret; 155 + if (wf->period_length_ns == 0) { 156 + *wfhw = (typeof(*wfhw)){ 157 + .enable = 0, 158 + }; 159 + 160 + return 0; 161 + } 162 + 163 + if (!pc->clk_pwms[pwm->hwpwm].rate) { 164 + struct clk *clk = pc->clk_pwms[pwm->hwpwm].clk; 165 + 166 + ret = clk_prepare_enable(clk); 167 + if (ret) 168 + return ret; 169 + 170 + pc->clk_pwms[pwm->hwpwm].rate = clk_get_rate(clk); 171 + 172 + clk_disable_unprepare(clk); 173 + } 171 174 172 175 clk_rate = pc->clk_pwms[pwm->hwpwm].rate; 176 + if (clk_rate == 0 || clk_rate > 1000000000) 177 + return -EINVAL; 173 178 174 - /* Make sure we use the bus clock and not the 26MHz clock */ 175 - if (pc->soc->pwm_ck_26m_sel_reg) 176 - writel(0, pc->regs + pc->soc->pwm_ck_26m_sel_reg); 177 - 178 - cnt_period = mul_u64_u64_div_u64(period_ns, clk_rate, NSEC_PER_SEC); 179 + cnt_period = mul_u64_u64_div_u64(wf->period_length_ns, clk_rate, NSEC_PER_SEC); 179 180 if (cnt_period == 0) { 180 - ret = -ERANGE; 181 - goto out; 181 + cnt_period = 1; 182 + ret = 1; 182 183 } 183 184 184 185 if (cnt_period > FIELD_MAX(PWMDWIDTH_PERIOD) + 1) { ··· 194 193 clkdiv = 0; 195 194 } 196 195 197 - cnt_duty = mul_u64_u64_div_u64(duty_ns, clk_rate, NSEC_PER_SEC) >> clkdiv; 196 + cnt_duty = mul_u64_u64_div_u64(wf->duty_length_ns, clk_rate, NSEC_PER_SEC) >> clkdiv; 198 197 if (cnt_duty > cnt_period) 199 198 cnt_duty = cnt_period; 200 199 ··· 207 206 208 207 cnt_period -= 1; 209 208 210 - dev_dbg(&chip->dev, "pwm#%u: %lld/%lld @%lu -> CON: %x, PERIOD: %llx, DUTY: %llx\n", 211 - pwm->hwpwm, duty_ns, period_ns, clk_rate, clkdiv, cnt_period, cnt_duty); 209 + dev_dbg(&chip->dev, "pwm#%u: %lld/%lld @%lu -> ENABLE: %x, CON: %x, PERIOD: %llx, DUTY: %llx\n", 210 + pwm->hwpwm, wf->duty_length_ns, wf->period_length_ns, clk_rate, 211 + enable, clkdiv, cnt_period, cnt_duty); 212 212 213 - if (pc->soc->pwm45_fixup && pwm->hwpwm > 2) { 213 + *wfhw = (typeof(*wfhw)){ 214 + .enable = enable, 215 + .con = clkdiv, 216 + .width = cnt_period, 217 + .thres = cnt_duty, 218 + }; 219 + 220 + return ret; 221 + } 222 + 223 + static int pwm_mediatek_round_waveform_fromhw(struct pwm_chip *chip, struct pwm_device *pwm, 224 + const void *_wfhw, struct pwm_waveform *wf) 225 + { 226 + const struct pwm_mediatek_waveform *wfhw = _wfhw; 227 + struct pwm_mediatek_chip *pc = to_pwm_mediatek_chip(chip); 228 + u32 clkdiv, cnt_period, cnt_duty; 229 + unsigned long clk_rate; 230 + 231 + /* 232 + * When _wfhw was populated, the clock was on, so .rate is 233 + * already set appropriately. 234 + */ 235 + clk_rate = pc->clk_pwms[pwm->hwpwm].rate; 236 + 237 + if (wfhw->enable) { 238 + clkdiv = FIELD_GET(PWMCON_CLKDIV, wfhw->con); 239 + cnt_period = FIELD_GET(PWMDWIDTH_PERIOD, wfhw->width); 240 + cnt_duty = FIELD_GET(PWMTHRES_DUTY, wfhw->thres); 241 + 214 242 /* 215 - * PWM[4,5] has distinct offset for PWMDWIDTH and PWMTHRES 216 - * from the other PWMs on MT7623. 243 + * cnt_period is a 13 bit value, NSEC_PER_SEC is 30 bits wide 244 + * and clkdiv is less than 8, so the multiplication doesn't 245 + * overflow an u64. 217 246 */ 218 - reg_width = PWM45DWIDTH_FIXUP; 219 - reg_thres = PWM45THRES_FIXUP; 247 + *wf = (typeof(*wf)){ 248 + .period_length_ns = 249 + DIV_ROUND_UP_ULL((u64)(cnt_period + 1) * NSEC_PER_SEC << clkdiv, clk_rate), 250 + .duty_length_ns = 251 + DIV_ROUND_UP_ULL((u64)(cnt_duty + 1) * NSEC_PER_SEC << clkdiv, clk_rate), 252 + }; 253 + } else { 254 + clkdiv = 0; 255 + cnt_period = 0; 256 + cnt_duty = 0; 257 + 258 + /* 259 + * .enable = 0 is also used for too small duty_cycle values, so 260 + * report the HW as being enabled to communicate the minimal 261 + * period. 262 + */ 263 + *wf = (typeof(*wf)){ 264 + .period_length_ns = 265 + DIV_ROUND_UP_ULL(NSEC_PER_SEC, clk_rate), 266 + .duty_length_ns = 0, 267 + }; 220 268 } 221 269 222 - pwm_mediatek_writel(pc, pwm->hwpwm, PWMCON, BIT(15) | clkdiv); 223 - pwm_mediatek_writel(pc, pwm->hwpwm, reg_width, cnt_period); 270 + dev_dbg(&chip->dev, "pwm#%u: ENABLE: %x, CLKDIV: %x, PERIOD: %x, DUTY: %x @%lu -> %lld/%lld\n", 271 + pwm->hwpwm, wfhw->enable, clkdiv, cnt_period, cnt_duty, clk_rate, 272 + wf->duty_length_ns, wf->period_length_ns); 273 + 274 + return 0; 275 + } 276 + 277 + static int pwm_mediatek_read_waveform(struct pwm_chip *chip, 278 + struct pwm_device *pwm, void *_wfhw) 279 + { 280 + struct pwm_mediatek_waveform *wfhw = _wfhw; 281 + struct pwm_mediatek_chip *pc = to_pwm_mediatek_chip(chip); 282 + u32 enable, clkdiv, cnt_period, cnt_duty; 283 + u32 reg_width = PWMDWIDTH, reg_thres = PWMTHRES; 284 + int ret; 285 + 286 + ret = pwm_mediatek_clk_enable(pc, pwm->hwpwm); 287 + if (ret < 0) 288 + return ret; 289 + 290 + enable = readl(pc->regs) & BIT(pwm->hwpwm); 224 291 225 292 if (enable) { 226 - pwm_mediatek_writel(pc, pwm->hwpwm, reg_thres, cnt_duty); 227 - pwm_mediatek_enable(chip, pwm); 293 + if (pc->soc->pwm45_fixup && pwm->hwpwm > 2) { 294 + /* 295 + * PWM[4,5] has distinct offset for PWMDWIDTH and PWMTHRES 296 + * from the other PWMs on MT7623. 297 + */ 298 + reg_width = PWM45DWIDTH_FIXUP; 299 + reg_thres = PWM45THRES_FIXUP; 300 + } 301 + 302 + clkdiv = FIELD_GET(PWMCON_CLKDIV, pwm_mediatek_readl(pc, pwm->hwpwm, PWMCON)); 303 + cnt_period = FIELD_GET(PWMDWIDTH_PERIOD, pwm_mediatek_readl(pc, pwm->hwpwm, reg_width)); 304 + cnt_duty = FIELD_GET(PWMTHRES_DUTY, pwm_mediatek_readl(pc, pwm->hwpwm, reg_thres)); 305 + 306 + *wfhw = (typeof(*wfhw)){ 307 + .enable = enable, 308 + .con = BIT(15) | clkdiv, 309 + .width = cnt_period, 310 + .thres = cnt_duty, 311 + }; 228 312 } else { 229 - pwm_mediatek_disable(chip, pwm); 313 + *wfhw = (typeof(*wfhw)){ 314 + .enable = 0, 315 + }; 316 + } 317 + 318 + pwm_mediatek_clk_disable(pc, pwm->hwpwm); 319 + 320 + return ret; 321 + } 322 + 323 + static int pwm_mediatek_write_waveform(struct pwm_chip *chip, 324 + struct pwm_device *pwm, const void *_wfhw) 325 + { 326 + const struct pwm_mediatek_waveform *wfhw = _wfhw; 327 + struct pwm_mediatek_chip *pc = to_pwm_mediatek_chip(chip); 328 + u32 ctrl; 329 + int ret; 330 + 331 + ret = pwm_mediatek_clk_enable(pc, pwm->hwpwm); 332 + if (ret < 0) 333 + return ret; 334 + 335 + ctrl = readl(pc->regs); 336 + 337 + if (wfhw->enable) { 338 + u32 reg_width = PWMDWIDTH, reg_thres = PWMTHRES; 339 + 340 + if (pc->soc->pwm45_fixup && pwm->hwpwm > 2) { 341 + /* 342 + * PWM[4,5] has distinct offset for PWMDWIDTH and PWMTHRES 343 + * from the other PWMs on MT7623. 344 + */ 345 + reg_width = PWM45DWIDTH_FIXUP; 346 + reg_thres = PWM45THRES_FIXUP; 347 + } 348 + 349 + if (!(ctrl & BIT(pwm->hwpwm))) { 350 + /* 351 + * The clks are already on, just increasing the usage 352 + * counter doesn't fail. 353 + */ 354 + ret = pwm_mediatek_clk_enable(pc, pwm->hwpwm); 355 + if (unlikely(ret < 0)) 356 + goto out; 357 + 358 + ctrl |= BIT(pwm->hwpwm); 359 + writel(ctrl, pc->regs); 360 + } 361 + 362 + /* Make sure we use the bus clock and not the 26MHz clock */ 363 + if (pc->soc->pwm_ck_26m_sel_reg) 364 + writel(0, pc->regs + pc->soc->pwm_ck_26m_sel_reg); 365 + 366 + pwm_mediatek_writel(pc, pwm->hwpwm, PWMCON, BIT(15) | wfhw->con); 367 + pwm_mediatek_writel(pc, pwm->hwpwm, reg_width, wfhw->width); 368 + pwm_mediatek_writel(pc, pwm->hwpwm, reg_thres, wfhw->thres); 369 + } else { 370 + if (ctrl & BIT(pwm->hwpwm)) { 371 + ctrl &= ~BIT(pwm->hwpwm); 372 + writel(ctrl, pc->regs); 373 + 374 + pwm_mediatek_clk_disable(pc, pwm->hwpwm); 375 + } 230 376 } 231 377 232 378 out: ··· 382 234 return ret; 383 235 } 384 236 385 - static int pwm_mediatek_apply(struct pwm_chip *chip, struct pwm_device *pwm, 386 - const struct pwm_state *state) 387 - { 388 - struct pwm_mediatek_chip *pc = to_pwm_mediatek_chip(chip); 389 - int err; 390 - 391 - if (state->polarity != PWM_POLARITY_NORMAL) 392 - return -EINVAL; 393 - 394 - if (!state->enabled) { 395 - if (pwm->state.enabled) { 396 - pwm_mediatek_disable(chip, pwm); 397 - pwm_mediatek_clk_disable(pc, pwm->hwpwm); 398 - } 399 - 400 - return 0; 401 - } 402 - 403 - err = pwm_mediatek_config(chip, pwm, state->duty_cycle, state->period); 404 - if (err) 405 - return err; 406 - 407 - if (!pwm->state.enabled) 408 - err = pwm_mediatek_clk_enable(pc, pwm->hwpwm); 409 - 410 - return err; 411 - } 412 - 413 - static int pwm_mediatek_get_state(struct pwm_chip *chip, struct pwm_device *pwm, 414 - struct pwm_state *state) 415 - { 416 - struct pwm_mediatek_chip *pc = to_pwm_mediatek_chip(chip); 417 - int ret; 418 - u32 enable; 419 - u32 reg_width = PWMDWIDTH, reg_thres = PWMTHRES; 420 - 421 - if (pc->soc->pwm45_fixup && pwm->hwpwm > 2) { 422 - /* 423 - * PWM[4,5] has distinct offset for PWMDWIDTH and PWMTHRES 424 - * from the other PWMs on MT7623. 425 - */ 426 - reg_width = PWM45DWIDTH_FIXUP; 427 - reg_thres = PWM45THRES_FIXUP; 428 - } 429 - 430 - ret = pwm_mediatek_clk_enable(pc, pwm->hwpwm); 431 - if (ret < 0) 432 - return ret; 433 - 434 - enable = readl(pc->regs); 435 - if (enable & BIT(pwm->hwpwm)) { 436 - u32 clkdiv, cnt_period, cnt_duty; 437 - unsigned long clk_rate; 438 - 439 - clk_rate = pc->clk_pwms[pwm->hwpwm].rate; 440 - 441 - state->enabled = true; 442 - state->polarity = PWM_POLARITY_NORMAL; 443 - 444 - clkdiv = FIELD_GET(PWMCON_CLKDIV, 445 - pwm_mediatek_readl(pc, pwm->hwpwm, PWMCON)); 446 - cnt_period = FIELD_GET(PWMDWIDTH_PERIOD, 447 - pwm_mediatek_readl(pc, pwm->hwpwm, reg_width)); 448 - cnt_duty = FIELD_GET(PWMTHRES_DUTY, 449 - pwm_mediatek_readl(pc, pwm->hwpwm, reg_thres)); 450 - 451 - /* 452 - * cnt_period is a 13 bit value, NSEC_PER_SEC is 30 bits wide 453 - * and clkdiv is less than 8, so the multiplication doesn't 454 - * overflow an u64. 455 - */ 456 - state->period = 457 - DIV_ROUND_UP_ULL((u64)cnt_period * NSEC_PER_SEC << clkdiv, clk_rate); 458 - state->duty_cycle = 459 - DIV_ROUND_UP_ULL((u64)cnt_duty * NSEC_PER_SEC << clkdiv, clk_rate); 460 - } else { 461 - state->enabled = false; 462 - } 463 - 464 - pwm_mediatek_clk_disable(pc, pwm->hwpwm); 465 - 466 - return ret; 467 - } 468 - 469 237 static const struct pwm_ops pwm_mediatek_ops = { 470 - .apply = pwm_mediatek_apply, 471 - .get_state = pwm_mediatek_get_state, 238 + .sizeof_wfhw = sizeof(struct pwm_mediatek_waveform), 239 + .round_waveform_tohw = pwm_mediatek_round_waveform_tohw, 240 + .round_waveform_fromhw = pwm_mediatek_round_waveform_fromhw, 241 + .read_waveform = pwm_mediatek_read_waveform, 242 + .write_waveform = pwm_mediatek_write_waveform, 472 243 }; 473 244 474 245 static int pwm_mediatek_init_used_clks(struct pwm_mediatek_chip *pc) ··· 444 377 soc = of_device_get_match_data(&pdev->dev); 445 378 446 379 chip = devm_pwmchip_alloc(&pdev->dev, soc->num_pwms, 447 - sizeof(*pc) + soc->num_pwms * sizeof(*pc->clk_pwms)); 380 + struct_size(pc, clk_pwms, soc->num_pwms)); 448 381 if (IS_ERR(chip)) 449 382 return PTR_ERR(chip); 450 383 pc = to_pwm_mediatek_chip(chip);
+12 -3
drivers/pwm/pwm-rzg2l-gpt.c
··· 96 96 return hwpwm & 0x1; 97 97 } 98 98 99 + static inline unsigned int rzg2l_gpt_sibling(unsigned int hwpwm) 100 + { 101 + return hwpwm ^ 0x1; 102 + } 103 + 99 104 static void rzg2l_gpt_write(struct rzg2l_gpt_chip *rzg2l_gpt, u32 reg, u32 data) 100 105 { 101 106 writel(data, rzg2l_gpt->mmio + reg); ··· 276 271 * in use with different settings. 277 272 */ 278 273 if (rzg2l_gpt->channel_request_count[ch] > 1) { 279 - if (period_ticks < rzg2l_gpt->period_ticks[ch]) 280 - return -EBUSY; 281 - else 274 + u8 sibling_ch = rzg2l_gpt_sibling(pwm->hwpwm); 275 + 276 + if (rzg2l_gpt_is_ch_enabled(rzg2l_gpt, sibling_ch)) { 277 + if (period_ticks < rzg2l_gpt->period_ticks[ch]) 278 + return -EBUSY; 279 + 282 280 period_ticks = rzg2l_gpt->period_ticks[ch]; 281 + } 283 282 } 284 283 285 284 prescale = rzg2l_gpt_calculate_prescale(rzg2l_gpt, period_ticks);
+387
drivers/pwm/pwm_th1520.rs
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + // Copyright (c) 2025 Samsung Electronics Co., Ltd. 3 + // Author: Michal Wilczynski <m.wilczynski@samsung.com> 4 + 5 + //! Rust T-HEAD TH1520 PWM driver 6 + //! 7 + //! Limitations: 8 + //! - The period and duty cycle are controlled by 32-bit hardware registers, 9 + //! limiting the maximum resolution. 10 + //! - The driver supports continuous output mode only; one-shot mode is not 11 + //! implemented. 12 + //! - The controller hardware provides up to 6 PWM channels. 13 + //! - Reconfiguration is glitch free - new period and duty cycle values are 14 + //! latched and take effect at the start of the next period. 15 + //! - Polarity is handled via a simple hardware inversion bit; arbitrary 16 + //! duty cycle offsets are not supported. 17 + //! - Disabling a channel is achieved by configuring its duty cycle to zero to 18 + //! produce a static low output. Clearing the `start` does not reliably 19 + //! force the static inactive level defined by the `INACTOUT` bit. Hence 20 + //! this method is not used in this driver. 21 + //! 22 + 23 + use core::ops::Deref; 24 + use kernel::{ 25 + c_str, 26 + clk::Clk, 27 + device::{Bound, Core, Device}, 28 + devres, 29 + io::mem::IoMem, 30 + of, platform, 31 + prelude::*, 32 + pwm, time, 33 + }; 34 + 35 + const TH1520_MAX_PWM_NUM: u32 = 6; 36 + 37 + // Register offsets 38 + const fn th1520_pwm_chn_base(n: u32) -> usize { 39 + (n * 0x20) as usize 40 + } 41 + 42 + const fn th1520_pwm_ctrl(n: u32) -> usize { 43 + th1520_pwm_chn_base(n) 44 + } 45 + 46 + const fn th1520_pwm_per(n: u32) -> usize { 47 + th1520_pwm_chn_base(n) + 0x08 48 + } 49 + 50 + const fn th1520_pwm_fp(n: u32) -> usize { 51 + th1520_pwm_chn_base(n) + 0x0c 52 + } 53 + 54 + // Control register bits 55 + const TH1520_PWM_START: u32 = 1 << 0; 56 + const TH1520_PWM_CFG_UPDATE: u32 = 1 << 2; 57 + const TH1520_PWM_CONTINUOUS_MODE: u32 = 1 << 5; 58 + const TH1520_PWM_FPOUT: u32 = 1 << 8; 59 + 60 + const TH1520_PWM_REG_SIZE: usize = 0xB0; 61 + 62 + fn ns_to_cycles(ns: u64, rate_hz: u64) -> u64 { 63 + const NSEC_PER_SEC_U64: u64 = time::NSEC_PER_SEC as u64; 64 + 65 + (match ns.checked_mul(rate_hz) { 66 + Some(product) => product, 67 + None => u64::MAX, 68 + }) / NSEC_PER_SEC_U64 69 + } 70 + 71 + fn cycles_to_ns(cycles: u64, rate_hz: u64) -> u64 { 72 + const NSEC_PER_SEC_U64: u64 = time::NSEC_PER_SEC as u64; 73 + 74 + // TODO: Replace with a kernel helper like `mul_u64_u64_div_u64_roundup` 75 + // once available in Rust. 76 + let numerator = cycles 77 + .saturating_mul(NSEC_PER_SEC_U64) 78 + .saturating_add(rate_hz - 1); 79 + 80 + numerator / rate_hz 81 + } 82 + 83 + /// Hardware-specific waveform representation for TH1520. 84 + #[derive(Copy, Clone, Debug, Default)] 85 + struct Th1520WfHw { 86 + period_cycles: u32, 87 + duty_cycles: u32, 88 + ctrl_val: u32, 89 + enabled: bool, 90 + } 91 + 92 + /// The driver's private data struct. It holds all necessary devres managed resources. 93 + #[pin_data(PinnedDrop)] 94 + struct Th1520PwmDriverData { 95 + #[pin] 96 + iomem: devres::Devres<IoMem<TH1520_PWM_REG_SIZE>>, 97 + clk: Clk, 98 + } 99 + 100 + // This `unsafe` implementation is a temporary necessity because the underlying `kernel::clk::Clk` 101 + // type does not yet expose `Send` and `Sync` implementations. This block should be removed 102 + // as soon as the clock abstraction provides these guarantees directly. 103 + // TODO: Remove those unsafe impl's when Clk will support them itself. 104 + 105 + // SAFETY: The `devres` framework requires the driver's private data to be `Send` and `Sync`. 106 + // We can guarantee this because the PWM core synchronizes all callbacks, preventing concurrent 107 + // access to the contained `iomem` and `clk` resources. 108 + unsafe impl Send for Th1520PwmDriverData {} 109 + 110 + // SAFETY: The same reasoning applies as for `Send`. The PWM core's synchronization 111 + // guarantees that it is safe for multiple threads to have shared access (`&self`) 112 + // to the driver data during callbacks. 113 + unsafe impl Sync for Th1520PwmDriverData {} 114 + 115 + impl pwm::PwmOps for Th1520PwmDriverData { 116 + type WfHw = Th1520WfHw; 117 + 118 + fn round_waveform_tohw( 119 + chip: &pwm::Chip<Self>, 120 + _pwm: &pwm::Device, 121 + wf: &pwm::Waveform, 122 + ) -> Result<pwm::RoundedWaveform<Self::WfHw>> { 123 + let data = chip.drvdata(); 124 + let mut status = 0; 125 + 126 + if wf.period_length_ns == 0 { 127 + dev_dbg!(chip.device(), "Requested period is 0, disabling PWM.\n"); 128 + 129 + return Ok(pwm::RoundedWaveform { 130 + status: 0, 131 + hardware_waveform: Th1520WfHw { 132 + enabled: false, 133 + ..Default::default() 134 + }, 135 + }); 136 + } 137 + 138 + let rate_hz = data.clk.rate().as_hz() as u64; 139 + 140 + let mut period_cycles = ns_to_cycles(wf.period_length_ns, rate_hz).min(u64::from(u32::MAX)); 141 + 142 + if period_cycles == 0 { 143 + dev_dbg!( 144 + chip.device(), 145 + "Requested period {} ns is too small for clock rate {} Hz, rounding up.\n", 146 + wf.period_length_ns, 147 + rate_hz 148 + ); 149 + 150 + period_cycles = 1; 151 + status = 1; 152 + } 153 + 154 + let mut duty_cycles = ns_to_cycles(wf.duty_length_ns, rate_hz).min(u64::from(u32::MAX)); 155 + 156 + let mut ctrl_val = TH1520_PWM_CONTINUOUS_MODE; 157 + 158 + let is_inversed = wf.duty_length_ns > 0 159 + && wf.duty_offset_ns > 0 160 + && wf.duty_offset_ns >= wf.period_length_ns.saturating_sub(wf.duty_length_ns); 161 + if is_inversed { 162 + duty_cycles = period_cycles - duty_cycles; 163 + } else { 164 + ctrl_val |= TH1520_PWM_FPOUT; 165 + } 166 + 167 + let wfhw = Th1520WfHw { 168 + // The cast is safe because the value was clamped with `.min(u64::from(u32::MAX))`. 169 + period_cycles: period_cycles as u32, 170 + duty_cycles: duty_cycles as u32, 171 + ctrl_val, 172 + enabled: true, 173 + }; 174 + 175 + dev_dbg!( 176 + chip.device(), 177 + "Requested: {}/{} ns [+{} ns] -> HW: {}/{} cycles, ctrl 0x{:x}, rate {} Hz\n", 178 + wf.duty_length_ns, 179 + wf.period_length_ns, 180 + wf.duty_offset_ns, 181 + wfhw.duty_cycles, 182 + wfhw.period_cycles, 183 + wfhw.ctrl_val, 184 + rate_hz 185 + ); 186 + 187 + Ok(pwm::RoundedWaveform { 188 + status, 189 + hardware_waveform: wfhw, 190 + }) 191 + } 192 + 193 + fn round_waveform_fromhw( 194 + chip: &pwm::Chip<Self>, 195 + _pwm: &pwm::Device, 196 + wfhw: &Self::WfHw, 197 + wf: &mut pwm::Waveform, 198 + ) -> Result { 199 + let data = chip.drvdata(); 200 + let rate_hz = data.clk.rate().as_hz() as u64; 201 + 202 + if wfhw.period_cycles == 0 { 203 + dev_dbg!( 204 + chip.device(), 205 + "HW state has zero period, reporting as disabled.\n" 206 + ); 207 + *wf = pwm::Waveform::default(); 208 + return Ok(()); 209 + } 210 + 211 + wf.period_length_ns = cycles_to_ns(u64::from(wfhw.period_cycles), rate_hz); 212 + 213 + let duty_cycles = u64::from(wfhw.duty_cycles); 214 + 215 + if (wfhw.ctrl_val & TH1520_PWM_FPOUT) != 0 { 216 + wf.duty_length_ns = cycles_to_ns(duty_cycles, rate_hz); 217 + wf.duty_offset_ns = 0; 218 + } else { 219 + let period_cycles = u64::from(wfhw.period_cycles); 220 + let original_duty_cycles = period_cycles.saturating_sub(duty_cycles); 221 + 222 + // For an inverted signal, `duty_length_ns` is the high time (period - low_time). 223 + wf.duty_length_ns = cycles_to_ns(original_duty_cycles, rate_hz); 224 + // The offset is the initial low time, which is what the hardware register provides. 225 + wf.duty_offset_ns = cycles_to_ns(duty_cycles, rate_hz); 226 + } 227 + 228 + Ok(()) 229 + } 230 + 231 + fn read_waveform( 232 + chip: &pwm::Chip<Self>, 233 + pwm: &pwm::Device, 234 + parent_dev: &Device<Bound>, 235 + ) -> Result<Self::WfHw> { 236 + let data = chip.drvdata(); 237 + let hwpwm = pwm.hwpwm(); 238 + let iomem_accessor = data.iomem.access(parent_dev)?; 239 + let iomap = iomem_accessor.deref(); 240 + 241 + let ctrl = iomap.try_read32(th1520_pwm_ctrl(hwpwm))?; 242 + let period_cycles = iomap.try_read32(th1520_pwm_per(hwpwm))?; 243 + let duty_cycles = iomap.try_read32(th1520_pwm_fp(hwpwm))?; 244 + 245 + let wfhw = Th1520WfHw { 246 + period_cycles, 247 + duty_cycles, 248 + ctrl_val: ctrl, 249 + enabled: duty_cycles != 0, 250 + }; 251 + 252 + dev_dbg!( 253 + chip.device(), 254 + "PWM-{}: read_waveform: Read hw state - period: {}, duty: {}, ctrl: 0x{:x}, enabled: {}", 255 + hwpwm, 256 + wfhw.period_cycles, 257 + wfhw.duty_cycles, 258 + wfhw.ctrl_val, 259 + wfhw.enabled 260 + ); 261 + 262 + Ok(wfhw) 263 + } 264 + 265 + fn write_waveform( 266 + chip: &pwm::Chip<Self>, 267 + pwm: &pwm::Device, 268 + wfhw: &Self::WfHw, 269 + parent_dev: &Device<Bound>, 270 + ) -> Result { 271 + let data = chip.drvdata(); 272 + let hwpwm = pwm.hwpwm(); 273 + let iomem_accessor = data.iomem.access(parent_dev)?; 274 + let iomap = iomem_accessor.deref(); 275 + let duty_cycles = iomap.try_read32(th1520_pwm_fp(hwpwm))?; 276 + let was_enabled = duty_cycles != 0; 277 + 278 + if !wfhw.enabled { 279 + dev_dbg!(chip.device(), "PWM-{}: Disabling channel.\n", hwpwm); 280 + if was_enabled { 281 + iomap.try_write32(wfhw.ctrl_val, th1520_pwm_ctrl(hwpwm))?; 282 + iomap.try_write32(0, th1520_pwm_fp(hwpwm))?; 283 + iomap.try_write32( 284 + wfhw.ctrl_val | TH1520_PWM_CFG_UPDATE, 285 + th1520_pwm_ctrl(hwpwm), 286 + )?; 287 + } 288 + return Ok(()); 289 + } 290 + 291 + iomap.try_write32(wfhw.ctrl_val, th1520_pwm_ctrl(hwpwm))?; 292 + iomap.try_write32(wfhw.period_cycles, th1520_pwm_per(hwpwm))?; 293 + iomap.try_write32(wfhw.duty_cycles, th1520_pwm_fp(hwpwm))?; 294 + iomap.try_write32( 295 + wfhw.ctrl_val | TH1520_PWM_CFG_UPDATE, 296 + th1520_pwm_ctrl(hwpwm), 297 + )?; 298 + 299 + // The `TH1520_PWM_START` bit must be written in a separate, final transaction, and 300 + // only when enabling the channel from a disabled state. 301 + if !was_enabled { 302 + iomap.try_write32(wfhw.ctrl_val | TH1520_PWM_START, th1520_pwm_ctrl(hwpwm))?; 303 + } 304 + 305 + dev_dbg!( 306 + chip.device(), 307 + "PWM-{}: Wrote {}/{} cycles", 308 + hwpwm, 309 + wfhw.duty_cycles, 310 + wfhw.period_cycles, 311 + ); 312 + 313 + Ok(()) 314 + } 315 + } 316 + 317 + #[pinned_drop] 318 + impl PinnedDrop for Th1520PwmDriverData { 319 + fn drop(self: Pin<&mut Self>) { 320 + self.clk.disable_unprepare(); 321 + } 322 + } 323 + 324 + struct Th1520PwmPlatformDriver; 325 + 326 + kernel::of_device_table!( 327 + OF_TABLE, 328 + MODULE_OF_TABLE, 329 + <Th1520PwmPlatformDriver as platform::Driver>::IdInfo, 330 + [(of::DeviceId::new(c_str!("thead,th1520-pwm")), ())] 331 + ); 332 + 333 + impl platform::Driver for Th1520PwmPlatformDriver { 334 + type IdInfo = (); 335 + const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); 336 + 337 + fn probe( 338 + pdev: &platform::Device<Core>, 339 + _id_info: Option<&Self::IdInfo>, 340 + ) -> Result<Pin<KBox<Self>>> { 341 + let dev = pdev.as_ref(); 342 + let request = pdev.io_request_by_index(0).ok_or(ENODEV)?; 343 + 344 + let clk = Clk::get(dev, None)?; 345 + 346 + clk.prepare_enable()?; 347 + 348 + // TODO: Get exclusive ownership of the clock to prevent rate changes. 349 + // The Rust equivalent of `clk_rate_exclusive_get()` is not yet available. 350 + // This should be updated once it is implemented. 351 + let rate_hz = clk.rate().as_hz(); 352 + if rate_hz == 0 { 353 + dev_err!(dev, "Clock rate is zero\n"); 354 + return Err(EINVAL); 355 + } 356 + 357 + if rate_hz > time::NSEC_PER_SEC as usize { 358 + dev_err!( 359 + dev, 360 + "Clock rate {} Hz is too high, not supported.\n", 361 + rate_hz 362 + ); 363 + return Err(EINVAL); 364 + } 365 + 366 + let chip = pwm::Chip::new( 367 + dev, 368 + TH1520_MAX_PWM_NUM, 369 + try_pin_init!(Th1520PwmDriverData { 370 + iomem <- request.iomap_sized::<TH1520_PWM_REG_SIZE>(), 371 + clk <- clk, 372 + }), 373 + )?; 374 + 375 + pwm::Registration::register(dev, chip)?; 376 + 377 + Ok(KBox::new(Th1520PwmPlatformDriver, GFP_KERNEL)?.into()) 378 + } 379 + } 380 + 381 + kernel::module_pwm_platform_driver! { 382 + type: Th1520PwmPlatformDriver, 383 + name: "pwm-th1520", 384 + authors: ["Michal Wilczynski <m.wilczynski@samsung.com>"], 385 + description: "T-HEAD TH1520 PWM driver", 386 + license: "GPL v2", 387 + }
+6 -33
include/linux/pwm.h
··· 488 488 #define pwmchip_add(chip) __pwmchip_add(chip, THIS_MODULE) 489 489 void pwmchip_remove(struct pwm_chip *chip); 490 490 491 + /* 492 + * For FFI wrapper use only: 493 + * The Rust PWM abstraction needs this to properly free the pwm_chip. 494 + */ 495 + void pwmchip_release(struct device *dev); 496 + 491 497 int __devm_pwmchip_add(struct device *dev, struct pwm_chip *chip, struct module *owner); 492 498 #define devm_pwmchip_add(dev, chip) __devm_pwmchip_add(dev, chip, THIS_MODULE) 493 499 ··· 616 610 return ERR_PTR(-ENODEV); 617 611 } 618 612 #endif 619 - 620 - static inline void pwm_apply_args(struct pwm_device *pwm) 621 - { 622 - struct pwm_state state = { }; 623 - 624 - /* 625 - * PWM users calling pwm_apply_args() expect to have a fresh config 626 - * where the polarity and period are set according to pwm_args info. 627 - * The problem is, polarity can only be changed when the PWM is 628 - * disabled. 629 - * 630 - * PWM drivers supporting hardware readout may declare the PWM device 631 - * as enabled, and prevent polarity setting, which changes from the 632 - * existing behavior, where all PWM devices are declared as disabled 633 - * at startup (even if they are actually enabled), thus authorizing 634 - * polarity setting. 635 - * 636 - * To fulfill this requirement, we apply a new state which disables 637 - * the PWM device and set the reference period and polarity config. 638 - * 639 - * Note that PWM users requiring a smooth handover between the 640 - * bootloader and the kernel (like critical regulators controlled by 641 - * PWM devices) will have to switch to the atomic API and avoid calling 642 - * pwm_apply_args(). 643 - */ 644 - 645 - state.enabled = false; 646 - state.polarity = pwm->args.polarity; 647 - state.period = pwm->args.period; 648 - state.usage_power = false; 649 - 650 - pwm_apply_might_sleep(pwm, &state); 651 - } 652 613 653 614 struct pwm_lookup { 654 615 struct list_head list;
+1
rust/bindings/bindings_helper.h
··· 72 72 #include <linux/pm_opp.h> 73 73 #include <linux/poll.h> 74 74 #include <linux/property.h> 75 + #include <linux/pwm.h> 75 76 #include <linux/random.h> 76 77 #include <linux/refcount.h> 77 78 #include <linux/regulator/consumer.h>
+1
rust/helpers/helpers.c
··· 43 43 #include "poll.c" 44 44 #include "processor.c" 45 45 #include "property.c" 46 + #include "pwm.c" 46 47 #include "rbtree.c" 47 48 #include "rcu.c" 48 49 #include "refcount.c"
+20
rust/helpers/pwm.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + // Copyright (c) 2025 Samsung Electronics Co., Ltd. 3 + // Author: Michal Wilczynski <m.wilczynski@samsung.com> 4 + 5 + #include <linux/pwm.h> 6 + 7 + struct device *rust_helper_pwmchip_parent(const struct pwm_chip *chip) 8 + { 9 + return pwmchip_parent(chip); 10 + } 11 + 12 + void *rust_helper_pwmchip_get_drvdata(struct pwm_chip *chip) 13 + { 14 + return pwmchip_get_drvdata(chip); 15 + } 16 + 17 + void rust_helper_pwmchip_set_drvdata(struct pwm_chip *chip, void *data) 18 + { 19 + pwmchip_set_drvdata(chip, data); 20 + }
+2
rust/kernel/lib.rs
··· 125 125 pub mod print; 126 126 pub mod processor; 127 127 pub mod ptr; 128 + #[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)] 129 + pub mod pwm; 128 130 pub mod rbtree; 129 131 pub mod regulator; 130 132 pub mod revocable;
+735
rust/kernel/pwm.rs
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + // Copyright (c) 2025 Samsung Electronics Co., Ltd. 3 + // Author: Michal Wilczynski <m.wilczynski@samsung.com> 4 + 5 + //! PWM subsystem abstractions. 6 + //! 7 + //! C header: [`include/linux/pwm.h`](srctree/include/linux/pwm.h). 8 + 9 + use crate::{ 10 + bindings, 11 + container_of, 12 + device::{self, Bound}, 13 + devres, 14 + error::{self, to_result}, 15 + prelude::*, 16 + types::{ARef, AlwaysRefCounted, Opaque}, // 17 + }; 18 + use core::{marker::PhantomData, ptr::NonNull}; 19 + 20 + /// Represents a PWM waveform configuration. 21 + /// Mirrors struct [`struct pwm_waveform`](srctree/include/linux/pwm.h). 22 + #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] 23 + pub struct Waveform { 24 + /// Total duration of one complete PWM cycle, in nanoseconds. 25 + pub period_length_ns: u64, 26 + 27 + /// Duty-cycle active time, in nanoseconds. 28 + /// 29 + /// For a typical normal polarity configuration (active-high) this is the 30 + /// high time of the signal. 31 + pub duty_length_ns: u64, 32 + 33 + /// Duty-cycle start offset, in nanoseconds. 34 + /// 35 + /// Delay from the beginning of the period to the first active edge. 36 + /// In most simple PWM setups this is `0`, so the duty cycle starts 37 + /// immediately at each period’s start. 38 + pub duty_offset_ns: u64, 39 + } 40 + 41 + impl From<bindings::pwm_waveform> for Waveform { 42 + fn from(wf: bindings::pwm_waveform) -> Self { 43 + Waveform { 44 + period_length_ns: wf.period_length_ns, 45 + duty_length_ns: wf.duty_length_ns, 46 + duty_offset_ns: wf.duty_offset_ns, 47 + } 48 + } 49 + } 50 + 51 + impl From<Waveform> for bindings::pwm_waveform { 52 + fn from(wf: Waveform) -> Self { 53 + bindings::pwm_waveform { 54 + period_length_ns: wf.period_length_ns, 55 + duty_length_ns: wf.duty_length_ns, 56 + duty_offset_ns: wf.duty_offset_ns, 57 + } 58 + } 59 + } 60 + 61 + /// Describes the outcome of a `round_waveform` operation. 62 + #[derive(Debug, Clone, Copy, PartialEq, Eq)] 63 + pub enum RoundingOutcome { 64 + /// The requested waveform was achievable exactly or by rounding values down. 65 + ExactOrRoundedDown, 66 + 67 + /// The requested waveform could only be achieved by rounding up. 68 + RoundedUp, 69 + } 70 + 71 + /// Wrapper for a PWM device [`struct pwm_device`](srctree/include/linux/pwm.h). 72 + #[repr(transparent)] 73 + pub struct Device(Opaque<bindings::pwm_device>); 74 + 75 + impl Device { 76 + /// Creates a reference to a [`Device`] from a valid C pointer. 77 + /// 78 + /// # Safety 79 + /// 80 + /// The caller must ensure that `ptr` is valid and remains valid for the lifetime of the 81 + /// returned [`Device`] reference. 82 + pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::pwm_device) -> &'a Self { 83 + // SAFETY: The safety requirements guarantee the validity of the dereference, while the 84 + // `Device` type being transparent makes the cast ok. 85 + unsafe { &*ptr.cast::<Self>() } 86 + } 87 + 88 + /// Returns a raw pointer to the underlying `pwm_device`. 89 + fn as_raw(&self) -> *mut bindings::pwm_device { 90 + self.0.get() 91 + } 92 + 93 + /// Gets the hardware PWM index for this device within its chip. 94 + pub fn hwpwm(&self) -> u32 { 95 + // SAFETY: `self.as_raw()` provides a valid pointer for `self`'s lifetime. 96 + unsafe { (*self.as_raw()).hwpwm } 97 + } 98 + 99 + /// Gets a reference to the parent `Chip` that this device belongs to. 100 + pub fn chip<T: PwmOps>(&self) -> &Chip<T> { 101 + // SAFETY: `self.as_raw()` provides a valid pointer. (*self.as_raw()).chip 102 + // is assumed to be a valid pointer to `pwm_chip` managed by the kernel. 103 + // Chip::from_raw's safety conditions must be met. 104 + unsafe { Chip::<T>::from_raw((*self.as_raw()).chip) } 105 + } 106 + 107 + /// Gets the label for this PWM device, if any. 108 + pub fn label(&self) -> Option<&CStr> { 109 + // SAFETY: self.as_raw() provides a valid pointer. 110 + let label_ptr = unsafe { (*self.as_raw()).label }; 111 + if label_ptr.is_null() { 112 + return None; 113 + } 114 + 115 + // SAFETY: label_ptr is non-null and points to a C string 116 + // managed by the kernel, valid for the lifetime of the PWM device. 117 + Some(unsafe { CStr::from_char_ptr(label_ptr) }) 118 + } 119 + 120 + /// Sets the PWM waveform configuration and enables the PWM signal. 121 + pub fn set_waveform(&self, wf: &Waveform, exact: bool) -> Result { 122 + let c_wf = bindings::pwm_waveform::from(*wf); 123 + 124 + // SAFETY: `self.as_raw()` provides a valid `*mut pwm_device` pointer. 125 + // `&c_wf` is a valid pointer to a `pwm_waveform` struct. The C function 126 + // handles all necessary internal locking. 127 + let ret = unsafe { bindings::pwm_set_waveform_might_sleep(self.as_raw(), &c_wf, exact) }; 128 + to_result(ret) 129 + } 130 + 131 + /// Queries the hardware for the configuration it would apply for a given 132 + /// request. 133 + pub fn round_waveform(&self, wf: &mut Waveform) -> Result<RoundingOutcome> { 134 + let mut c_wf = bindings::pwm_waveform::from(*wf); 135 + 136 + // SAFETY: `self.as_raw()` provides a valid `*mut pwm_device` pointer. 137 + // `&mut c_wf` is a valid pointer to a mutable `pwm_waveform` struct that 138 + // the C function will update. 139 + let ret = unsafe { bindings::pwm_round_waveform_might_sleep(self.as_raw(), &mut c_wf) }; 140 + 141 + to_result(ret)?; 142 + 143 + *wf = Waveform::from(c_wf); 144 + 145 + if ret == 1 { 146 + Ok(RoundingOutcome::RoundedUp) 147 + } else { 148 + Ok(RoundingOutcome::ExactOrRoundedDown) 149 + } 150 + } 151 + 152 + /// Reads the current waveform configuration directly from the hardware. 153 + pub fn get_waveform(&self) -> Result<Waveform> { 154 + let mut c_wf = bindings::pwm_waveform::default(); 155 + 156 + // SAFETY: `self.as_raw()` is a valid pointer. We provide a valid pointer 157 + // to a stack-allocated `pwm_waveform` struct for the kernel to fill. 158 + let ret = unsafe { bindings::pwm_get_waveform_might_sleep(self.as_raw(), &mut c_wf) }; 159 + 160 + to_result(ret)?; 161 + 162 + Ok(Waveform::from(c_wf)) 163 + } 164 + } 165 + 166 + /// The result of a `round_waveform_tohw` operation. 167 + #[derive(Debug, Clone, Copy, PartialEq, Eq)] 168 + pub struct RoundedWaveform<WfHw> { 169 + /// A status code, 0 for success or 1 if values were rounded up. 170 + pub status: c_int, 171 + /// The driver-specific hardware representation of the waveform. 172 + pub hardware_waveform: WfHw, 173 + } 174 + 175 + /// Trait defining the operations for a PWM driver. 176 + pub trait PwmOps: 'static + Sized { 177 + /// The driver-specific hardware representation of a waveform. 178 + /// 179 + /// This type must be [`Copy`], [`Default`], and fit within `PWM_WFHWSIZE`. 180 + type WfHw: Copy + Default; 181 + 182 + /// Optional hook for when a PWM device is requested. 183 + fn request(_chip: &Chip<Self>, _pwm: &Device, _parent_dev: &device::Device<Bound>) -> Result { 184 + Ok(()) 185 + } 186 + 187 + /// Optional hook for capturing a PWM signal. 188 + fn capture( 189 + _chip: &Chip<Self>, 190 + _pwm: &Device, 191 + _result: &mut bindings::pwm_capture, 192 + _timeout: usize, 193 + _parent_dev: &device::Device<Bound>, 194 + ) -> Result { 195 + Err(ENOTSUPP) 196 + } 197 + 198 + /// Convert a generic waveform to the hardware-specific representation. 199 + /// This is typically a pure calculation and does not perform I/O. 200 + fn round_waveform_tohw( 201 + _chip: &Chip<Self>, 202 + _pwm: &Device, 203 + _wf: &Waveform, 204 + ) -> Result<RoundedWaveform<Self::WfHw>> { 205 + Err(ENOTSUPP) 206 + } 207 + 208 + /// Convert a hardware-specific representation back to a generic waveform. 209 + /// This is typically a pure calculation and does not perform I/O. 210 + fn round_waveform_fromhw( 211 + _chip: &Chip<Self>, 212 + _pwm: &Device, 213 + _wfhw: &Self::WfHw, 214 + _wf: &mut Waveform, 215 + ) -> Result { 216 + Err(ENOTSUPP) 217 + } 218 + 219 + /// Read the current hardware configuration into the hardware-specific representation. 220 + fn read_waveform( 221 + _chip: &Chip<Self>, 222 + _pwm: &Device, 223 + _parent_dev: &device::Device<Bound>, 224 + ) -> Result<Self::WfHw> { 225 + Err(ENOTSUPP) 226 + } 227 + 228 + /// Write a hardware-specific waveform configuration to the hardware. 229 + fn write_waveform( 230 + _chip: &Chip<Self>, 231 + _pwm: &Device, 232 + _wfhw: &Self::WfHw, 233 + _parent_dev: &device::Device<Bound>, 234 + ) -> Result { 235 + Err(ENOTSUPP) 236 + } 237 + } 238 + 239 + /// Bridges Rust `PwmOps` to the C `pwm_ops` vtable. 240 + struct Adapter<T: PwmOps> { 241 + _p: PhantomData<T>, 242 + } 243 + 244 + impl<T: PwmOps> Adapter<T> { 245 + const VTABLE: PwmOpsVTable = create_pwm_ops::<T>(); 246 + 247 + /// # Safety 248 + /// 249 + /// `wfhw_ptr` must be valid for writes of `size_of::<T::WfHw>()` bytes. 250 + unsafe fn serialize_wfhw(wfhw: &T::WfHw, wfhw_ptr: *mut c_void) -> Result { 251 + let size = core::mem::size_of::<T::WfHw>(); 252 + 253 + build_assert!(size <= bindings::PWM_WFHWSIZE as usize); 254 + 255 + // SAFETY: The caller ensures `wfhw_ptr` is valid for `size` bytes. 256 + unsafe { 257 + core::ptr::copy_nonoverlapping( 258 + core::ptr::from_ref::<T::WfHw>(wfhw).cast::<u8>(), 259 + wfhw_ptr.cast::<u8>(), 260 + size, 261 + ); 262 + } 263 + 264 + Ok(()) 265 + } 266 + 267 + /// # Safety 268 + /// 269 + /// `wfhw_ptr` must be valid for reads of `size_of::<T::WfHw>()` bytes. 270 + unsafe fn deserialize_wfhw(wfhw_ptr: *const c_void) -> Result<T::WfHw> { 271 + let size = core::mem::size_of::<T::WfHw>(); 272 + 273 + build_assert!(size <= bindings::PWM_WFHWSIZE as usize); 274 + 275 + let mut wfhw = T::WfHw::default(); 276 + // SAFETY: The caller ensures `wfhw_ptr` is valid for `size` bytes. 277 + unsafe { 278 + core::ptr::copy_nonoverlapping( 279 + wfhw_ptr.cast::<u8>(), 280 + core::ptr::from_mut::<T::WfHw>(&mut wfhw).cast::<u8>(), 281 + size, 282 + ); 283 + } 284 + 285 + Ok(wfhw) 286 + } 287 + 288 + /// # Safety 289 + /// 290 + /// `dev` must be a valid pointer to a `bindings::device` embedded within a 291 + /// `bindings::pwm_chip`. This function is called by the device core when the 292 + /// last reference to the device is dropped. 293 + unsafe extern "C" fn release_callback(dev: *mut bindings::device) { 294 + // SAFETY: The function's contract guarantees that `dev` points to a `device` 295 + // field embedded within a valid `pwm_chip`. `container_of!` can therefore 296 + // safely calculate the address of the containing struct. 297 + let c_chip_ptr = unsafe { container_of!(dev, bindings::pwm_chip, dev) }; 298 + 299 + // SAFETY: `c_chip_ptr` is a valid pointer to a `pwm_chip` as established 300 + // above. Calling this FFI function is safe. 301 + let drvdata_ptr = unsafe { bindings::pwmchip_get_drvdata(c_chip_ptr) }; 302 + 303 + // SAFETY: The driver data was initialized in `new`. We run its destructor here. 304 + unsafe { core::ptr::drop_in_place(drvdata_ptr.cast::<T>()) }; 305 + 306 + // Now, call the original release function to free the `pwm_chip` itself. 307 + // SAFETY: `dev` is the valid pointer passed into this callback, which is 308 + // the expected argument for `pwmchip_release`. 309 + unsafe { 310 + bindings::pwmchip_release(dev); 311 + } 312 + } 313 + 314 + /// # Safety 315 + /// 316 + /// Pointers from C must be valid. 317 + unsafe extern "C" fn request_callback( 318 + chip_ptr: *mut bindings::pwm_chip, 319 + pwm_ptr: *mut bindings::pwm_device, 320 + ) -> c_int { 321 + // SAFETY: PWM core guarentees `chip_ptr` and `pwm_ptr` are valid pointers. 322 + let (chip, pwm) = unsafe { (Chip::<T>::from_raw(chip_ptr), Device::from_raw(pwm_ptr)) }; 323 + 324 + // SAFETY: The PWM core guarantees the parent device exists and is bound during callbacks. 325 + let bound_parent = unsafe { chip.bound_parent_device() }; 326 + match T::request(chip, pwm, bound_parent) { 327 + Ok(()) => 0, 328 + Err(e) => e.to_errno(), 329 + } 330 + } 331 + 332 + /// # Safety 333 + /// 334 + /// Pointers from C must be valid. 335 + unsafe extern "C" fn capture_callback( 336 + chip_ptr: *mut bindings::pwm_chip, 337 + pwm_ptr: *mut bindings::pwm_device, 338 + res: *mut bindings::pwm_capture, 339 + timeout: usize, 340 + ) -> c_int { 341 + // SAFETY: Relies on the function's contract that `chip_ptr` and `pwm_ptr` are valid 342 + // pointers. 343 + let (chip, pwm, result) = unsafe { 344 + ( 345 + Chip::<T>::from_raw(chip_ptr), 346 + Device::from_raw(pwm_ptr), 347 + &mut *res, 348 + ) 349 + }; 350 + 351 + // SAFETY: The PWM core guarantees the parent device exists and is bound during callbacks. 352 + let bound_parent = unsafe { chip.bound_parent_device() }; 353 + match T::capture(chip, pwm, result, timeout, bound_parent) { 354 + Ok(()) => 0, 355 + Err(e) => e.to_errno(), 356 + } 357 + } 358 + 359 + /// # Safety 360 + /// 361 + /// Pointers from C must be valid. 362 + unsafe extern "C" fn round_waveform_tohw_callback( 363 + chip_ptr: *mut bindings::pwm_chip, 364 + pwm_ptr: *mut bindings::pwm_device, 365 + wf_ptr: *const bindings::pwm_waveform, 366 + wfhw_ptr: *mut c_void, 367 + ) -> c_int { 368 + // SAFETY: Relies on the function's contract that `chip_ptr` and `pwm_ptr` are valid 369 + // pointers. 370 + let (chip, pwm, wf) = unsafe { 371 + ( 372 + Chip::<T>::from_raw(chip_ptr), 373 + Device::from_raw(pwm_ptr), 374 + Waveform::from(*wf_ptr), 375 + ) 376 + }; 377 + match T::round_waveform_tohw(chip, pwm, &wf) { 378 + Ok(rounded) => { 379 + // SAFETY: `wfhw_ptr` is valid per this function's safety contract. 380 + if unsafe { Self::serialize_wfhw(&rounded.hardware_waveform, wfhw_ptr) }.is_err() { 381 + return EINVAL.to_errno(); 382 + } 383 + rounded.status 384 + } 385 + Err(e) => e.to_errno(), 386 + } 387 + } 388 + 389 + /// # Safety 390 + /// 391 + /// Pointers from C must be valid. 392 + unsafe extern "C" fn round_waveform_fromhw_callback( 393 + chip_ptr: *mut bindings::pwm_chip, 394 + pwm_ptr: *mut bindings::pwm_device, 395 + wfhw_ptr: *const c_void, 396 + wf_ptr: *mut bindings::pwm_waveform, 397 + ) -> c_int { 398 + // SAFETY: Relies on the function's contract that `chip_ptr` and `pwm_ptr` are valid 399 + // pointers. 400 + let (chip, pwm) = unsafe { (Chip::<T>::from_raw(chip_ptr), Device::from_raw(pwm_ptr)) }; 401 + // SAFETY: `deserialize_wfhw`'s safety contract is met by this function's contract. 402 + let wfhw = match unsafe { Self::deserialize_wfhw(wfhw_ptr) } { 403 + Ok(v) => v, 404 + Err(e) => return e.to_errno(), 405 + }; 406 + 407 + let mut rust_wf = Waveform::default(); 408 + match T::round_waveform_fromhw(chip, pwm, &wfhw, &mut rust_wf) { 409 + Ok(()) => { 410 + // SAFETY: `wf_ptr` is guaranteed valid by the C caller. 411 + unsafe { 412 + *wf_ptr = rust_wf.into(); 413 + }; 414 + 0 415 + } 416 + Err(e) => e.to_errno(), 417 + } 418 + } 419 + 420 + /// # Safety 421 + /// 422 + /// Pointers from C must be valid. 423 + unsafe extern "C" fn read_waveform_callback( 424 + chip_ptr: *mut bindings::pwm_chip, 425 + pwm_ptr: *mut bindings::pwm_device, 426 + wfhw_ptr: *mut c_void, 427 + ) -> c_int { 428 + // SAFETY: Relies on the function's contract that `chip_ptr` and `pwm_ptr` are valid 429 + // pointers. 430 + let (chip, pwm) = unsafe { (Chip::<T>::from_raw(chip_ptr), Device::from_raw(pwm_ptr)) }; 431 + 432 + // SAFETY: The PWM core guarantees the parent device exists and is bound during callbacks. 433 + let bound_parent = unsafe { chip.bound_parent_device() }; 434 + match T::read_waveform(chip, pwm, bound_parent) { 435 + // SAFETY: `wfhw_ptr` is valid per this function's safety contract. 436 + Ok(wfhw) => match unsafe { Self::serialize_wfhw(&wfhw, wfhw_ptr) } { 437 + Ok(()) => 0, 438 + Err(e) => e.to_errno(), 439 + }, 440 + Err(e) => e.to_errno(), 441 + } 442 + } 443 + 444 + /// # Safety 445 + /// 446 + /// Pointers from C must be valid. 447 + unsafe extern "C" fn write_waveform_callback( 448 + chip_ptr: *mut bindings::pwm_chip, 449 + pwm_ptr: *mut bindings::pwm_device, 450 + wfhw_ptr: *const c_void, 451 + ) -> c_int { 452 + // SAFETY: Relies on the function's contract that `chip_ptr` and `pwm_ptr` are valid 453 + // pointers. 454 + let (chip, pwm) = unsafe { (Chip::<T>::from_raw(chip_ptr), Device::from_raw(pwm_ptr)) }; 455 + 456 + // SAFETY: The PWM core guarantees the parent device exists and is bound during callbacks. 457 + let bound_parent = unsafe { chip.bound_parent_device() }; 458 + 459 + // SAFETY: `wfhw_ptr` is valid per this function's safety contract. 460 + let wfhw = match unsafe { Self::deserialize_wfhw(wfhw_ptr) } { 461 + Ok(v) => v, 462 + Err(e) => return e.to_errno(), 463 + }; 464 + match T::write_waveform(chip, pwm, &wfhw, bound_parent) { 465 + Ok(()) => 0, 466 + Err(e) => e.to_errno(), 467 + } 468 + } 469 + } 470 + 471 + /// VTable structure wrapper for PWM operations. 472 + /// Mirrors [`struct pwm_ops`](srctree/include/linux/pwm.h). 473 + #[repr(transparent)] 474 + pub struct PwmOpsVTable(bindings::pwm_ops); 475 + 476 + // SAFETY: PwmOpsVTable is Send. The vtable contains only function pointers 477 + // and a size, which are simple data types that can be safely moved across 478 + // threads. The thread-safety of calling these functions is handled by the 479 + // kernel's locking mechanisms. 480 + unsafe impl Send for PwmOpsVTable {} 481 + 482 + // SAFETY: PwmOpsVTable is Sync. The vtable is immutable after it is created, 483 + // so it can be safely referenced and accessed concurrently by multiple threads 484 + // e.g. to read the function pointers. 485 + unsafe impl Sync for PwmOpsVTable {} 486 + 487 + impl PwmOpsVTable { 488 + /// Returns a raw pointer to the underlying `pwm_ops` struct. 489 + pub(crate) fn as_raw(&self) -> *const bindings::pwm_ops { 490 + &self.0 491 + } 492 + } 493 + 494 + /// Creates a PWM operations vtable for a type `T` that implements `PwmOps`. 495 + /// 496 + /// This is used to bridge Rust trait implementations to the C `struct pwm_ops` 497 + /// expected by the kernel. 498 + pub const fn create_pwm_ops<T: PwmOps>() -> PwmOpsVTable { 499 + // SAFETY: `core::mem::zeroed()` is unsafe. For `pwm_ops`, all fields are 500 + // `Option<extern "C" fn(...)>` or data, so a zeroed pattern (None/0) is valid initially. 501 + let mut ops: bindings::pwm_ops = unsafe { core::mem::zeroed() }; 502 + 503 + ops.request = Some(Adapter::<T>::request_callback); 504 + ops.capture = Some(Adapter::<T>::capture_callback); 505 + 506 + ops.round_waveform_tohw = Some(Adapter::<T>::round_waveform_tohw_callback); 507 + ops.round_waveform_fromhw = Some(Adapter::<T>::round_waveform_fromhw_callback); 508 + ops.read_waveform = Some(Adapter::<T>::read_waveform_callback); 509 + ops.write_waveform = Some(Adapter::<T>::write_waveform_callback); 510 + ops.sizeof_wfhw = core::mem::size_of::<T::WfHw>(); 511 + 512 + PwmOpsVTable(ops) 513 + } 514 + 515 + /// Wrapper for a PWM chip/controller ([`struct pwm_chip`](srctree/include/linux/pwm.h)). 516 + #[repr(transparent)] 517 + pub struct Chip<T: PwmOps>(Opaque<bindings::pwm_chip>, PhantomData<T>); 518 + 519 + impl<T: PwmOps> Chip<T> { 520 + /// Creates a reference to a [`Chip`] from a valid pointer. 521 + /// 522 + /// # Safety 523 + /// 524 + /// The caller must ensure that `ptr` is valid and remains valid for the lifetime of the 525 + /// returned [`Chip`] reference. 526 + pub(crate) unsafe fn from_raw<'a>(ptr: *mut bindings::pwm_chip) -> &'a Self { 527 + // SAFETY: The safety requirements guarantee the validity of the dereference, while the 528 + // `Chip` type being transparent makes the cast ok. 529 + unsafe { &*ptr.cast::<Self>() } 530 + } 531 + 532 + /// Returns a raw pointer to the underlying `pwm_chip`. 533 + pub(crate) fn as_raw(&self) -> *mut bindings::pwm_chip { 534 + self.0.get() 535 + } 536 + 537 + /// Gets the number of PWM channels (hardware PWMs) on this chip. 538 + pub fn num_channels(&self) -> u32 { 539 + // SAFETY: `self.as_raw()` provides a valid pointer for `self`'s lifetime. 540 + unsafe { (*self.as_raw()).npwm } 541 + } 542 + 543 + /// Returns `true` if the chip supports atomic operations for configuration. 544 + pub fn is_atomic(&self) -> bool { 545 + // SAFETY: `self.as_raw()` provides a valid pointer for `self`'s lifetime. 546 + unsafe { (*self.as_raw()).atomic } 547 + } 548 + 549 + /// Returns a reference to the embedded `struct device` abstraction. 550 + pub fn device(&self) -> &device::Device { 551 + // SAFETY: 552 + // - `self.as_raw()` provides a valid pointer to `bindings::pwm_chip`. 553 + // - The `dev` field is an instance of `bindings::device` embedded 554 + // within `pwm_chip`. 555 + // - Taking a pointer to this embedded field is valid. 556 + // - `device::Device` is `#[repr(transparent)]`. 557 + // - The lifetime of the returned reference is tied to `self`. 558 + unsafe { device::Device::from_raw(&raw mut (*self.as_raw()).dev) } 559 + } 560 + 561 + /// Gets the typed driver specific data associated with this chip's embedded device. 562 + pub fn drvdata(&self) -> &T { 563 + // SAFETY: `pwmchip_get_drvdata` returns the pointer to the private data area, 564 + // which we know holds our `T`. The pointer is valid for the lifetime of `self`. 565 + unsafe { &*bindings::pwmchip_get_drvdata(self.as_raw()).cast::<T>() } 566 + } 567 + 568 + /// Returns a reference to the parent device of this PWM chip's device. 569 + /// 570 + /// # Safety 571 + /// 572 + /// The caller must guarantee that the parent device exists and is bound. 573 + /// This is guaranteed by the PWM core during `PwmOps` callbacks. 574 + unsafe fn bound_parent_device(&self) -> &device::Device<Bound> { 575 + // SAFETY: Per the function's safety contract, the parent device exists. 576 + let parent = unsafe { self.device().parent().unwrap_unchecked() }; 577 + 578 + // SAFETY: Per the function's safety contract, the parent device is bound. 579 + // This is guaranteed by the PWM core during `PwmOps` callbacks. 580 + unsafe { parent.as_bound() } 581 + } 582 + 583 + /// Allocates and wraps a PWM chip using `bindings::pwmchip_alloc`. 584 + /// 585 + /// Returns an [`ARef<Chip>`] managing the chip's lifetime via refcounting 586 + /// on its embedded `struct device`. 587 + pub fn new( 588 + parent_dev: &device::Device, 589 + num_channels: u32, 590 + data: impl pin_init::PinInit<T, Error>, 591 + ) -> Result<ARef<Self>> { 592 + let sizeof_priv = core::mem::size_of::<T>(); 593 + // SAFETY: `pwmchip_alloc` allocates memory for the C struct and our private data. 594 + let c_chip_ptr_raw = 595 + unsafe { bindings::pwmchip_alloc(parent_dev.as_raw(), num_channels, sizeof_priv) }; 596 + 597 + let c_chip_ptr: *mut bindings::pwm_chip = error::from_err_ptr(c_chip_ptr_raw)?; 598 + 599 + // SAFETY: The `drvdata` pointer is the start of the private area, which is where 600 + // we will construct our `T` object. 601 + let drvdata_ptr = unsafe { bindings::pwmchip_get_drvdata(c_chip_ptr) }; 602 + 603 + // SAFETY: We construct the `T` object in-place in the allocated private memory. 604 + unsafe { data.__pinned_init(drvdata_ptr.cast())? }; 605 + 606 + // SAFETY: `c_chip_ptr` points to a valid chip. 607 + unsafe { 608 + (*c_chip_ptr).dev.release = Some(Adapter::<T>::release_callback); 609 + } 610 + 611 + // SAFETY: `c_chip_ptr` points to a valid chip. 612 + // The `Adapter`'s `VTABLE` has a 'static lifetime, so the pointer 613 + // returned by `as_raw()` is always valid. 614 + unsafe { 615 + (*c_chip_ptr).ops = Adapter::<T>::VTABLE.as_raw(); 616 + } 617 + 618 + // Cast the `*mut bindings::pwm_chip` to `*mut Chip`. This is valid because 619 + // `Chip` is `repr(transparent)` over `Opaque<bindings::pwm_chip>`, and 620 + // `Opaque<T>` is `repr(transparent)` over `T`. 621 + let chip_ptr_as_self = c_chip_ptr.cast::<Self>(); 622 + 623 + // SAFETY: `chip_ptr_as_self` points to a valid `Chip` (layout-compatible with 624 + // `bindings::pwm_chip`) whose embedded device has refcount 1. 625 + // `ARef::from_raw` takes this pointer and manages it via `AlwaysRefCounted`. 626 + Ok(unsafe { ARef::from_raw(NonNull::new_unchecked(chip_ptr_as_self)) }) 627 + } 628 + } 629 + 630 + // SAFETY: Implements refcounting for `Chip` using the embedded `struct device`. 631 + unsafe impl<T: PwmOps> AlwaysRefCounted for Chip<T> { 632 + #[inline] 633 + fn inc_ref(&self) { 634 + // SAFETY: `self.0.get()` points to a valid `pwm_chip` because `self` exists. 635 + // The embedded `dev` is valid. `get_device` increments its refcount. 636 + unsafe { 637 + bindings::get_device(&raw mut (*self.0.get()).dev); 638 + } 639 + } 640 + 641 + #[inline] 642 + unsafe fn dec_ref(obj: NonNull<Chip<T>>) { 643 + let c_chip_ptr = obj.cast::<bindings::pwm_chip>().as_ptr(); 644 + 645 + // SAFETY: `obj` is a valid pointer to a `Chip` (and thus `bindings::pwm_chip`) 646 + // with a non-zero refcount. `put_device` handles decrement and final release. 647 + unsafe { 648 + bindings::put_device(&raw mut (*c_chip_ptr).dev); 649 + } 650 + } 651 + } 652 + 653 + // SAFETY: `Chip` is a wrapper around `*mut bindings::pwm_chip`. The underlying C 654 + // structure's state is managed and synchronized by the kernel's device model 655 + // and PWM core locking mechanisms. Therefore, it is safe to move the `Chip` 656 + // wrapper (and the pointer it contains) across threads. 657 + unsafe impl<T: PwmOps + Send> Send for Chip<T> {} 658 + 659 + // SAFETY: It is safe for multiple threads to have shared access (`&Chip`) because 660 + // the `Chip` data is immutable from the Rust side without holding the appropriate 661 + // kernel locks, which the C core is responsible for. Any interior mutability is 662 + // handled and synchronized by the C kernel code. 663 + unsafe impl<T: PwmOps + Sync> Sync for Chip<T> {} 664 + 665 + /// A resource guard that ensures `pwmchip_remove` is called on drop. 666 + /// 667 + /// This struct is intended to be managed by the `devres` framework by transferring its ownership 668 + /// via [`devres::register`]. This ties the lifetime of the PWM chip registration 669 + /// to the lifetime of the underlying device. 670 + pub struct Registration<T: PwmOps> { 671 + chip: ARef<Chip<T>>, 672 + } 673 + 674 + impl<T: 'static + PwmOps + Send + Sync> Registration<T> { 675 + /// Registers a PWM chip with the PWM subsystem. 676 + /// 677 + /// Transfers its ownership to the `devres` framework, which ties its lifetime 678 + /// to the parent device. 679 + /// On unbind of the parent device, the `devres` entry will be dropped, automatically 680 + /// calling `pwmchip_remove`. This function should be called from the driver's `probe`. 681 + pub fn register(dev: &device::Device<Bound>, chip: ARef<Chip<T>>) -> Result { 682 + let chip_parent = chip.device().parent().ok_or(EINVAL)?; 683 + if dev.as_raw() != chip_parent.as_raw() { 684 + return Err(EINVAL); 685 + } 686 + 687 + let c_chip_ptr = chip.as_raw(); 688 + 689 + // SAFETY: `c_chip_ptr` points to a valid chip with its ops initialized. 690 + // `__pwmchip_add` is the C function to register the chip with the PWM core. 691 + unsafe { 692 + to_result(bindings::__pwmchip_add(c_chip_ptr, core::ptr::null_mut()))?; 693 + } 694 + 695 + let registration = Registration { chip }; 696 + 697 + devres::register(dev, registration, GFP_KERNEL) 698 + } 699 + } 700 + 701 + impl<T: PwmOps> Drop for Registration<T> { 702 + fn drop(&mut self) { 703 + let chip_raw = self.chip.as_raw(); 704 + 705 + // SAFETY: `chip_raw` points to a chip that was successfully registered. 706 + // `bindings::pwmchip_remove` is the correct C function to unregister it. 707 + // This `drop` implementation is called automatically by `devres` on driver unbind. 708 + unsafe { 709 + bindings::pwmchip_remove(chip_raw); 710 + } 711 + } 712 + } 713 + 714 + /// Declares a kernel module that exposes a single PWM driver. 715 + /// 716 + /// # Examples 717 + /// 718 + ///```ignore 719 + /// kernel::module_pwm_platform_driver! { 720 + /// type: MyDriver, 721 + /// name: "Module name", 722 + /// authors: ["Author name"], 723 + /// description: "Description", 724 + /// license: "GPL v2", 725 + /// } 726 + ///``` 727 + #[macro_export] 728 + macro_rules! module_pwm_platform_driver { 729 + ($($user_args:tt)*) => { 730 + $crate::module_platform_driver! { 731 + $($user_args)* 732 + imports_ns: ["PWM"], 733 + } 734 + }; 735 + }
+8
rust/macros/module.rs
··· 98 98 description: Option<String>, 99 99 alias: Option<Vec<String>>, 100 100 firmware: Option<Vec<String>>, 101 + imports_ns: Option<Vec<String>>, 101 102 } 102 103 103 104 impl ModuleInfo { ··· 113 112 "license", 114 113 "alias", 115 114 "firmware", 115 + "imports_ns", 116 116 ]; 117 117 const REQUIRED_KEYS: &[&str] = &["type", "name", "license"]; 118 118 let mut seen_keys = Vec::new(); ··· 139 137 "license" => info.license = expect_string_ascii(it), 140 138 "alias" => info.alias = Some(expect_string_array(it)), 141 139 "firmware" => info.firmware = Some(expect_string_array(it)), 140 + "imports_ns" => info.imports_ns = Some(expect_string_array(it)), 142 141 _ => panic!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."), 143 142 } 144 143 ··· 196 193 if let Some(firmware) = info.firmware { 197 194 for fw in firmware { 198 195 modinfo.emit("firmware", &fw); 196 + } 197 + } 198 + if let Some(imports) = info.imports_ns { 199 + for ns in imports { 200 + modinfo.emit("import_ns", &ns); 199 201 } 200 202 } 201 203