Skip to contentSkip to conversation

fit: dm-verity support

PATCH Superseded Daniel Golle 3 participants 12 messages May 13 – May 15

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v4 cover fit: dm-verity support

This series adds dm-verity support to U-Boot's FIT image infrastructure. It is the first logical subset of the larger OpenWrt boot method series posted as an RFC in February 2026 [1], extracted here for independent review and merging.

OpenWrt's firmware model embeds a read-only squashfs or erofs root filesystem directly inside a uImage.FIT container as a FILESYSTEM-type loadable FIT image. At boot the kernel maps this sub-image directly from the underlying block device via the fitblk driver (/dev/fit0, /dev/fit1, ...), the goal is that the bootloader never even copies it to RAM.

dm-verity enables the kernel to verify the integrity of those mapped filesystems at read time, with a Merkle hash tree stored contiguously in the same sub-image just after the data. Two kernel command-line parameters are required:

dm-mod.create= -- the device-mapper target table for the verity device
dm-mod.waitfor= -- a comma-separated list of block devices to wait for
before dm-init sets up the targets (needed when fitblk probes late, e.g. because it depends on NVMEM calibration data)

The FIT dm-verity node schema was upstreamed into the flat-image-tree specification [2], which this implementation tries to follow exactly.

The runtime feature is guarded behind CONFIG_FIT_VERITY. If not enabled the resulting binary size remains unchanged. If enabled the binary size increases by about 3kB.

[1] previous submissions:

    RFC: https://www.mail-archive.com/[email protected]/msg565945.html
    v1:  https://www.mail-archive.com/[email protected]/msg569472.html
    v2:  https://www.mail-archive.com/[email protected]/msg570599.html
    v3:  https://www.mail-archive.com/[email protected]/msg573223.html

[2] flat-image-tree dm-verity node spec:

    https://github.com/open-source-firmware/flat-image-tree/commit/795fd5fd7f0121d0cb03efb1900aafc61c704771

v4: address comments by Simon Glass and Tom Rini
* pytest: verify the computed digest with veritysetup verify against the external data section
* pytest: parametrize test_mkimage_verity with matched and mismatched block sizes to exercise hash-start-block != num-data-blocks
* pytest: use run_and_log_expect_exception() with the expected diagnostic for the no-external-data case
* enable CONFIG_FIT_VERITY in the sandbox configs that build a full U-Boot binary so CI may exercise the new tests

v3: address comments by Heinrich Schuchardt and Simon Glass
* use unsigned int instead of int for data-block-size and hash-block-size
* replace printf() with log_err() for the "broken dm-verity metadata" diagnostic
* use FIT_VERITY_*_PROP, FIT_TYPE_PROP and FIT_LOADABLE_PROP constants in the unit test instead of literal strings
* extend the mkimage block-count overflow check to also cover hash_start_block (matters when hash-block-size < data-block-size)
* doc: clarify that hash-start-block only equals num-data-blocks when data-block-size == hash-block-size
* pytest: drop unused 'struct' import and the home-rolled have_veritysetup() helper in favour of @pytest.mark.requiredtool('veritysetup')

v2: address comments by Simon Glass
* use is_power_of_2() for pre-boot sanity check
* let fit_verity_build_cmdline() return 0 on success
* add comment explaining why bootm_start() calls fit_verity_free()
* use existing hex2bin() (and adapt it to be usable for host-tools)
* fix stale comment still including superblock despite veritysetup being called with --no-superblock
* add power-of-two check for data-block-size and hash-block-size to mkimage
* don't ignore return value of fdt_delprop()
* various documentation fixes, minimal example
* add pytest for mkimage part
* add run-time unit test for cmdline generation part

Daniel Golle (8):
image: fit: add dm-verity property name constants
boot: fit: support generating DM verity cmdline parameters
include: hexdump: make hex2bin() usable from host tools
tools: mkimage: add dm-verity Merkle-tree generation
doc: fit: add dm-verity boot parameter documentation
test: boot: add runtime unit test for fit_verity_build_cmdline()
test: py: add mkimage dm-verity round-trip test
configs: sandbox: enable CONFIG_FIT_VERITY

 boot/Kconfig                       |  20 ++
 boot/bootm.c                       |  13 ++
 boot/image-board.c                 |   5 +
 boot/image-fit.c                   | 337 ++++++++++++++++++++++++++++
 configs/sandbox64_defconfig        |   1 +
 configs/sandbox_defconfig          |   1 +
 configs/sandbox_flattree_defconfig |   1 +
 doc/usage/fit/dm-verity.rst        | 284 +++++++++++++++++++++++
 doc/usage/fit/index.rst            |   1 +
 include/hexdump.h                  |   8 +-
 include/image.h                    |  97 +++++++-
 test/boot/Makefile                 |   1 +
 test/boot/fit_verity.c             | 306 +++++++++++++++++++++++++
 test/cmd_ut.c                      |   2 +
 test/py/tests/test_fit_verity.py   | 175 +++++++++++++++
 tools/fit_image.c                  | 116 +++++++++-
 tools/image-host.c                 | 349 ++++++++++++++++++++++++++++-
 17 files changed, 1704 insertions(+), 13 deletions(-)
 create mode 100644 doc/usage/fit/dm-verity.rst
 create mode 100644 test/boot/fit_verity.c
 create mode 100644 test/py/tests/test_fit_verity.py
Signature · 1 line
2.54.0
#1 lore raw

PATCH v4 1/8 image: fit: add dm-verity property name constants

Add FIT_VERITY_NODENAME and the complete set of FIT_VERITY_*_PROP constants for the dm-verity child node of filesystem-type images, plus the five optional boolean error-handling property names aligned with the flat-image-tree specification.

---
v4: no changes
v3: no changes
v2: no changes

 include/image.h | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
