Module 5 · Lesson 73 of 129

Writing a clock provider

Register a fixed-rate clock with the Common Clock Framework, publish it through device tree, and verify its rate from a separate consumer driver.

  • Beginner to advanced
  • 7 min read
  • 35 min lab
What you will need

Ubuntu 24.04 with a Linux 6.8 build and matching build files, a kernel module toolchain, and an ARM64 QEMU virt guest that can boot with a custom device tree. No physical board is required.

Your place in the module
By the end you can 4 objectives
  • Identify the roles of struct clk_hw, struct clk_ops, and struct clk_init_data.
  • Distinguish the functions of fixed-rate clocks, PLLs, muxes, dividers, and gates.
  • Register a fixed-rate clock and publish it as a device-tree provider.
  • Verify that a separate consumer node resolves the clock and reads its configured rate.
Video coming soonWriting a clock provider
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The clock framework
  • A successful clk_get or devm_clk_get returns a clock handle without preparing or enabling the clock.
  • clk_prepare_enable can sleep and each successful call needs a matching clk_disable_unprepare.
  • clock-names selects an entry in clocks, and the referenced provider's #clock-cells specifies how many argument cells follow its phandle.
01

Describe the clock to the framework

3 min read

The last lesson consumed clocks. This lesson answers the provider side: struct clk_hw and clk_ops, and how fixed-rate, gate, divider and mux clocks form a tree.

A peripheral can require a clock whose control register is shared with other outputs. If two drivers update fields in that register independently, a read-modify-write in one can overwrite the other's change. The Common Clock Framework (CCF) gives consumers clock handles and lets provider code implement the hardware-specific operations. A controller driver can then coordinate access to its shared registers. The kernel's clock framework documentation describes this division and the locking rules for provider callbacks. The Common Clk Framework

struct clk_hw is the provider's handle for one clock. A provider typically embeds it in a larger structure with the information its callbacks need, such as a fixed frequency or a mapped register address and bit index. CCF passes the clk_hw pointer to each operation. The callback uses container_of() to recover the enclosing object, so the same operations can serve several clock instances with different hardware data. A consumer receives a struct clk * for use with the consumer API.

struct clk_ops lists the callbacks a clock implements. A read-only fixed-rate output can supply just .recalc_rate. A gate can implement .enable, .disable, and .is_enabled. A programmable divider typically reports its rate through .recalc_rate and implements rate selection and programming. With a mux, .get_parent reports the selected input index, and .set_parent programs the selection if the hardware allows it. Choose the callbacks from the capabilities of the output you are registering.

An active clock pathFixed-rate oscillatorPLLSynthesizes a frequencyMuxPLL input selectedDividerReduces the rateGateControls signal deliveryPeripheralFixed-rate oscillatorPLLSynthesizes a frequencyMuxPLL input selectedDividerReduces the rateGateControls signaldeliveryPeripheral
One possible active path through a controller with separate clock stages

A fixed-rate oscillator provides a reference frequency. A phase-locked loop (PLL) can synthesize another frequency from that reference. A mux selects one of its inputs, for example a direct oscillator signal or a PLL output. A divider reduces the selected frequency according to its hardware encoding. A gate controls whether the resulting signal reaches the downstream device. Closing a gate stops delivery of the signal. The configured rate reported by CCF can still be the same, so a rate read alone does not prove that a clock is running.

When writing a controller driver, identify the inputs, the outputs exposed to consumers, and which operations each stage supports. The kernel provides registration helpers for common implementations, including fixed-rate clocks, gates, dividers, and muxes. A PLL often needs hardware-specific operations because its valid settings and lock behavior depend on the controller. For an MMIO gate, the CCF enable and disable callbacks must run without sleeping. If several fields share a register, protect the read-modify-write with a lock shared by the code that accesses those fields. CCF uses different locks for enable operations and operations such as rate changes, so its locking alone does not serialize every access to a shared register.

02

Register the clock and publish the provider

3 min read

struct clk_init_data supplies the registration name, operations, flags, and any parent descriptions. Set hw.init to that description before registering the clock. In older drivers you will see clk_register(dev, hw), which returns a struct clk * or an error pointer. Pair a successful manual registration with clk_unregister(). For provider code that already owns a struct clk_hw, clk_hw_register() returns an integer status. This example uses devm_clk_hw_register(), which also arranges unregistration when the device's managed resources are released.

Registration through lookupInitializeclk_hwRegisterwith CCFPublish DTproviderResolveconsumerphandleInitializeclk_hwRegisterwith CCFPublish DTproviderResolveconsumerphandle
Clock registration and device-tree publication are separate steps

The following kernel code supplies the probe callback for a platform driver matched to embeddex,lab-clock. The rate is a chosen lab setting in hertz. This software clock has no MMIO registers and generates no electrical signal. The example assumes one provider instance and uses a distinct CCF registration name for it.

c
#include <linux/clk-provider.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/slab.h>

struct lab_clock {
    struct clk_hw hw;
    unsigned long rate;
};

static unsigned long lab_recalc_rate(struct clk_hw *hw,
                                     unsigned long parent_rate)
{
    struct lab_clock *clock = container_of(hw, struct lab_clock, hw);

    (void)parent_rate;
    return clock->rate;
}

static const struct clk_ops lab_ops = { .recalc_rate = lab_recalc_rate };

