Module 5 · Lesson 113 of 129

Implementing the driver stack

Implement SensorNode’s IIO sensor, GPIO button, LED and runtime PM, then verify their Linux interfaces in QEMU.

  • Beginner to advanced
  • 9 min read
  • 65 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, an ARM64 QEMU virt guest with a Linux 6.8 build, a matching kernel toolchain, dtc, and evtest in the guest

Your place in the module
By the end you can 4 objectives
  • Implement a platform IIO driver that returns raw samples and propagates read errors
  • Bind a GPIO button and an LED to standard Linux drivers through the guest device tree
  • Sequence clock and reset operations across runtime resume, suspend and teardown
  • Demonstrate sensor reads, button events, LED state and runtime PM in QEMU
Video coming soonImplementing the driver stack
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The dev loop and risk list
  • QEMU can exercise driver behavior with a fake sensor backend
  • A board build needs the matching target kernel build tree and toolchain
  • Checkpatch, sparse, and KUnit provide different evidence
01

Bind the SensorNode devices

3 min read

The last lesson kicked off the project and set up the loop. This lesson answers the build itself, implementing the IIO, input, LED and PM drivers and wiring in the device tree, clocks, resets and GPIO.

A sensor driver that reads registers with its clock disabled can fail even after it has successfully registered an IIO device. The kernel’s runtime PM documentation describes the distinction that matters here: after a successful resume the device must be ready for I/O, and after a successful suspend it must no longer process data or communicate with the CPU until it resumes. Build that rule into the sensor driver from the first working read. Runtime PM callbacks

Use an ARM64 QEMU virt guest for this milestone. The guest uses the emulated PL061 GPIO controller for the button and LED. For the sensor, use a deliberately synthetic sample source in the SensorNode platform driver and give that device a clock from a DT fixed-clock provider. A DT node can cause Linux to create a platform device, but it cannot give QEMU a new peripheral model. Give the synthetic sensor its own project compatible so the driver selects the sample backend explicitly. A future hardware compatible can select a real backend with the appropriate bus or MMIO access. Keep the QEMU node free of a fabricated register range or IRQ.

SensorNode devices and interfacesSensorButtonLEDDriverSensorNodeIIOgpio-keysleds-gpioResourceCore clockGPIO and IRQOutput GPIOReadoutRaw sampleInput eventsBrightness
The three SensorNode devices and the Linux interfaces they provide

Start from the DTB generated by the project’s QEMU machine configuration. The virt machine option dumpdtb writes that DTB. Decompile it with dtc -I dtb -O dts, edit the resulting source, compile it with dtc -I dts -O dtb, and boot the edited DTB with QEMU’s -dtb option. Preserve the generated GPIO controller, interrupt routing and existing power button. When editing decompiled source, use the actual GPIO controller phandle from that tree or give its node a label and reference the label. Build the guest with IIO, input event devices, gpio-keys, the LED class, leds-gpio, PL061 GPIO and runtime PM support available. Load any pieces built as modules.

For the sensor node, put the clock provider in clocks and give that entry the consumer name core in clock-names. Use the same name in devm_clk_get(dev, "core"). A fixed-rate provider gives the lab a genuine clock lookup and lets you exercise prepare and enable accounting. Its rate is a fixture setting for the synthetic device, and enabling it does not demonstrate physical clock gating. On a target where the binding supplies a reset, put the reset specifier in resets and its name in reset-names. Use devm_reset_control_get_optional_exclusive() when the binding permits a missing reset. An absent optional reset is represented by NULL. An error pointer still carries a real error, including possible probe deferral. Use a required getter if the hardware cannot operate without reset control.

On a board with pin multiplexing, the device that owns the pins gets the corresponding pinctrl-names and pinctrl-0 configuration. The device core selects a defined default state before probe when there is no init state. Put bus pin configuration on the controller where the board binding assigns that ownership. Put button and LED pin configuration on the appropriate device according to the board wiring. The QEMU PL061 fixture needs no fabricated pinctrl provider. On a real target, adding a sleep state to DT describes the configuration. The driver or subsystem must select it at the appropriate transition if the design uses it. Pin control requests and device states

02

Expose the sensor, button and LED

3 min read

In the sensor platform driver, match the synthetic compatible with an OF match table and export it with MODULE_DEVICE_TABLE when building a module. In probe, allocate the IIO device with devm_iio_device_alloc() and store the clock, reset and sample backend in its private data. Store the IIO pointer as platform driver data so runtime PM callbacks can retrieve it. Fill in the IIO name, channel list, channel count, info and INDIO_DIRECT_MODE. Use a single voltage channel with index zero, set indexed, and include BIT(IIO_CHAN_INFO_RAW) in the channel’s info_mask_separate. That combination gives the lab in_voltage0_raw. Register with devm_iio_device_register() after the driver can handle a read immediately.

In read_raw, handle IIO_CHAN_INFO_RAW and return -EINVAL for unsupported requests. Acquire runtime PM before calling the sample backend. For the synthetic backend, choose a documented raw test value and return it consistently. On success put that value in *val and return IIO_VAL_INT. Return any backend error as a negative errno. This keeps an I/O failure distinguishable from a valid zero sample. The value in this lab is an integer code from the fixture. A physical voltage reading needs the conversion specified for the real sensor, including a scale if the driver exposes one. IIO core interfaces

One direct sensor readRead rawattributeResume andgetAttemptsampleMark lastbusyExit from step 2: Resume failsReturn errorPut withautosuspendReturnresultRead rawattributeResume andgetExit from step 2: ResumefailsReturn errorAttemptsampleMark lastbusyPut withautosuspendReturnresult
The sensor read holds a runtime PM reference through sample acquisition