include/image.h +17 -0
index 34efac6056d..482446a8115 100644
@@ -1079,6 +1079,23 @@ int booti_setup(ulong image, ulong *relocated_addr, ulong *size,
 #define FIT_CIPHER_NODENAME	"cipher"
 #define FIT_ALGO_PROP		"algo"
 
+/* dm-verity node */
+#define FIT_VERITY_NODENAME	"dm-verity"
+#define FIT_VERITY_ALGO_PROP	"algo"
+#define FIT_VERITY_DBS_PROP	"data-block-size"
+#define FIT_VERITY_HBS_PROP	"hash-block-size"
+#define FIT_VERITY_NBLK_PROP	"num-data-blocks"
+#define FIT_VERITY_HBLK_PROP	"hash-start-block"
+#define FIT_VERITY_DIGEST_PROP	"digest"
+#define FIT_VERITY_SALT_PROP	"salt"
+
+/* dm-verity error-handling modes (optional boolean property names) */
+#define FIT_VERITY_OPT_RESTART	"restart-on-corruption"
+#define FIT_VERITY_OPT_PANIC	"panic-on-corruption"
+#define FIT_VERITY_OPT_RERR	"restart-on-error"
+#define FIT_VERITY_OPT_PERR	"panic-on-error"
+#define FIT_VERITY_OPT_ONCE	"check-at-most-once"
+
 /* image node */
 #define FIT_DATA_PROP		"data"
 #define FIT_DATA_POSITION_PROP	"data-position"
Signature · 1 line
2.54.0
#2 lore raw

PATCH v4 2/8 boot: fit: support generating DM verity cmdline parameters

In reply to Daniel Golle

Add fit_verity_build_cmdline(): when a FILESYSTEM loadable carries a dm-verity subnode, construct the dm-mod.create= kernel cmdline parameter from the verity metadata (block-size, data-blocks, algo, root-hash, salt) and append it to bootargs.

Also add dm-mod.waitfor=/dev/fit0[,/dev/fitN] for each dm-verity device so the kernel waits for the underlying FIT block device to appear before setting up device-mapper targets. This is needed when the block driver probes late, e.g. because it depends on NVMEM calibration data.

The dm-verity target references /dev/fitN where N is the loadable's index in the configuration -- matching the order Linux's FIT block driver assigns block devices. hash-start-block is read directly from the FIT dm-verity node; mkimage ensures its value equals num-data-blocks by invoking veritysetup with --no-superblock.

---
v4: no changes
v3:
* use unsigned int for data_block_size and hash_block_size
* replace printf() with log_err() for the "broken dm-verity metadata"
v2:
* use is_power_of_2() for pre-boot sanity check
* let fit_verity_build_cmdline() return 0 on success
* add comment explaining why bootm_start() calls fit_verity_free()

 boot/Kconfig       |  20 +++
 boot/bootm.c       |  13 ++
 boot/image-board.c |   5 +
 boot/image-fit.c   | 337 +++++++++++++++++++++++++++++++++++++++++++++
 include/image.h    |  80 ++++++++++-
 5 files changed, 454 insertions(+), 1 deletion(-)
boot/Kconfig +20 -0
index ae6f09a6ede..e1114aea843 100644
@@ -142,6 +142,26 @@ config FIT_CIPHER
 	  Enable the feature of data ciphering/unciphering in the tool mkimage
 	  and in the u-boot support of the FIT image.
 
+config FIT_VERITY
+	bool "dm-verity boot parameter generation from FIT metadata"
+	depends on FIT && OF_LIBFDT
+	help
+	  When a FIT configuration contains loadable sub-images of type
+	  IH_TYPE_FILESYSTEM with a dm-verity subnode, this option enables
+	  building the dm-mod.create= and dm-mod.waitfor= kernel
+	  command-line parameters from the verity metadata
+	  (data-block-size, hash-block-size, num-data-blocks,
+	  hash-start-block, algorithm, digest, salt) stored in the FIT.
+
+	  The generated parameters reference /dev/fitN block devices that
+	  Linux's uImage.FIT block driver assigns to loadable sub-images.
+
+	  During FIT parsing (BOOTM_STATE_FINDOTHER), verity cmdline
+	  fragments are stored in struct bootm_headers and automatically
+	  appended to the bootargs environment variable during
+	  BOOTM_STATE_OS_PREP.  This works from both the bootm command
+	  and BOOTSTD bootmeths.
+
 config FIT_VERBOSE
 	bool "Show verbose messages when FIT images fail"
 	help
boot/bootm.c +13 -0
index 4836d6b2d41..d6a54a49fce 100644
@@ -243,6 +243,13 @@ static int boot_get_kernel(const char *addr_fit, struct bootm_headers *images,
 
 static int bootm_start(void)
 {
+	/*
+	 * Free dm-verity allocations from a prior boot attempt before
+	 * zeroing the structure.  The pointers are guaranteed to be valid
+	 * or NULL: .bss is zero-initialised, and memset() below zeroes
+	 * them again after every boot.
+	 */
+	fit_verity_free(&images);
 	memset((void *)&images, 0, sizeof(images));
 	images.verify = env_get_yesno("verify");
 
@@ -1071,6 +1078,12 @@ int bootm_run_states(struct bootm_info *bmi, int states)
 		/* For Linux OS do all substitutions at console processing */
 		if (images->os.os == IH_OS_LINUX)
 			flags = BOOTM_CL_ALL;
+		ret = fit_verity_apply_bootargs(images);
+		if (ret) {
+			printf("dm-verity bootargs failed (err=%d)\n", ret);
+			ret = CMD_RET_FAILURE;
+			goto err;
+		}
 		ret = bootm_process_cmdline_env(flags);
 		if (ret) {
 			printf("Cmdline setup failed (err=%d)\n", ret);
boot/image-board.c +5 -0
index 005d60caf5c..265f29d44ff 100644
@@ -810,6 +810,11 @@ int boot_get_loadable(struct bootm_headers *images)
 
 			fit_loadable_process(img_type, img_data, img_len);
 		}
+
+		fit_img_result = fit_verity_build_cmdline(buf, conf_noffset,
+							  images);
+		if (fit_img_result < 0)
+			return fit_img_result;
 		break;
 	default:
 		printf("The given image format is not supported (corrupt?)\n");
boot/image-fit.c +337 -0

360 lines not on this page · raw message

include/image.h +79 -1

92 lines not on this page · raw message

Signature · 1 line
2.54.0
#3 lore raw

PATCH v4 3/8 include: hexdump: make hex2bin() usable from host tools

In reply to Daniel Golle

Make hexdump.h work in host-tool builds by using 'uint8_t' instead of 'u8', and including either user-space libc <ctype.h> for host-tools or <linux/ctype.h> when building U-Boot itself.

---
v4: no changes
v3: no changes
v2: new patch

 include/hexdump.h | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
include/hexdump.h +6 -2
index f2ca4793d69..5cb48d79efe 100644
@@ -7,7 +7,11 @@
 #ifndef HEXDUMP_H
 #define HEXDUMP_H
 
+#ifdef USE_HOSTCC
+#include <ctype.h>
+#else
 #include <linux/ctype.h>
+#endif
 #include <linux/types.h>
 
 enum dump_prefix_t {
@@ -20,7 +24,7 @@ extern const char hex_asc[];
 #define hex_asc_lo(x)	hex_asc[((x) & 0x0f)]
 #define hex_asc_hi(x)	hex_asc[((x) & 0xf0) >> 4]
 
-static inline char *hex_byte_pack(char *buf, u8 byte)
+static inline char *hex_byte_pack(char *buf, uint8_t byte)
 {
 	*buf++ = hex_asc_hi(byte);
 	*buf++ = hex_asc_lo(byte);
@@ -52,7 +56,7 @@ static inline int hex_to_bin(char ch)
  *
  * Return 0 on success, -1 in case of bad input.
  */
-static inline int hex2bin(u8 *dst, const char *src, size_t count)
+static inline int hex2bin(uint8_t *dst, const char *src, size_t count)
 {
 	while (count--) {
 		int hi = hex_to_bin(*src++);
Signature · 1 line
2.54.0
#4 lore raw

PATCH v4 4/8 tools: mkimage: add dm-verity Merkle-tree generation

In reply to Daniel Golle

When mkimage encounters a dm-verity subnode inside a component image node it now automatically invokes veritysetup(8) with --no-superblock to generate the Merkle hash tree, screen-scrapes the Root hash and Salt from the tool output, and writes the computed properties back into the FIT blob.

The user only needs to specify algorithm, data-block-size, and hash-block-size in the ITS; mkimage fills in digest, salt, num-data-blocks, and hash-start-block. Because --no-superblock is used, hash-start-block equals num-data-blocks with no off-by-one.

The image data property is replaced with the expanded content (original data followed directly by the hash tree) so that subsequent hash and signature subnodes operate on the complete image.

fit_image_add_verification_data() is restructured into two passes:
dm-verity first (may grow data), then hashes and signatures.

---
v4: no changes
v3: extend the block-count overflow check to also cover hash_start_block
(matters when hash-block-size < data-block-size)
v2:
* use existing hex2bin() instead of open-coding it
* fix stale comment still mentioning the verity superblock
* add power-of-two check for data-block-size and hash-block-size
* don't ignore return value of fdt_delprop()

 tools/fit_image.c  | 116 ++++++++++++++-
 tools/image-host.c | 349 ++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 455 insertions(+), 10 deletions(-)
tools/fit_image.c +110 -6
index 1dbc14c63e4..95942336820 100644
@@ -40,10 +40,10 @@ static int fit_estimate_hash_sig_size(struct image_tool_params *params, const ch
 		return -EIO;
 
 	/*
-	 * Walk the FIT image, looking for nodes named hash* and
-	 * signature*. Since the interesting nodes are subnodes of an
-	 * image or configuration node, we are only interested in
-	 * those at depth exactly 3.
+	 * Walk the FIT image, looking for nodes named hash*,
+	 * signature*, and dm-verity.  Since the interesting nodes are
+	 * subnodes of an image or configuration node, we are only
+	 * interested in those at depth exactly 3.
 	 *
 	 * The estimate for a hash node is based on a sha512 digest
 	 * being 64 bytes, with another 64 bytes added to account for
@@ -55,6 +55,10 @@ static int fit_estimate_hash_sig_size(struct image_tool_params *params, const ch
 	 * account for fdt overhead and the various other properties
 	 * (hashed-nodes etc.) that will also be filled in.
 	 *
+	 * For a dm-verity node the small metadata properties (digest,
+	 * salt, two u32s and a temp-file path) are written into the
+	 * FDT by fit_image_process_verity().
+	 *
 	 * One could try to be more precise in the estimates by
 	 * looking at the "algo" property and, in the case of
 	 * configuration signatures, the sign-images property. Also,
@@ -76,6 +80,18 @@ static int fit_estimate_hash_sig_size(struct image_tool_params *params, const ch
 
 		if (signing && !strncmp(name, FIT_SIG_NODENAME, strlen(FIT_SIG_NODENAME)))
 			estimate += 1024;
+
+		if (!strcmp(name, FIT_VERITY_NODENAME)) {
+			if (!params->external_data) {
+				fprintf(stderr,
+					"%s: dm-verity requires external data (-E)\n",
+					params->cmdname);
+				munmap(fdt, sbuf.st_size);
+				close(fd);
+				return -EINVAL;
+			}
+			estimate += 256;
+		}
 	}
 
 	munmap(fdt, sbuf.st_size);
@@ -470,6 +486,67 @@ static int fit_write_images(struct image_tool_params *params, char *fdt)
 	return 0;
 }
 
+/**
+ * fit_copy_image_data() - copy image data, using verity temp file if present
+ * @fdt:		FIT blob
+ * @node:		image node offset
+ * @buf:		destination buffer
+ * @buf_ptr:	write offset within @buf
+ * @data:		embedded image data (used when no verity temp file exists)
+ * @lenp:		in/out: on entry, length of @data; on exit, bytes written
+ *
+ * When fit_image_process_verity() has run, a temp-file path is stored in
+ * the dm-verity subnode.  Read that file (original data + hash tree) into
+ * @buf instead of copying the embedded data property.
+ *
+ * Return: 0 on success, -EIO on error
+ */
+static int fit_copy_image_data(void *fdt, int node, void *buf,
+			       int buf_ptr, const void *data, int *lenp)
+{
+	const char *vfile;
+	char vfile_buf[256];
+	struct stat vst;
+	int vfd, ret;
+	int vn;
+
+	vn = fdt_subnode_offset(fdt, node, FIT_VERITY_NODENAME);
+	vfile = NULL;
+	if (vn >= 0)
+		vfile = fdt_getprop(fdt, vn, "verity-data-file", NULL);
+	if (!vfile) {
+		memcpy(buf + buf_ptr, data, *lenp);
+		return 0;
+	}
+
+	/* Copy path -- FDT shifts after delprop */
+	snprintf(vfile_buf, sizeof(vfile_buf), "%s", vfile);
+	ret = fdt_delprop(fdt, vn, "verity-data-file");
+	if (ret) {
+		fprintf(stderr, "Can't remove verity-data-file property: %s\n",
+			fdt_strerror(ret));
+		return -EPERM;
+	}
+
+	if (stat(vfile_buf, &vst)) {
+		fprintf(stderr, "Can't stat verity data: %s\n",
+			strerror(errno));
+		return -EIO;
+	}
+	vfd = open(vfile_buf, O_RDONLY);
+	if (vfd < 0 || read(vfd, buf + buf_ptr, vst.st_size) != vst.st_size) {
+		fprintf(stderr, "Can't read verity data: %s\n",
+			strerror(errno));
+		if (vfd >= 0)
+			close(vfd);
+		return -EIO;
+	}
+	close(vfd);
+	*lenp = vst.st_size;
+	unlink(vfile_buf);
+	return 0;
+}
+
 /**
  * fit_write_configs() - Write out a list of configurations to the FIT
  *
@@ -653,6 +730,11 @@ static int fit_extract_data(struct image_tool_params *params, const char *fname)
 	int node;
 	int align_size = 0;
 	int len = 0;
+	int verity_extra = 0;
+	int orig_len;
+	int vn;
+	const char *vf;
+	struct stat vst;
 
 	fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, false);
 	if (fd < 0)
@@ -686,11 +768,30 @@ static int fit_extract_data(struct image_tool_params *params, const char *fname)
 		align_size += 4;
 	}
 
+	/*
+	 * When dm-verity is active the external data for an image is
+	 * larger than the embedded data property (original + hash tree).
+	 * Walk images once more to account for the difference.
+	 */
+	fdt_for_each_subnode(node, fdt, images) {
+		vn = fdt_subnode_offset(fdt, node, FIT_VERITY_NODENAME);
+		orig_len = 0;
+
+		if (vn < 0)
+			continue;
+		vf = fdt_getprop(fdt, vn, "verity-data-file", NULL);
+		if (!vf)
+			continue;
+		fdt_getprop(fdt, node, FIT_DATA_PROP, &orig_len);
+		if (!stat(vf, &vst) && vst.st_size > orig_len)
+			verity_extra += vst.st_size - orig_len;
+	}
+
 	/*
 	 * Allocate space to hold the image data we will extract,
 	 * extral space allocate for image alignment to prevent overflow.
 	 */
-	buf = calloc(1, fit_size + align_size);
+	buf = calloc(1, fit_size + align_size + verity_extra);
 	if (!buf) {
 		ret = -ENOMEM;
 		goto err_munmap;
@@ -721,7 +822,10 @@ static int fit_extract_data(struct image_tool_params *params, const char *fname)
 		data = fdt_getprop(fdt, node, FIT_DATA_PROP, &len);
 		if (!data)
 			continue;
-		memcpy(buf + buf_ptr, data, len);
+
+		ret = fit_copy_image_data(fdt, node, buf, buf_ptr, data, &len);
+		if (ret)
+			goto err_munmap;
 		debug("Extracting data size %x\n", len);
 
 		ret = fdt_delprop(fdt, node, FIT_DATA_PROP);
tools/image-host.c +345 -4

397 lines not on this page · raw message

Signature · 1 line
2.54.0
#6 lore raw

PATCH v4 5/8 doc: fit: add dm-verity boot parameter documentation

In reply to Daniel Golle

Add documentation for CONFIG_FIT_VERITY which allows U-Boot to construct dm-mod.create= and dm-mod.waitfor= kernel command-line parameters from dm-verity metadata embedded in FIT filesystem sub-images.

The new document covers the relationship between FIT loadable indices and the /dev/fitN block devices that the Linux uImage.FIT block driver creates, provides a complete .its example with a dm-verity-protected SquashFS root filesystem, describes all required and optional dm-verity subnode properties and explains how mkimage generates the verity metadata automatically.

dm-verity is only supported for external-data FIT images (mkimage -E); mkimage aborts with an error if the flag is omitted.

---
v4: no changes
v3: clarify that hash-start-block only equals num-data-blocks when
data-block-size == hash-block-size; in the general case it is data_size / hash-block-size
v2: trim minimal .its example to user-provided properties only and
remove stale references to a verity superblock

 doc/usage/fit/dm-verity.rst | 284 ++++++++++++++++++++++++++++++++++++
 doc/usage/fit/index.rst     |   1 +
 2 files changed, 285 insertions(+)
 create mode 100644 doc/usage/fit/dm-verity.rst
doc/usage/fit/dm-verity.rst new file +284 -0
new file mode 100644
index 00000000000..eddce9e7cf7
@@ -0,0 +1,284 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+FIT dm-verity Boot Parameters
+=============================
+
+Introduction
+------------
+
+Linux's dm-verity device-mapper target provides transparent integrity
+checking of block devices using a Merkle tree. It is commonly used to
+protect read-only root filesystems such as SquashFS images.
+
+When a FIT image packages the root filesystem as a loadable sub-image of
+type ``filesystem`` (``IH_TYPE_FILESYSTEM``), the verity metadata can be
+stored alongside the image data in a ``dm-verity`` subnode. U-Boot reads
+this metadata at boot time and generates the kernel command-line parameters
+that Linux needs to activate the verity target, eliminating the need for
+an initramfs or userspace helper to set up dm-verity.
+
+This feature is enabled by ``CONFIG_FIT_VERITY`` (see ``boot/Kconfig``).
+
+Prerequisites
+-------------
+
+* **Linux uImage.FIT block driver** – the kernel must include the FIT block
+  driver that exposes loadable sub-images as ``/dev/fit0``, ``/dev/fit1``,
+  etc.  The driver assigns device numbers in the order loadables appear in
+  the FIT configuration.
+
+* **dm-verity support in the kernel** – ``CONFIG_DM_VERITY`` must be
+  enabled so the kernel can process the ``dm-mod.create=`` parameter.
+
+* **CONFIG_FIT_VERITY** enabled in U-Boot.
+
+How it works
+------------
+
+The implementation is split into a **build** phase and an **apply** phase,
+both of which run automatically within the ``bootm`` state machine. No boot
+method needs to call verity functions explicitly.
+
+**Build phase** (``BOOTM_STATE_FINDOTHER`` → ``boot_get_loadable()``)
+
+1. After all loadable sub-images have been loaded,
+   ``fit_verity_build_cmdline()`` iterates the configuration's
+   ``loadables`` list.
+
+2. For each loadable that is an ``IH_TYPE_FILESYSTEM`` image **and**
+   contains a ``dm-verity`` child node, a dm-verity target specification is
+   built by the helper ``fit_verity_build_target()``.
+
+3. The dm-verity target references ``/dev/fitN``, where *N* is the
+   zero-based index of the loadable in the configuration.  This matches the
+   numbering used by the Linux FIT block driver.
+
+4. The resulting fragments are stored in ``struct bootm_headers``:
+
+   ``images->dm_mod_create``
+     The full dm-verity target table. Multiple targets are separated by ``;``.
+
+   ``images->dm_mod_waitfor``
+     Comma-separated list of ``/dev/fitN`` devices so the kernel waits for
+     the underlying FIT block devices to appear before activating
+     device-mapper.
+
+**Apply phase** (``BOOTM_STATE_OS_PREP``)
+
+5. Just before ``bootm_process_cmdline_env()`` processes the ``bootargs``
+   environment variable, ``fit_verity_apply_bootargs()`` appends the
+   ``dm-mod.create=`` and ``dm-mod.waitfor=`` parameters.
+
+**Bootmeth integration**
+
+  Because the fragments are stored in ``struct bootm_headers``, a boot
+  method can check ``fit_verity_active(images)`` between bootm state
+  invocations. A typical pattern splits ``bootm_run_states()`` into two
+  calls -- one for ``START|FINDOS|FINDOTHER|LOADOS`` and one for
+  ``OS_PREP|OS_GO`` -- and inspects ``fit_verity_active()`` in
+  between to decide whether to add a ``root=`` parameter pointing at the
+  dm-verity device.
+
+FIT image source (.its) example
+-------------------------------
+
+Below is a minimal ``.its`` file showing a kernel and a dm-verity-protected
+root filesystem packaged as a FIT. Only the three user-provided properties
+(``algo``, ``data-block-size``, ``hash-block-size``) are included; ``mkimage``
+computes and fills in ``digest``, ``salt``, ``num-data-blocks``, and
+``hash-start-block`` automatically (see `Generating verity metadata`_ below)::
+
+    /dts-v1/;
+
+    / {
+        description = "Kernel + dm-verity rootfs";
+        #address-cells = <1>;
+
+        images {
+            kernel {
+                description = "Linux kernel";
+                data = /incbin/("./Image.gz");
+                type = "kernel";
+                arch = "arm64";
+                os = "linux";
+                compression = "gzip";
+                load = <0x44000000>;
+                entry = <0x44000000>;
+                hash-1 {
+                    algo = "sha256";
+                };
+            };
+
+            fdt {
+                description = "Device tree blob";
+                data = /incbin/("./board.dtb");
+                type = "flat_dt";
+                arch = "arm64";
+                compression = "none";
+                hash-1 {
+                    algo = "sha256";
+                };
+            };
+
+            rootfs {
+                description = "SquashFS root filesystem";
+                data = /incbin/("./rootfs.squashfs");
+                type = "filesystem";
+                arch = "arm64";
+                compression = "none";
+                hash-1 {
+                    algo = "sha256";
+                };
+
+                dm-verity {
+                    algo = "sha256";
+                    data-block-size = <4096>;
+                    hash-block-size = <4096>;
+                };
+            };
+        };
+
+        configurations {
+            default = "config-1";
+            config-1 {
+                description = "Boot with dm-verity rootfs";
+                kernel = "kernel";
+                fdt = "fdt";
+                loadables = "rootfs";
+            };
+        };
+    };
+
+With this configuration U-Boot produces a kernel command line similar to::
+
+    dm-mod.create="rootfs,,, ro,0 <data_sectors> verity 1 \
+        /dev/fit0 /dev/fit0 4096 4096 3762 3762 sha256 \
+        8e6791637f93cbb81fc45299e203cbe85ca2e47a38f5051bddeece92d7b1c9f9 \
+        aa7b11f8db8fe2e5bfd4eca1d18a22b5de7ea39d2e1b93bb7272ce0c6ca3cc8e" \
+    dm-mod.waitfor=/dev/fit0
+
+dm-verity subnode properties
+----------------------------
+
+User-provided properties (required in the ``.its``):
+
+.. list-table::
+   :header-rows: 1
+   :widths: 20 15 65
+
+   * - Property
+     - Type
+     - Description
+   * - ``algo``
+     - string
+     - Hash algorithm name, e.g. ``"sha256"``.
+   * - ``data-block-size``
+     - u32
+     - Data block size in bytes (>= 512, typically 4096).
+   * - ``hash-block-size``
+     - u32
+     - Hash block size in bytes (>= 512, typically 4096).
+
+Computed properties (filled in by ``mkimage``):
+
+.. list-table::
+   :header-rows: 1
+   :widths: 20 15 65
+
+   * - Property
+     - Type
+     - Description
+   * - ``num-data-blocks``
+     - u32
+     - Number of data blocks in the filesystem image (computed from the
+       image size and ``data-block-size``).
+   * - ``hash-start-block``
+     - u32
+     - Offset in ``hash-block-size``-sized blocks from the start of the
+       sub-image to the root block of the hash tree.
+   * - ``digest``
+     - byte array
+     - Root hash of the Merkle tree, stored as raw bytes. Length must match
+       the output size of ``algo``.
+   * - ``salt``
+     - byte array
+     - Salt used when computing the Merkle tree, stored as raw bytes.
+
+These values are the same ones produced by ``veritysetup format`` and can
+typically be obtained from its output.
+The ``digest`` and ``salt`` byte arrays correspond to the hex-encoded
+``Root hash`` and ``Salt`` printed by ``veritysetup format``.
+
+Optional boolean properties (when present, they are collected and appended
+as dm-verity optional parameters with hyphens converted to underscores):
+
+.. list-table::
+   :header-rows: 1
+   :widths: 30 70
+
+   * - Property
+     - Description
+   * - ``restart-on-corruption``
+     - Restart the system on data corruption.
+   * - ``panic-on-corruption``
+     - Panic the system on data corruption.
+   * - ``restart-on-error``
+     - Restart the system on I/O error.
+   * - ``panic-on-error``
+     - Panic the system on I/O error.
+   * - ``check-at-most-once``
+     - Verify data blocks only on first read.
+
+
+Generating verity metadata
+--------------------------
+
+``mkimage`` automates the entire process. When it encounters a
+``dm-verity`` subnode, it:
+
+1. Writes the embedded image data to a temporary file.
+2. Runs ``veritysetup format`` with the user-supplied algorithm and
+   block sizes.
+3. Parses ``Root hash`` and ``Salt`` from ``veritysetup`` stdout.
+4. Reads back the expanded file (original data + Merkle hash tree) and
+   replaces the image's ``data`` property.
+5. Writes the computed ``digest``, ``salt``, ``num-data-blocks``, and
+   ``hash-start-block`` properties into the ``dm-verity`` subnode.
+
+Images with ``dm-verity`` subnodes **must** use external data layout
+(``mkimage -E``). ``mkimage`` will abort with an error if ``-E`` is
+not specified.
+
+Usage::
+
+    # Create the filesystem image
+    mksquashfs rootfs/ rootfs.squashfs -comp xz
+
+    # Build the FIT (dm-verity is computed automatically)
+    mkimage -E -f image.its image.itb
+
+``veritysetup`` (from the cryptsetup_ package) must be installed on
+the build host.
+
+.. _cryptsetup: https://gitlab.com/cryptsetup/cryptsetup
+
+.. note::
+
+   ``veritysetup format`` is invoked with ``--no-superblock``, so no
+   on-disk superblock is written between the data and hash regions.
+   The Merkle hash tree is appended directly to the image data within
+   the FIT external data section.  ``hash-start-block`` is therefore
+   computed as ``data_size / hash-block-size`` (the offset of the hash
+   region in units of ``hash-block-size``).  When ``data-block-size``
+   equals ``hash-block-size`` this happens to equal ``num-data-blocks``.
+
+Kconfig
+-------
+
+``CONFIG_FIT_VERITY``
+  Depends on ``CONFIG_FIT`` and ``CONFIG_OF_LIBFDT``.
+  When enabled, ``fit_verity_build_cmdline()`` and
+  ``fit_verity_apply_bootargs()`` are compiled into the boot path.
+  When disabled, the functions are static inlines returning 0, so there
+  is no code-size impact.  Works with both the ``bootm`` command and
+  BOOTSTD boot methods.
doc/usage/fit/index.rst +1 -0
index 6c78d8584ed..d17582b1d64 100644
@@ -11,6 +11,7 @@ images that it reads and boots. Documentation about FIT is available in
     :maxdepth: 1
 
     beaglebone_vboot
+    dm-verity
     howto
     kernel_fdt
     kernel_fdts_compressed
Signature · 1 line
2.54.0
#9 lore raw

PATCH v4 6/8 test: boot: add runtime unit test for fit_verity_build_cmdline()

In reply to Daniel Golle

Add test/boot/fit_verity.c with four tests that construct FIT blobs in memory and exercise fit_verity_build_cmdline().

---
v4: no changes
v3: replace literal property name strings with the FIT_VERITY_*_PROP
v2: new patch

 test/boot/Makefile     |   1 +
 test/boot/fit_verity.c | 306 +++++++++++++++++++++++++++++++++++++++++
 test/cmd_ut.c          |   2 +
 3 files changed, 309 insertions(+)
 create mode 100644 test/boot/fit_verity.c
test/boot/Makefile +1 -0
index 89538d4f0a6..d98f212b243 100644
@@ -15,6 +15,7 @@ endif
 ifdef CONFIG_SANDBOX
 obj-$(CONFIG_$(PHASE_)CMDLINE) += bootm.o
 endif
+obj-$(CONFIG_$(PHASE_)FIT_VERITY) += fit_verity.o
 obj-$(CONFIG_MEASURED_BOOT) += measurement.o
 
 ifdef CONFIG_OF_LIVE
test/boot/fit_verity.c new file +306 -0

306 lines not on this page · raw message

test/cmd_ut.c +2 -0
index 44e5fdfdaa6..d1b376f617c 100644
@@ -59,6 +59,7 @@ SUITE_DECL(env);
 SUITE_DECL(exit);
 SUITE_DECL(fdt);
 SUITE_DECL(fdt_overlay);
+SUITE_DECL(fit_verity);
 SUITE_DECL(font);
 SUITE_DECL(hush);
 SUITE_DECL(lib);
@@ -86,6 +87,7 @@ static struct suite suites[] = {
 	SUITE(exit, "shell exit and variables"),
 	SUITE(fdt, "fdt command"),
 	SUITE(fdt_overlay, "device tree overlays"),
+	SUITE(fit_verity, "FIT dm-verity cmdline generation"),
 	SUITE(font, "font command"),
 	SUITE(hush, "hush behaviour"),
 	SUITE(lib, "library functions"),
Signature · 1 line
2.54.0
#10 lore raw

PATCH v4 7/8 test: py: add mkimage dm-verity round-trip test

In reply to Daniel Golle

Add test/py/tests/test_fit_verity.py covering:
- mkimage writes correct dm-verity properties for matched and mismatched block sizes (4096/4096 and 4096/1024);
- veritysetup verify re-checks the digest against the .itb's external data section;
- mkimage rejects dm-verity images built without -E.

All tests are skipped if veritysetup is not installed on the host.

---
v4:
* verify the computed digest with veritysetup verify against the external data section
* parametrize test_mkimage_verity with matched and mismatched block sizes to exercise hash-start-block != num-data-blocks
* use run_and_log_expect_exception() with the expected diagnostic for the no-external-data case
v3: drop unused 'struct' import and the home-rolled have_veritysetup()
helper; use @pytest.mark.requiredtool('veritysetup') instead
v2: new patch

 test/py/tests/test_fit_verity.py | 175 +++++++++++++++++++++++++++++++
 1 file changed, 175 insertions(+)
 create mode 100644 test/py/tests/test_fit_verity.py
test/py/tests/test_fit_verity.py new file +175 -0
new file mode 100644
index 00000000000..5952c189858
@@ -0,0 +1,175 @@
+# SPDX-License-Identifier: GPL-2.0+
+#
+# Copyright 2026 Daniel Golle <[email protected]>
+
+"""
+Test mkimage dm-verity Merkle-tree generation
+
+Build a minimal .its with a dm-verity subnode (user-provided properties only),
+run mkimage -E, and verify that the computed properties (digest, salt,
+num-data-blocks, hash-start-block) are written into the resulting FIT.
+The computed digest is then re-verified by running ``veritysetup verify``
+against the external data section of the .itb.
+
+This test does not run the sandbox.  It only exercises the host tool 'mkimage'.
+Requires 'veritysetup' from the cryptsetup package on the build host.
+"""
+
+import os
+import struct
+import pytest
+import utils
+
+ITS_TEMPLATE = """\
+/dts-v1/;
+
+/ {
+    description = "dm-verity test";
+    #address-cells = <1>;
+
+    images {
+        rootfs {
+            description = "test filesystem";
+            data = /incbin/("./rootfs.bin");
+            type = "filesystem";
+            arch = "sandbox";
+            compression = "none";
+
+            dm-verity {
+                algo = "sha256";
+                data-block-size = <%d>;
+                hash-block-size = <%d>;
+            };
+        };
+    };
+
+    configurations {
+        default = "conf-1";
+        conf-1 {
+            description = "test config";
+            loadables = "rootfs";
+        };
+    };
+};
+"""
+
+def _fdt_totalsize(path):
+    """Read the totalsize field from an FDT header (offset 4, big-endian u32)."""
+    with open(path, 'rb') as f:
+        magic, totalsize = struct.unpack('>II', f.read(8))
+    assert magic == 0xd00dfeed, f'not an FDT: magic={magic:#x}'
+    return totalsize
+
+
+def _run_round_trip(ubman, tempdir, data_block_size, hash_block_size):
+    """Build a FIT with dm-verity, verify written properties, re-verify with veritysetup."""
+    mkimage = ubman.config.build_dir + '/tools/mkimage'
+
+    rootfs_file = os.path.join(tempdir, 'rootfs.bin')
+    its_file = os.path.join(tempdir, 'image.its')
+    fit_file = os.path.join(tempdir, 'image.itb')
+
+    # 64 data blocks of 0xa5
+    num_blocks = 64
+    data_size = data_block_size * num_blocks
+    with open(rootfs_file, 'wb') as f:
+        f.write(bytes([0xa5]) * data_size)
+
+    with open(its_file, 'w') as f:
+        f.write(ITS_TEMPLATE % (data_block_size, hash_block_size))
+
+    dtc_args = f'-I dts -O dtb -i {tempdir}'
+    utils.run_and_log(ubman,
+                      [mkimage, '-E', '-D', dtc_args, '-f', its_file, fit_file])
+
+    def fdt_get(node, prop):
+        val = utils.run_and_log(ubman, f'fdtget {fit_file} {node} {prop}')
+        return val.strip()
+
+    def fdt_get_hex(node, prop):
+        val = utils.run_and_log(ubman, f'fdtget -tbx {fit_file} {node} {prop}')
+        return ''.join(b.zfill(2) for b in val.strip().split())
+
+    verity_path = '/images/rootfs/dm-verity'
+
+    assert fdt_get(verity_path, 'algo') == 'sha256'
+    assert int(fdt_get(verity_path, 'data-block-size')) == data_block_size
+    assert int(fdt_get(verity_path, 'hash-block-size')) == hash_block_size
+
+    nblk = int(fdt_get(verity_path, 'num-data-blocks'))
+    assert nblk == num_blocks, f'num-data-blocks {nblk} != {num_blocks}'
+
+    hblk = int(fdt_get(verity_path, 'hash-start-block'))
+    # With --no-superblock, hash-start-block = data_size / hash-block-size
+    assert hblk == data_size // hash_block_size, \
+        f'hash-start-block {hblk} != {data_size // hash_block_size}'
+
+    digest = fdt_get_hex(verity_path, 'digest')
+    assert len(digest) == 64 and digest != '0' * 64
+    salt = fdt_get_hex(verity_path, 'salt')
+    assert len(salt) == 64
+
+    # Re-verify the digest with veritysetup against the .itb's external data.
+    # With -E, image data sits after the FIT FDT at (fdt_totalsize + data-offset).
+    data_offset = int(fdt_get('/images/rootfs', 'data-offset'))
+    data_size_full = int(fdt_get('/images/rootfs', 'data-size'))
+    ext_pos = _fdt_totalsize(fit_file) + data_offset
+    expanded = os.path.join(tempdir, 'expanded.bin')
+    with open(fit_file, 'rb') as src, open(expanded, 'wb') as dst:
+        src.seek(ext_pos)
+        dst.write(src.read(data_size_full))
+
+    utils.run_and_log(ubman, [
+        'veritysetup', 'verify', expanded, expanded, digest,
+        '--no-superblock',
+        f'--data-block-size={data_block_size}',
+        f'--hash-block-size={hash_block_size}',
+        f'--data-blocks={nblk}',
+        '--hash=sha256',
+        f'--salt={salt}',
+        f'--hash-offset={data_size}',
+    ])
+
+
[email protected]('dtc')
[email protected]('fdtget')
[email protected]('veritysetup')
[email protected]('data_block_size,hash_block_size,subdir', [
+    (4096, 4096, 'verity-equal'),
+    (4096, 1024, 'verity-unequal'),
+])
+def test_mkimage_verity(ubman, data_block_size, hash_block_size, subdir):
+    """mkimage writes correct dm-verity properties and the digest verifies.
+
+    Run with matching and mismatched block sizes so the
+    ``hash-start-block != num-data-blocks`` path is exercised.
+    """
+    tempdir = os.path.join(ubman.config.result_dir, subdir)
+    os.makedirs(tempdir, exist_ok=True)
+    _run_round_trip(ubman, tempdir, data_block_size, hash_block_size)
+
+
[email protected]('dtc')
[email protected]('veritysetup')
+def test_mkimage_verity_requires_external(ubman):
+    """mkimage rejects dm-verity without -E with the expected diagnostic."""
+
+    mkimage = ubman.config.build_dir + '/tools/mkimage'
+    tempdir = os.path.join(ubman.config.result_dir, 'verity_no_ext')
+    os.makedirs(tempdir, exist_ok=True)
+
+    rootfs_file = os.path.join(tempdir, 'rootfs.bin')
+    its_file = os.path.join(tempdir, 'image.its')
+    fit_file = os.path.join(tempdir, 'image.itb')
+
+    with open(rootfs_file, 'wb') as f:
+        f.write(bytes([0xa5]) * 4096 * 8)
+
+    with open(its_file, 'w') as f:
+        f.write(ITS_TEMPLATE % (4096, 4096))
+
+    dtc_args = f'-I dts -O dtb -i {tempdir}'
+    utils.run_and_log_expect_exception(
+        ubman,
+        [mkimage, '-D', dtc_args, '-f', its_file, fit_file],
+        1, 'dm-verity requires external data')
Signature · 1 line
2.54.0
#11 lore raw

PATCH v4 8/8 configs: sandbox: enable CONFIG_FIT_VERITY

In reply to Daniel Golle

Enable FIT_VERITY in the sandbox configs that build a full U-Boot binary so CI may exercise the new dm-verity unit test (test/boot/fit_verity.c) and the mkimage pytest (test/py/tests/test_fit_verity.py) introduced earlier in this series.

---
v4: new patch

 configs/sandbox64_defconfig        | 1 +
 configs/sandbox_defconfig          | 1 +
 configs/sandbox_flattree_defconfig | 1 +
 3 files changed, 3 insertions(+)
configs/sandbox64_defconfig +1 -0
index 5bf6146b1d0..f5d5b21e733 100644
@@ -18,6 +18,7 @@ CONFIG_EFI_RT_VOLATILE_STORE=y
 CONFIG_BUTTON_CMD=y
 CONFIG_FIT=y
 CONFIG_FIT_SIGNATURE=y
+CONFIG_FIT_VERITY=y
 CONFIG_FIT_VERBOSE=y
 CONFIG_LEGACY_IMAGE_FORMAT=y
 CONFIG_BOOTSTAGE=y
configs/sandbox_defconfig +1 -0
index ba800f7d19d..ff4a6eb285a 100644
@@ -22,6 +22,7 @@ CONFIG_BUTTON_CMD=y
 CONFIG_FIT=y
 CONFIG_FIT_SIGNATURE=y
 CONFIG_FIT_CIPHER=y
+CONFIG_FIT_VERITY=y
 CONFIG_FIT_VERBOSE=y
 CONFIG_BOOTMETH_ANDROID=y
 CONFIG_BOOTMETH_RAUC=y
configs/sandbox_flattree_defconfig +1 -0
index a14dd5beb31..4ad2bb01673 100644
@@ -14,6 +14,7 @@ CONFIG_EFI_CAPSULE_CRT_FILE="board/sandbox/capsule_pub_key_good.crt"
 CONFIG_BUTTON_CMD=y
 CONFIG_FIT=y
 CONFIG_FIT_SIGNATURE=y
+CONFIG_FIT_VERITY=y
 CONFIG_FIT_VERBOSE=y
 CONFIG_LEGACY_IMAGE_FORMAT=y
 CONFIG_BOOTSTAGE=y
Signature · 1 line
2.54.0
#7 lore raw

Re: [PATCH v4 5/8] doc: fit: add dm-verity boot parameter documentation

In reply to Daniel Golle

Am 13. Mai 2026 04:09:29 MESZ schrieb Daniel Golle <[email protected]>:

Quoted 52 lines

Add documentation for CONFIG_FIT_VERITY which allows U-Boot to construct dm-mod.create= and dm-mod.waitfor= kernel command-line parameters from dm-verity metadata embedded in FIT filesystem sub-images.

The new document covers the relationship between FIT loadable indices and the /dev/fitN block devices that the Linux uImage.FIT block driver creates, provides a complete .its example with a dm-verity-protected SquashFS root filesystem, describes all required and optional dm-verity subnode properties and explains how mkimage generates the verity metadata automatically.

dm-verity is only supported for external-data FIT images (mkimage -E); mkimage aborts with an error if the flag is omitted.

---
v4: no changes
v3: clarify that hash-start-block only equals num-data-blocks when
data-block-size == hash-block-size; in the general case it is data_size / hash-block-size
v2: trim minimal .its example to user-provided properties only and
remove stale references to a verity superblock

doc/usage/fit/dm-verity.rst | 284 ++++++++++++++++++++++++++++++++++++
doc/usage/fit/index.rst | 1 +

2 files changed, 285 insertions(+)

create mode 100644 doc/usage/fit/dm-verity.rst

doc/usage/fit/dm-verity.rst new file +16 -0
new file mode 100644
index 00000000000..eddce9e7cf7
@@ -0,0 +1,284 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+FIT dm-verity Boot Parameters
+=============================
+
+Introduction
+------------
+
+Linux's dm-verity device-mapper target provides transparent integrity
+checking of block devices using a Merkle tree. It is commonly used to
+protect read-only root filesystems such as SquashFS images.
+
+When a FIT image packages the root filesystem as a loadable sub-image of
+type ``filesystem`` (``IH_TYPE_FILESYSTEM``), the verity metadata can be
+stored alongside the image data in a ``dm-verity`` subnode. U-Boot reads
+this metadata at boot time and generates the kernel command-line parameters

doc/usage/fit/dm-verity.rst line 26

Quoted 10 lines
doc/usage/fit/dm-verity.rst new file +10 -0
+that Linux needs to activate the verity target, eliminating the need for
+an initramfs or userspace helper to set up dm-verity.
+
+This feature is enabled by ``CONFIG_FIT_VERITY`` (see ``boot/Kconfig``).
+
+Prerequisites
+-------------
+
+* **Linux uImage.FIT block driver** – the kernel must include the FIT block
+  driver that exposes loadable sub-images as ``/dev/fit0``, ``/dev/fit1``,

The dtb file format of FIT images only guarantees 4 byte alignment. Does that match with the requirement of file-system drivers including dma access if the FIT is for example on eMMC? Or do we need a mechanism to enforce higher alignment in FIT images?

Best regards

Heinrich

Quoted 270 lines
doc/usage/fit/dm-verity.rst new file +258 -0
+  etc.  The driver assigns device numbers in the order loadables appear in
+  the FIT configuration.
+
+* **dm-verity support in the kernel** – ``CONFIG_DM_VERITY`` must be
+  enabled so the kernel can process the ``dm-mod.create=`` parameter.
+
+* **CONFIG_FIT_VERITY** enabled in U-Boot.
+
+How it works
+------------
+
+The implementation is split into a **build** phase and an **apply** phase,
+both of which run automatically within the ``bootm`` state machine. No boot
+method needs to call verity functions explicitly.
+
+**Build phase** (``BOOTM_STATE_FINDOTHER`` → ``boot_get_loadable()``)
+
+1. After all loadable sub-images have been loaded,
+   ``fit_verity_build_cmdline()`` iterates the configuration's
+   ``loadables`` list.
+
+2. For each loadable that is an ``IH_TYPE_FILESYSTEM`` image **and**
+   contains a ``dm-verity`` child node, a dm-verity target specification is
+   built by the helper ``fit_verity_build_target()``.
+
+3. The dm-verity target references ``/dev/fitN``, where *N* is the
+   zero-based index of the loadable in the configuration.  This matches the
+   numbering used by the Linux FIT block driver.
+
+4. The resulting fragments are stored in ``struct bootm_headers``:
+
+   ``images->dm_mod_create``
+     The full dm-verity target table. Multiple targets are separated by ``;``.
+
+   ``images->dm_mod_waitfor``
+     Comma-separated list of ``/dev/fitN`` devices so the kernel waits for
+     the underlying FIT block devices to appear before activating
+     device-mapper.
+
+**Apply phase** (``BOOTM_STATE_OS_PREP``)
+
+5. Just before ``bootm_process_cmdline_env()`` processes the ``bootargs``
+   environment variable, ``fit_verity_apply_bootargs()`` appends the
+   ``dm-mod.create=`` and ``dm-mod.waitfor=`` parameters.
+
+**Bootmeth integration**
+
+  Because the fragments are stored in ``struct bootm_headers``, a boot
+  method can check ``fit_verity_active(images)`` between bootm state
+  invocations. A typical pattern splits ``bootm_run_states()`` into two
+  calls -- one for ``START|FINDOS|FINDOTHER|LOADOS`` and one for
+  ``OS_PREP|OS_GO`` -- and inspects ``fit_verity_active()`` in
+  between to decide whether to add a ``root=`` parameter pointing at the
+  dm-verity device.
+
+FIT image source (.its) example
+-------------------------------
+
+Below is a minimal ``.its`` file showing a kernel and a dm-verity-protected
+root filesystem packaged as a FIT. Only the three user-provided properties
+(``algo``, ``data-block-size``, ``hash-block-size``) are included; ``mkimage``
+computes and fills in ``digest``, ``salt``, ``num-data-blocks``, and
+``hash-start-block`` automatically (see `Generating verity metadata`_ below)::
+
+    /dts-v1/;
+
+    / {
+        description = "Kernel + dm-verity rootfs";
+        #address-cells = <1>;
+
+        images {
+            kernel {
+                description = "Linux kernel";
+                data = /incbin/("./Image.gz");
+                type = "kernel";
+                arch = "arm64";
+                os = "linux";
+                compression = "gzip";
+                load = <0x44000000>;
+                entry = <0x44000000>;
+                hash-1 {
+                    algo = "sha256";
+                };
+            };
+
+            fdt {
+                description = "Device tree blob";
+                data = /incbin/("./board.dtb");
+                type = "flat_dt";
+                arch = "arm64";
+                compression = "none";
+                hash-1 {
+                    algo = "sha256";
+                };
+            };
+
+            rootfs {
+                description = "SquashFS root filesystem";
+                data = /incbin/("./rootfs.squashfs");
+                type = "filesystem";
+                arch = "arm64";
+                compression = "none";
+                hash-1 {
+                    algo = "sha256";
+                };
+
+                dm-verity {
+                    algo = "sha256";
+                    data-block-size = <4096>;
+                    hash-block-size = <4096>;
+                };
+            };
+        };
+
+        configurations {
+            default = "config-1";
+            config-1 {
+                description = "Boot with dm-verity rootfs";
+                kernel = "kernel";
+                fdt = "fdt";
+                loadables = "rootfs";
+            };
+        };
+    };
+
+With this configuration U-Boot produces a kernel command line similar to::
+
+    dm-mod.create="rootfs,,, ro,0 <data_sectors> verity 1 \
+        /dev/fit0 /dev/fit0 4096 4096 3762 3762 sha256 \
+        8e6791637f93cbb81fc45299e203cbe85ca2e47a38f5051bddeece92d7b1c9f9 \
+        aa7b11f8db8fe2e5bfd4eca1d18a22b5de7ea39d2e1b93bb7272ce0c6ca3cc8e" \
+    dm-mod.waitfor=/dev/fit0
+
+dm-verity subnode properties
+----------------------------
+
+User-provided properties (required in the ``.its``):
+
+.. list-table::
+   :header-rows: 1
+   :widths: 20 15 65
+
+   * - Property
+     - Type
+     - Description
+   * - ``algo``
+     - string
+     - Hash algorithm name, e.g. ``"sha256"``.
+   * - ``data-block-size``
+     - u32
+     - Data block size in bytes (>= 512, typically 4096).
+   * - ``hash-block-size``
+     - u32
+     - Hash block size in bytes (>= 512, typically 4096).
+
+Computed properties (filled in by ``mkimage``):
+
+.. list-table::
+   :header-rows: 1
+   :widths: 20 15 65
+
+   * - Property
+     - Type
+     - Description
+   * - ``num-data-blocks``
+     - u32
+     - Number of data blocks in the filesystem image (computed from the
+       image size and ``data-block-size``).
+   * - ``hash-start-block``
+     - u32
+     - Offset in ``hash-block-size``-sized blocks from the start of the
+       sub-image to the root block of the hash tree.
+   * - ``digest``
+     - byte array
+     - Root hash of the Merkle tree, stored as raw bytes. Length must match
+       the output size of ``algo``.
+   * - ``salt``
+     - byte array
+     - Salt used when computing the Merkle tree, stored as raw bytes.
+
+These values are the same ones produced by ``veritysetup format`` and can
+typically be obtained from its output.
+The ``digest`` and ``salt`` byte arrays correspond to the hex-encoded
+``Root hash`` and ``Salt`` printed by ``veritysetup format``.
+
+Optional boolean properties (when present, they are collected and appended
+as dm-verity optional parameters with hyphens converted to underscores):
+
+.. list-table::
+   :header-rows: 1
+   :widths: 30 70
+
+   * - Property
+     - Description
+   * - ``restart-on-corruption``
+     - Restart the system on data corruption.
+   * - ``panic-on-corruption``
+     - Panic the system on data corruption.
+   * - ``restart-on-error``
+     - Restart the system on I/O error.
+   * - ``panic-on-error``
+     - Panic the system on I/O error.
+   * - ``check-at-most-once``
+     - Verify data blocks only on first read.
+
+
+Generating verity metadata
+--------------------------
+
+``mkimage`` automates the entire process. When it encounters a
+``dm-verity`` subnode, it:
+
+1. Writes the embedded image data to a temporary file.
+2. Runs ``veritysetup format`` with the user-supplied algorithm and
+   block sizes.
+3. Parses ``Root hash`` and ``Salt`` from ``veritysetup`` stdout.
+4. Reads back the expanded file (original data + Merkle hash tree) and
+   replaces the image's ``data`` property.
+5. Writes the computed ``digest``, ``salt``, ``num-data-blocks``, and
+   ``hash-start-block`` properties into the ``dm-verity`` subnode.
+
+Images with ``dm-verity`` subnodes **must** use external data layout
+(``mkimage -E``). ``mkimage`` will abort with an error if ``-E`` is
+not specified.
+
+Usage::
+
+    # Create the filesystem image
+    mksquashfs rootfs/ rootfs.squashfs -comp xz
+
+    # Build the FIT (dm-verity is computed automatically)
+    mkimage -E -f image.its image.itb
+
+``veritysetup`` (from the cryptsetup_ package) must be installed on
+the build host.
+
+.. _cryptsetup: https://gitlab.com/cryptsetup/cryptsetup
+
+.. note::
+
+   ``veritysetup format`` is invoked with ``--no-superblock``, so no
+   on-disk superblock is written between the data and hash regions.
+   The Merkle hash tree is appended directly to the image data within
+   the FIT external data section.  ``hash-start-block`` is therefore
+   computed as ``data_size / hash-block-size`` (the offset of the hash
+   region in units of ``hash-block-size``).  When ``data-block-size``
+   equals ``hash-block-size`` this happens to equal ``num-data-blocks``.
+
+Kconfig
+-------
+
+``CONFIG_FIT_VERITY``
+  Depends on ``CONFIG_FIT`` and ``CONFIG_OF_LIBFDT``.
+  When enabled, ``fit_verity_build_cmdline()`` and
+  ``fit_verity_apply_bootargs()`` are compiled into the boot path.
+  When disabled, the functions are static inlines returning 0, so there
+  is no code-size impact.  Works with both the ``bootm`` command and
+  BOOTSTD boot methods.
doc/usage/fit/index.rst +1 -0
index 6c78d8584ed..d17582b1d64 100644
@@ -11,6 +11,7 @@ images that it reads and boots. Documentation about FIT is available in
    :maxdepth: 1
 
    beaglebone_vboot
+    dm-verity
    howto
    kernel_fdt
    kernel_fdts_compressed
#8 lore raw

Re: [PATCH v4 5/8] doc: fit: add dm-verity boot parameter documentation

Quoted 8 lines · Heinrich Schuchardt

Am 13. Mai 2026 04:09:29 MESZ schrieb Daniel Golle <[email protected]>:

Quoted 7 lines

Add documentation for CONFIG_FIT_VERITY which allows U-Boot to construct dm-mod.create= and dm-mod.waitfor= kernel command-line parameters from dm-verity metadata embedded in FIT filesystem sub-images.

[...]

Quoted 8 lines

doc/usage/fit/dm-verity.rst line 26

Quoted 5 lines
doc/usage/fit/dm-verity.rst new file +5 -0
+Prerequisites
+-------------
+
+* **Linux uImage.FIT block driver** – the kernel must include the FIT block
+  driver that exposes loadable sub-images as ``/dev/fit0``, ``/dev/fit1``,

The dtb file format of FIT images only guarantees 4 byte alignment. Does that match with the requirement of file-system drivers including dma access if the FIT is for example on eMMC? Or do we need a mechanism to enforce higher alignment in FIT images?

The fitblk driver requires the 'filesystem' image to start and end on block boundaries of the underlying block device. As the 'filesystem' image is outside of the FIT structure itself (external data) this can be achieved by having mkimage -E -B 0x1000.

This is a restriction of the current implementation of the fitblk driver to avoid the complexity (and computation overhead) which comes with unaligned access (a lot of memcpy, basically...). Future implementations may no longer have that restriction, while of course performance will always slightly suffer from the image not being aligned with the block size of the lower device.

Hence I consider this current resitriction something to be documented along with the fitblk driver, and outside of the scope of what U-Boot itself is involved with.

Reviewed-by on v4 4/8
#5 lore raw

Re: [PATCH v4 4/8] tools: mkimage: add dm-verity Merkle-tree generation

In reply to Daniel Golle

Hi Daniel,

Quoted 17 lines · Daniel Golle

tools: mkimage: add dm-verity Merkle-tree generation

When mkimage encounters a dm-verity subnode inside a component image node it now automatically invokes veritysetup(8) with --no-superblock to generate the Merkle hash tree, screen-scrapes the Root hash and Salt from the tool output, and writes the computed properties back into the FIT blob.

The user only needs to specify algorithm, data-block-size, and hash-block-size in the ITS; mkimage fills in digest, salt, num-data-blocks, and hash-start-block. Because --no-superblock is used, hash-start-block equals num-data-blocks with no off-by-one.

The image data property is replaced with the expanded content (original data followed directly by the hash tree) so that subsequent hash and signature subnodes operate on the complete image.

Quoted 8 lines

fit_image_add_verification_data() is restructured into two passes:
dm-verity first (may grow data), then hashes and signatures.

[...]

tools/fit_image.c | 116 +++++++++++++++++-

 tools/image-host.c | 349 ++++++++++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 455 insertions(+), 10 deletions(-)

Thoughts below

tools/image-host.c int fit_image_cipher_data(const char *keydir, void *keydest, · line 632

Quoted 6 lines
tools/image-host.c +4 -0
@@ -626,6 +629,310 @@ int fit_image_cipher_data(const char *keydir, void *keydest,
+static int fit_image_process_verity(void *fit, const char *image_name,
+                                 int image_noffset, int verity_noffset,
+                                 const void *data, size_t data_size,
+                                 void **expanded_data, size_t *expanded_size)

Please drop image_noffset - it is unused.

Quoted 6 lines
tools/image-host.c +4 -0
@@ -626,6 +629,310 @@ int fit_image_cipher_data(const char *keydir, void *keydest,
+     {
+             static const char * const valid_algos[] = {
+                     'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
+                     'ripemd160', 'whirlpool',

tools/image-host.c int fit_image_cipher_data(const char *keydir, void *keydest, · line 642

Quoted 10 lines
tools/image-host.c +10 -0
+                     'sha3-224', 'sha3-256', 'sha3-384', 'sha3-512',
+                     'stribog256', 'stribog512',
+                     'sm3',
+                     /* blake2b/blake2s with explicit digest sizes */
+                     'blake2b-160', 'blake2b-256', 'blake2b-384',
+                     'blake2b-512',
+                     'blake2s-128', 'blake2s-160', 'blake2s-224',
+                     'blake2s-256',
+                     NULL
+             };

This list will drift out of sync with what veritysetup supports, and users get a misleading 'Unsupported dm-verity hash algorithm' from mkimage when veritysetup would accept it.

The only reason for valid_algos[] is shell-injection avoidance from popen, right?. I'd much rather see fork()/execvp() used directly: pass the algo as an argv[] element and the list disappears. What do you think?

tools/image-host.c int fit_image_cipher_data(const char *keydir, void *keydest, · line 634

Quoted 8 lines
tools/image-host.c +6 -0
@@ -626,6 +629,310 @@ int fit_image_cipher_data(const char *keydir, void *keydest,
+     /*
+      * Stash the temp-file path so that fit_extract_data() can use
+      * the expanded content for the external-data section.
+      */
+     ret = fdt_setprop_string(fit, verity_noffset,
+                              'verity-data-file', tmpfile);

Communicating a host-side tmpfile path through the FIT blob leaks a transient filesystem detail into the FDT, and the in-memory expanded buffer and on-disk copy of the same bytes coexist. Since you already return expanded_data/expanded_size to the caller, can fit_extract_data() consume that buffer directly? That removes both verity-data-file and the second read in fit_copy_image_data().

tools/image-host.c int fit_image_add_verification_data(const char *keydir, const char *keyfile, · line 984

Quoted 12 lines
tools/image-host.c +4 -1
@@ -667,9 +976,12 @@ int fit_image_add_verification_data(const char *keydir, const char *keyfile,
-             if (ret < 0)
+             if (ret < 0) {
+                     free(verity_data);
                      return ret;
+             }
      }
 
+     free(verity_data);
      return 0;
 }

The temp file is only unlinked by fit_copy_image_data() on the happy path. If pass 2 fails, or mkimage aborts before fit_extract_data() runs, the tmpfile is leaked in /tmp. Please also unlink() on the error return path (or drop the tmpfile mechanism - see other comment). We try to have a blank line before the final return in a function.

tools/image-host.c int fit_image_cipher_data(const char *keydir, void *keydest, · line 629

Quoted 3 lines
tools/image-host.c +1 -0
@@ -626,6 +629,310 @@ int fit_image_cipher_data(const char *keydir, void *keydest,
+     int data_block_size, hash_block_size;

The v3 changelog notes these moved to unsigned int on the runtime side
- please apply the same here for consistency, otherwise a malformed .its with a huge u32 sneaks through fdt32_to_cpu() as a negative int and the >= 512 check fires for the wrong reason.

Regards,
Simon