static int lab_clock_probe(struct platform_device *pdev)
{
    struct device *dev = &pdev->dev;
    struct clk_init_data init = { .name = "embeddex-lab-ref", .ops = &lab_ops };
    struct lab_clock *clock;
    int ret;

    clock = devm_kzalloc(dev, sizeof(*clock), GFP_KERNEL);
    if (!clock)
        return -ENOMEM;
    clock->rate = 24000000UL;
    clock->hw.init = &init;
    ret = devm_clk_hw_register(dev, &clock->hw);
    if (ret)
        return ret;
    return devm_of_clk_add_hw_provider(dev, of_clk_hw_simple_get, &clock->hw);
}

Build the callbacks as kernel module code with the kernel build system. Use the platform driver and OF match table pattern from the earlier driver lessons, with the function above as .probe. The temporary init description is used during registration and may go out of scope when probe returns. The enclosing lab_clock object and the operations must remain valid while the clock is registered. Here the operations are static, and managed allocation keeps the object alive through unregistration.

devm_of_clk_add_hw_provider() publishes a lookup callback for the provider's device-tree node. of_clk_hw_simple_get returns the same clk_hw for this single-output provider. Add a root-level provider node named clock-lab with the label labclk, compatible = "embeddex,lab-clock"; and #clock-cells = <0>;. The zero means the clock specifier contains only the provider phandle, with no output selector after it. Add a separate root-level node named clock-client with compatible = "embeddex,lab-client";, clocks = <&labclk>; and clock-names = "ref";. These are lab-specific compatibles. Use the guest's own device tree as the base so its boot devices remain described.

A second platform driver matches embeddex,lab-client. Device-tree lookup uses the phandle to find the provider and the consumer's clock-names property to associate "ref" with its clocks entry. The name "ref" belongs to the consumer node. The name "embeddex-lab-ref" is the clock's registration name inside CCF. Changing that registration name does not require changing clock-names.

c
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/platform_device.h>

static int lab_client_probe(struct platform_device *pdev)
{
    struct device *dev = &pdev->dev;
    struct clk *clk = devm_clk_get(dev, "ref");

    if (IS_ERR(clk))
        return dev_err_probe(dev, PTR_ERR(clk), "cannot get ref clock\n");

    dev_info(dev, "ref rate: %lu Hz\n", clk_get_rate(clk));
    return 0;
}

The rate logged by this probe should match the rate configured in the provider. This read needs no enable operation for the fixed-rate example. The probe preserves lookup errors, including -EPROBE_DEFER when the provider described by the phandle has yet to register. A failure after clock registration also has a defined cleanup path. If the provider registration fails, the probe returns that error and managed cleanup unregisters the clock. On teardown after successful probe, managed resources are released in reverse order: remove the device-tree provider, unregister the clock, then free its state. Unbind the lab consumer before removing the provider during a manual test.

03

Follow parent changes in a clock tree

2 min read

A clock's parent is the upstream clock that currently supplies its input. A fixed-rate root can stand alone. A divider usually has one input, while a mux can have several possible inputs and one active parent. CCF represents the currently selected relationships as a tree for each root. When the provider initializes a mux, the order of its parent descriptions must agree with the indices returned by .get_parent and accepted by .set_parent. If the hardware uses sparse selector values, the driver must translate between those values and CCF's parent indices.

Successful mux reparentingRequest newparentValidateparentchoiceProgram muxselectorUpdateclock treeRequest newparentValidateparentchoiceProgram muxselectorUpdateclock tree
The framework and mux hardware cooperate to change the active parent

clk_set_parent(clk, parent) requests a new parent. For a controllable mux, CCF checks that the requested clock is an eligible parent and calls the provider's .set_parent callback when a switch is needed. The callback writes the hardware selector and returns a status. A successful switch changes the active relationship and can change the rates of clocks farther downstream even if their own registers stay untouched. If the hardware requires the output to be unprepared before switching, the provider can specify CLK_SET_PARENT_GATE, which lets CCF reject switching a prepared clock.

A driver that needs to react to a clock's rate changes can register a notifier with clk_notifier_register() and remove it with clk_notifier_unregister(). The rate-change notifications are PRE_RATE_CHANGE, POST_RATE_CHANGE, and ABORT_RATE_CHANGE. A pre-change callback can reject a proposed rate change. A device that pauses work in the pre-change callback can use the post-change notification to update its timing and resume, or the abort notification to resume with its prior timing. These are rate-change notifications, so a parent switch that leaves the rate unchanged should not be treated as a guaranteed notification.

Mark an output with CLK_IS_CRITICAL when the system depends on that clock continuing to run, such as a clock required for an essential interconnect. CCF prepares and enables a critical clock at registration and protects it from ordinary shutdown. The designation reflects a hardware requirement. A lab source with a dedicated consumer needs no critical flag, and the flag has no role in resolving a device-tree lookup.

For a fixed-rate provider, the useful evidence is the consumer's reading of the declared frequency through its own device-tree reference. The next lesson, The reset framework and probe ordering, asks what happens when a device needs both a clock and a reset controller before its driver can use it.

Key takeaways

  • The provider embeds struct clk_hw in an object that holds its private state.
  • Clock registration and device-tree provider registration are separate operations.
  • A single-output provider using of_clk_hw_simple_get can expose a zero-cell clock specifier.
  • Registering the clock before publishing the provider gives managed teardown the reverse order.
Reflect
  1. Explain to a colleague, in two sentences: identify the roles of struct clk_hw, struct clk_ops, and struct clk_init_data.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close