For the button, reuse the generated gpio-keys power-key child in the QEMU DT and check its linux,code. On the DT-based virt setup, the QEMU monitor command system_powerdown can stimulate the emulated power button. This is a power-button request, so run evtest --grab on the matching event device first and use a disposable guest with guest shutdown handling controlled. Watch for the key code and its press and release events. The button driver translates a GPIO transition into an input event. It derives the IRQ from the GPIO in this setup. A board node that describes a separate interrupt needs an interrupt specifier that matches its wiring and binding. Linux assigns the IRQ number. Copying a number printed by a previous boot into DT would describe the wrong thing.

For the LED, add a gpio-leds node with a child using a free line on the emulated PL061. Check the generated tree and the machine configuration for other uses of the line, including the power key. Give the LED a distinct label such as sensornode:green:status and set the GPIO polarity to match the connection you are modeling. The GPIO descriptor API applies active-low polarity to logical operations. Set a known initial state with default-state = "off". The LED class device should appear under /sys/class/leds/. In the guest, use cat to read max_brightness. With manual control, write 0 and then the advertised maximum to brightness with sufficient permissions, reading brightness back after each write. Select none in trigger if that attribute exists and a trigger is active. The emulated setup demonstrates software state changes. A physical light needs an attached LED. GPIO logical and physical values

Identify the sensor by the name attribute in /sys/bus/iio/devices/iio:deviceN/ and read in_voltage0_raw there. Identify the button by the device name and supported key code shown by evtest. N and /dev/input/eventN indices are assigned at runtime. Use the discovered paths in your demo notes so the same procedure works after a reboot even if enumeration changes.

03

Make runtime PM and failure handling agree

4 min read

The sensor’s runtime PM callbacks belong to its platform driver. Attach a struct dev_pm_ops through the platform driver’s .driver.pm. In this fixture, probe acquires resource handles and leaves the sensor idle. A newly initialized device has a suspended runtime PM status. That status fits this implementation because probe leaves the consumer clock disabled and does no sample I/O. If a hardware backend starts out active and probe leaves it active, establish that state in runtime PM before enabling runtime management. The software state has to match what the driver actually did.

For a device whose reset can be operated with the core clock running, resume calls clk_prepare_enable() and then reset_control_deassert() when a reset is present. Use the hardware’s required ordering for a real backend. If enabling the clock fails, return its error immediately. If deasserting reset fails, disable and unprepare the clock before returning the reset error. If a later initialization step fails after reset was released, undo that release where possible before disabling the clock and preserve the original failure for the caller. Runtime suspend asserts the reset, when present, and then calls clk_disable_unprepare(). If assertion fails, return the error and leave the clock enabled. The callback has failed to put the device into its suspended state.

Runtime PM resource orderRuntimeresumeRuntimesuspendFirst operationEnable clockAssert resetif presentSecond operationRelease resetif presentDisable clockSuccess stateReady foraccessSuspended
Runtime resume and suspend change resources in opposite order

In probe, set an autosuspend delay in milliseconds, call pm_runtime_use_autosuspend(), and enable runtime PM before registering the IIO device. Use pm_runtime_resume_and_get() in read_raw. A negative return means you should return the error without reading or putting a reference. After every successful get, mark the device last busy with pm_runtime_mark_last_busy() and release the reference with pm_runtime_put_autosuspend() after the sample attempt, including when the backend fails. Keep a backend error as the read result. A PM put that schedules or attempts idle processing has a different purpose from the sample call and cannot turn a failed sample into a successful one.

For resource acquisition failures, return the original errno, using dev_err_probe() when adding probe context. -EPROBE_DEFER means the driver core can retry when suppliers become available. A clock name mismatch is a configuration error to diagnose by comparing clock-names to the getter argument. Keep registration last so a clock or reset lookup error cannot leave a visible sensor interface behind. The other two devices bind independently, so a failed sensor probe can coexist with working input events and LED control.

Arrange teardown in the reverse order of exposure. One implementation is to register a devm_add_action_or_reset() cleanup action after enabling runtime PM and before managed IIO registration. If action registration fails, the action runs immediately. If later IIO registration fails, managed cleanup runs during probe unwind. After a successful bind, managed IIO unregistration runs before the PM cleanup action. In the action, disable runtime PM, undo the autosuspend setup, and power down explicitly if runtime status is still active. Handle any final reset error and ensure the clock enable acquired by this driver is balanced on removal. The managed clock and reset handles are still available because you acquired them before registering the action. Disabling runtime PM stops runtime transitions, while releasing the handles alone does not undo a clock enable.

For Milestone 2, the successful guest run has four observations: the IIO raw code, the button event pair, two LED brightness readings and sensor runtime PM status. Read power/runtime_status on the sensor’s platform device, the device that owns the PM callbacks. With runtime control set to auto, let the autosuspend delay expire and check for suspended. Read the IIO attribute again to confirm access resumes successfully. A status read can miss the brief active interval, so a successful read after an observed suspend is stronger evidence than trying to catch that interval by hand. Restore the valid DT after checking a deliberate clock-name mismatch and confirm the sensor binds again. QEMU validates the Linux interfaces and the modeled transitions. Board reset sequencing, actual pin states and physical power savings need evidence from the hardware that implements them.

The next lesson, Concurrency and blocking in the project, asks what happens when sensor access, interrupt handling and power transitions overlap. It starts with the callbacks and device lifetimes established here.

Key takeaways

  • Device tree describes devices and their resources, while QEMU supplies the hardware behavior
  • The gpio-keys and leds-gpio drivers provide the project’s input and LED interfaces
  • The sensor driver holds a runtime PM usage reference while accessing the device
  • Releasing a managed resource handle does not reverse hardware state changes
Reflect
  1. Explain to a colleague, in two sentences: implement a platform IIO driver that returns raw samples and propagates read errors
  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