[PATCH v3 1/3] rust: clk: use the type-state pattern

Daniel Almeida daniel.almeida at collabora.com
Thu Jan 8 06:14:37 PST 2026


Hi Maxime :)

> 
> I don't know the typestate pattern that well, but I wonder if we don't
> paint ourselves into a corner by introducing it.
> 
> While it's pretty common to get your clock from the get go into a state,
> and then don't modify it (like what devm_clk_get_enabled provides for
> example), and the typestate pattern indeed works great for those, we

Minor correction, devm_clk_get_enabled is not handled by the typestate
pattern. The next patch does include this function for convenience, but
you get a Result<()>. The typestate pattern is used when you want more
control.

> also have a significant number of drivers that will have a finer-grained
> control over the clock enablement for PM.
> 
> For example, it's quite typical to have (at least) one clock for the bus
> interface that drives the register, and one that drives the main
> component logic. The former needs to be enabled only when you're
> accessing the registers (and can be abstracted with
> regmap_mmio_attach_clk for example), and the latter needs to be enabled
> only when the device actually starts operating.
> 
> You have a similar thing for the prepare vs enable thing. The difference
> between the two is that enable can be called into atomic context but
> prepare can't.
> 
> So for drivers that would care about this, you would create your device
> with an unprepared clock, and then at various times during the driver
> lifetime, you would mutate that state.
> 
> AFAIU, encoding the state of the clock into the Clk type (and thus
> forcing the structure that holds it) prevents that mutation. If not, we
> should make it clearer (by expanding the doc maybe?) how such a pattern
> can be supported.
> 
> Maxime

IIUC, your main point seems to be about mutating the state at runtime? This is
possible with this code. You can just have an enum, for example:

enum MyClocks {
	Unprepared(Clk<Unprepared>),
        Prepared(Clk<Prepared>),
	Enabled(Clk<Enabled>), 
}

In fact, I specifically wanted to ensure that this was possible when writing
these patches, as it’s needed by drivers. If you want to, I can cover that in
the examples, no worries.

Same for Regulator<T>, by the way.

— Daniel


More information about the linux-riscv mailing list