Skip to content
systemcoding.dev
Kernels

Load Device Firmware From a Driver With request_firmware

Load a firmware blob in a Linux 6.12 driver with request_firmware, validate it, copy it to the device, release it, and use the async variant for early probes.

7 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Linux, C and Raspberry Pi logos.

Some hardware has no program of its own until the host provides one. The driver's job is to ask the kernel for the file, check that it is what it expects, copy it to the device and start the device's processor. The kernel's firmware loader does the finding, the reading, the decompression and the cleanup, and the driver sees two functions and a small structure. This post uses Linux 6.12 to write that sequence for a device with a memory window that receives the image: the request, the validation of a header and a checksum, the upload, the release, and the asynchronous form that avoids blocking probe. The search path the loader uses, and how to install files for it, is covered in the earlier post on firmware locations.

The interface is documented in the kernel's request_firmware guide.

The basic call

c
int request_firmware(const struct firmware **fw, const char *name,
		     struct device *device);
void release_firmware(const struct firmware *fw);

request_firmware() searches for name, reads it into memory and returns a pointer to a struct firmware with two fields that matter: data, a pointer to the bytes, and size, their count. It returns zero on success and a negative errno on failure. The call sleeps, so it works only in process context, and the buffer is read-only. When you have finished with the data, release_firmware() frees it. The structure and its buffer belong to the kernel, and your driver must not free them itself.

Declare the file name in the module's metadata, so tools can tell which firmware a module needs:

c
MODULE_FIRMWARE("example/sample-fw-v2.bin");

modinfo prints it, and initramfs generators read it to know what to copy into the image.

A complete load, validate and upload

This example loads an image with a 12-byte header: a magic number, a payload length and a CRC32 of the payload. It then copies the payload into a device window and starts the device:

sample_fw.cc
#include <linux/crc32.h>
#include <linux/firmware.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>

#define FW_NAME		"example/sample-fw-v2.bin"
#define FW_MAGIC	0x53465731	/* "SFW1" */
#define REG_CTRL	0x00
#define CTRL_RUN	BIT(0)
#define FW_WINDOW	0x1000

struct sample_fw_hdr {
	__le32 magic;
	__le32 length;
	__le32 crc32;
};

struct sample {
	void __iomem *regs;
};

static int sample_load_firmware(struct device *dev, struct sample *s)
{
	const struct firmware *fw;
	const struct sample_fw_hdr *hdr;
	const u8 *payload;
	u32 length, crc;
	int ret;

	ret = request_firmware(&fw, FW_NAME, dev);
	if (ret) {
		dev_err(dev, "cannot load %s: %d\n", FW_NAME, ret);
		return ret;
	}

	if (fw->size < sizeof(*hdr)) {
		ret = -EINVAL;
		goto out;
	}

	hdr = (const struct sample_fw_hdr *)fw->data;
	if (le32_to_cpu(hdr->magic) != FW_MAGIC) {
		dev_err(dev, "bad firmware magic\n");
		ret = -EINVAL;
		goto out;
	}

	length = le32_to_cpu(hdr->length);
	if (length > fw->size - sizeof(*hdr) || length > FW_WINDOW) {
		dev_err(dev, "bad firmware length %u\n", length);
		ret = -EINVAL;
		goto out;
	}

	payload = fw->data + sizeof(*hdr);
	crc = crc32_le(~0, payload, length) ^ ~0;
	if (crc != le32_to_cpu(hdr->crc32)) {
		dev_err(dev, "firmware checksum mismatch\n");
		ret = -EINVAL;
		goto out;
	}

	memcpy_toio(s->regs + 0x100, payload, length);
	iowrite32(CTRL_RUN, s->regs + REG_CTRL);
	dev_info(dev, "firmware %s loaded, %u bytes\n", FW_NAME, length);
out:
	release_firmware(fw);
	return ret;
}

With a valid 3,072-byte image, the log shows:

Text
sample-fw soc:sample: firmware example/sample-fw-v2.bin loaded, 3072 bytes

If the file is missing, the loader's own message comes first, followed by the driver's:

