[PATCH v4 4/9] pwm: Add Rust driver for T-HEAD TH1520 SoC

Danilo Krummrich dakr at kernel.org
Thu Jun 19 05:19:14 PDT 2025


On Wed, Jun 18, 2025 at 02:27:37PM +0200, Michal Wilczynski wrote:

<snip>

> +    fn write_waveform(
> +        chip: &pwm::Chip,
> +        pwm: &pwm::Device,
> +        wfhw: &Self::WfHw,
> +        parent_dev: &Device<Bound>,
> +    ) -> Result {
> +        let data: &Self = chip.drvdata().ok_or(EINVAL)?;

<snip>

> +impl platform::Driver for Th1520PwmPlatformDriver {
> +    type IdInfo = ();
> +    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
> +
> +    fn probe(
> +        pdev: &platform::Device<Core>,
> +        _id_info: Option<&Self::IdInfo>,
> +    ) -> Result<Pin<KBox<Self>>> {
> +        let dev = pdev.as_ref();
> +        let resource = pdev.resource(0).ok_or(ENODEV)?;
> +        let iomem = pdev.ioremap_resource_sized::<TH1520_PWM_REG_SIZE>(resource)?;
> +        let clk = Clk::get(pdev.as_ref(), None)?;
> +
> +        clk.prepare_enable()?;
> +
> +        // TODO: Get exclusive ownership of the clock to prevent rate changes.
> +        // The Rust equivalent of `clk_rate_exclusive_get()` is not yet available.
> +        // This should be updated once it is implemented.
> +        let rate_hz = clk.rate().as_hz();
> +        if rate_hz == 0 {
> +            dev_err!(dev, "Clock rate is zero\n");
> +            return Err(EINVAL);
> +        }
> +
> +        if rate_hz > time::NSEC_PER_SEC as usize {
> +            dev_err!(
> +                dev,
> +                "Clock rate {} Hz is too high, not supported.\n",
> +                rate_hz
> +            );
> +            return Err(ERANGE);
> +        }
> +
> +        let chip = pwm::Chip::new(dev, MAX_PWM_NUM, 0)?;
> +
> +        let drvdata = KBox::new(Th1520PwmDriverData { iomem, clk }, GFP_KERNEL)?;
> +        chip.set_drvdata(drvdata);

Sorry that I didn't spot this before: Is there a reason you can't pass drvdata
directly to pwm::Chip::new()?

If not, you can initialize the pwm::Chip's drvdata on creation of the pwm::Chip.

This has the advantage that your chip.drvdata() (see write_waveform() above)
becomes infallible.

(If there are reasons this isn't possible, there are other potential solutions
to avoid chip.drvdata() to return an Option.)

> +
> +        pwm::Registration::new_foreign_owned(dev, chip, &TH1520_PWM_OPS)?;
> +
> +        Ok(KBox::new(Th1520PwmPlatformDriver, GFP_KERNEL)?.into())
> +    }
> +}



More information about the linux-riscv mailing list