Text
sample-fw soc:sample: Direct firmware load for example/sample-fw-v2.bin failed with error -2
sample-fw soc:sample: cannot load example/sample-fw-v2.bin: -2

Why the validation matters

The firmware file is data from outside the kernel, and the driver treats it as untrusted. The order of the checks in the example is deliberate. The size check comes before the header is read, so a truncated file cannot make the code read past the buffer. The length field is compared to what is left in the file and to the device window, so a corrupt length cannot write beyond the window or the buffer. The checksum catches bit rot and a mismatched file. Without them, a damaged file in /lib/firmware becomes a kernel memory corruption.

A version check follows the same logic. Hardware revisions often need a specific firmware generation, so the file name carries a version (sample-fw-v2.bin) and the driver, or the header, states which it needs. A driver that accepts any file and fails mysteriously on a mismatch is far harder to support than one that prints "firmware version 1 is not supported, need 2".

The copy uses memcpy_toio(), not memcpy(), because the destination is device memory behind an __iomem pointer, as in the BAR mapping post. For a device that takes its image by DMA instead, the driver maps the buffer with the DMA API and lets the device pull it.

Not found is not always an error

A device that works without updated firmware, using what is in its flash, can treat a missing file as acceptable. The plain call prints a warning when the file is absent, which is noise for an optional update. firmware_request_nowarn() takes the same arguments and keeps quiet:

c
ret = firmware_request_nowarn(&fw, "example/sample-update.bin", dev);
if (ret == -ENOENT)
	return 0;	/* no update available, run from flash */

Use it only for files that are truly optional. A missing required file should be loud.

Not in probe, or asynchronously

Calling request_firmware() in probe has a trap. A driver that is built into the kernel, or loaded from the initramfs, probes before the root filesystem is mounted, and the search for the file fails because the file is not reachable yet. If the firmware is not in the initramfs, probe fails and the device stays dead until the module is reloaded by hand.

There are two remedies. The first is to include the firmware in the initramfs, so it is found at any time. The second is to request it asynchronously and let the loader find it when it can:

c
int request_firmware_nowait(struct module *module, bool uevent,
			    const char *name, struct device *device,
			    gfp_t gfp, void *context,
			    void (*cont)(const struct firmware *fw, void *context));

The call returns immediately, and the kernel calls cont from a worker thread when the file has been loaded, or with fw set to NULL if it could not be. The driver finishes initialization there:

c
static void sample_fw_ready(const struct firmware *fw, void *context)
{
	struct sample *s = context;

	if (!fw) {
		dev_err(s->dev, "firmware not available\n");
		return;
	}
	sample_upload(s, fw);
	release_firmware(fw);
}

ret = request_firmware_nowait(THIS_MODULE, false, FW_NAME, dev,
			      GFP_KERNEL, s, sample_fw_ready);

The uevent argument chooses whether to send a hotplug event for the old user-space helper, which is almost always false today. The context pointer must remain valid until cont runs, which means the driver structure must outlive the call, so the remove function has to wait for or cancel the pending request. This is the same lifetime discipline as in the USB disconnect post: something runs later against your structure, and remove must account for it. The asynchronous form also keeps probe fast, which helps boot time when the file is large.

Large and cached firmware

Some drivers need the firmware again after a suspend or a reset. Calling request_firmware() during resume works because the kernel caches firmware around suspend for exactly this reason: the file system may not be available at that stage, and the cache holds what drivers loaded before. It is a good reason to keep the request in a helper that the resume path can call, and not to save the pointer and keep it past release_firmware().

Packaging and updating the file

Two habits keep firmware manageable over the life of a product. Put the version in the file name, so that a driver and a firmware that must match are matched by name: when the interface between them changes, the driver asks for a new name, and an old file sitting in /lib/firmware cannot be loaded by mistake. And ship the file with the driver or in a package that depends on it, since the module and the blob are one deliverable from the user's point of view. A driver that works only when somebody has separately copied a file into place generates support requests that look like hardware faults.

For upstream drivers, the firmware is submitted to the linux-firmware repository, with its license, and the driver names the file there. For an out-of-tree driver, document the expected path and the checksum of the supported image, and print both in the error message when loading fails, so the reader knows exactly what to install.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.