Skip to contentSkip to conversation

Add support for structured tags and v18 dtb version

PATCH Superseded Herve Codina 3 participants 107 messages Aug 26 – Nov 2 Arm/Amlogic Meson SoC support Page 1 of 2

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v3 cover Add support for structured tags and v18 dtb version

Previously, I sent a RFC series related to support for metadata and addon device-trees [1].

During the discussion the concept of structured tags and "unknown" tags emerged as well as the need to have them handled as a prerequisite of support for metadata and addon.

The conclusion was the need for a new dtb version (v18) with support for:
- Structured tags and based on them, "unknown" tags.
Those structured tags allow to have an standardized definition of tags with the capability of skipping a tag and its related data when a "unknown" tag is incountered by a given version of libfdt, dtc and tools. Those "unknown" tags are tags defined in future versions. Even if they exact meaning is unknown for an 'old' version, they structure is understood and the 'old' version can skip them without any errors if allowed.

- Flags in the dtb header (dt_flags).
The goal of this field is to have a placeholder to specify the type of dtb we are dealing with. For instance, addons dtb will set a flag in this placeholder

- A last compatible version for writing purpose.
The goal of the new dtb header field (last_comp_version_w) is to disable globally any modification. It works similarly to last_comp_version but for modification. It can be used to avoid any modification that could be done by an 'old' version and could lead to inconsistencies between the modification itself and some "unknown" tags.

This current series implements those features and leads to the v18 dtb version.

First patch is a fix/improvement of fdtget. IMHO, this patch could be taken even if other patches in the series lead to discussion.

Patches 2 to 4 add support (and update tests) for a possible FDT_NOP tag at offset 0. Here also, those patches are fixes patches.

Patch 5 is a preparation patch improving the test treegen tool.

Patch 6 introduces the structured tags. The patch gives definitions needed to handle those tags.

Patches 7, 8 and 9 handles "unknown" tags in fdtdump, dtc and libfdt. This is the reading part implementation related to "unknown" tags in tools and lib.

Patch 9 to 13 are preparation commits for patch 14 and patch 14 itself is handling modifications (writing part) when unknown tags are involved.

The last patch (patch 15) bumps the dtb version including changes that cannot be moved out of the version bump without having a v18 without all expected features.

Also, several tests are added as soon as the related feature is supported. Those tests are part of the last commit adding the feature.

As already said, this current series is a prerequisite to the support for metadata and addons. The RFC series related to metadata and addons
[1] will be rebased on top of this prerequisite. Please, keep that in mind for the review of this current prerequisite series.

[1] https://lore.kernel.org/all/[email protected]/

This v3 iteration is rebased on top of the last upstream code with also several additional modification mostly related to:
- feedback received on v2
- nopulate test improvement (FDT_NODE at offset 0)
- wip (write in place) modification missed in previous iteration

Best regards,
Hervé

Changes:

v2 -> v3
v2: https://lore.kernel.org/devicetree-compiler/[email protected]/

Rebase on top of the last master branch of the dtc repository.

Even if Frank Li has sent his 'Reviewed-by' tag on all v2 patches, his 'Reviewed-by' tag is not added on patches having substantial modification in this v3.

- Patch 1 (New patch):
Remove open coded loops in fdtget.

- Patch 2 (patch 1 and 2 in v2):
Squash v2 patch 1 and patch 2
Rename fdt_first_node() to fdt_root_offset()
Make fdt_root_offset() accessible from users of libfdt library. Fix libfdt functions that must take care of root node offset vs offset 0 (identified thanks to nopulate update and missed in v2):
- fdt_get_name(),
- fdt_first_property_offset(),
- fdt_supernode_atdepth_offset(),
- fdt_node_depth(),
- fdt_add_property_().
Update commit log
Add 'Reviewed-by: Frank Li'

- Patch 3 (new patch):
Update tests to avoid considering offset 0 as the expected offset for the root node.

- Patch 4 (new patch):
Improve nopulate to add a FDT_NOP tag at offset 0 (i.e. before the root node).

- Patch 5 (patch 3 in v2)
Port modification done on tree.S in v2 to the treegen tool

- Patch 6 (patch 4 in v2)
Force structured tags to be unsigned. This avoids later signed/unsigned mismatch.
Add 'Reviewed-by: Frank Li'

- Patch 7 (patch 5 in v2)
Use treegen tool to generate unknown_tags_can_skip.dtb and unknown_tags_no_skip.dtb.
Slightly modified unknown_tags_can_skip.dtb content. Add 'Reviewed-by: Frank Li'

- Patch 8 (patch 6 in v2)
Update expected dtbs due to slightly modification in unknown_tags_can_skip.dtb
Add 'Reviewed-by: Frank Li'

- Patch 9 (patch 7 in v2)
Rename fdt_is_unknown_tag() to fdt_tag_is_unknown() Add 'Reviewed-by: Frank Li'

- Patch 10 (patch 8 in v2)
Add 'Reviewed-by: Frank Li'

- Patch 11 (New patch)
Introduce fdt_getprop_by_offset_w() and its related test. This new function is needed for later fdt_wip modifications.

- Patch 12 (New patch)
Introduce fdt_getprop_offset_namelen() and its simple variant fdt_getprop_offset(). This new function is needed for later fdt_wip modifications

- Patch 13 (New patch)
Introduce wip_func, a test utility to call wip (write inplace) functions family. This allows to write test with custom scenario when unknown tags are involved.

- Patch 14 (patch 9 in v2)
Handle modification done using inplace functions (fdt_wip.c). Those were missed in previous v2.
Add a test involving wip functions when unknown tags are present. Update expected dtbs due to slightly modification in unknown_tags_can_skip.dtb

- Patch 15 (patch 10 in v2)
Add a test for the dt_flags default value
Update header generation in treegen tool and use treegen tool to generate last_comp_version_w.dtb
Add 'Reviewed-by: Frank Li'

v1 -> v2
v1: https://lore.kernel.org/devicetree-compiler/[email protected]/T/#t

Rebase on top of the last master branch of the dtc repository. Remove the RFC tag.

- Patches 1, 2, 3, 4 and 7 in v1: Removed
Already applied.

- Patch 1 (5 in v1)
Update the commit log.

- Patch 2 (6 in v1)
Fix a typo in the commit log.
Add a comment related to 'offset <= 0' in fdt_next_node().

- Patch 3 (8 in v1)
No change

- Patch 4 (9 in v1)
Fix typos in commit log.
Replace DATA_LNG_ENCODING by DATA_LEN_ENCODING in commit log. Use SKIP_SAFE instead of CAN_SKIP in commit log.
Rename FDT_TAG_DATA_LNG to FDT_TAG_DATA_VARLEN in tags definition. Rename FDT_TEST_LNG_CAN_SKIP to FDT_TEST_VARLEN_CAN_SKIP.

- Patch 5 (10 in v1)
Use FDT_TAG_DATA_VARLEN instead of FDT_TAG_DATA_LNG.
Use FDT_TEST_VARLEN_CAN_SKIP instead of FDT_TEST_LNG_CAN_SKIP. Update values used in the unknown_tags_can_skip dtb test file. Use 'len' instead of 'lng'
Update the '-uu' option help message.
Update the fdtdump test to be stricter (avoid removing some specific comments related to unknown tags in sed command used in the test).

- Patch 6 (11 in v1)
Use FDT_TAG_DATA_VARLEN instead of FDT_TAG_DATA_LNG. Update the dtc test due to unknown_tags_can_skip dtb changes. Add 'Reviewed-by: Luca Ceresoli'

- Patch 7 (12 in v1)
Replace fdt_get_next() by fdt_next_tag() in commit title and log. Fix a typo in commit log.
Use FDT_TAG_DATA_VARLEN instead of FDT_TAG_DATA_LNG. Update the fdtget test due to unknown_tags_can_skip dtb changes. Add 'Reviewed-by: Luca Ceresoli'

- Patch 8 (13 in v1)
Fix commit log.
Add 'Reviewed-by: Luca Ceresoli'

- Patch 9 (14 in v1)
Update the fdtput test due to unknown_tags_can_skip dtb and fdtdump changes.
Add a missing ')' in commit log
Add 'Reviewed-by: Luca Ceresoli'

- Patch 10 (15 in v1)
Fix typos and clarify several parts of the commit log.

Herve Codina (15):
fdtget: Use libfdt iterators instead of open coded loops
libfdt: Don't assume the root node is available at offset 0
tests: Don't assume the root node is available at offset 0 tests/nopulate: Add a FDT_NOP before the root node
tests: treegen: Introduce emit_fdt_header_vers() Introduce structured tag value definition
fdtdump: Handle unknown tags
flattree: Handle unknown tags
libfdt: Handle unknown tags in fdt_next_tag()
libfdt: Introduce fdt_ptr_offset_()
libfdt: Introduce fdt_getprop_by_offset_w()
libfdt: Introduce fdt_getprop_offset_namelen()
tests: Add wip_func utility
libfdt: Handle unknown tags on dtb modifications Introduce v18 dtb version

 dtc.h                                         |   2 +-
 fdtdump.c                                     |  53 ++++-
 fdtget.c                                      |  73 ++----
 flattree.c                                    | 102 +++++++-
 libfdt/fdt.c                                  | 114 ++++++++-
 libfdt/fdt.h                                  |  28 +++
 libfdt/fdt_ro.c                               |  70 +++++-
 libfdt/fdt_rw.c                               | 161 ++++++++++++-
 libfdt/fdt_sw.c                               |   3 +
 libfdt/fdt_wip.c                              |  28 ++-
 libfdt/libfdt.h                               |  28 ++-
 libfdt/libfdt_internal.h                      |  19 ++
 libfdt/version.lds                            |   1 +
 pylibfdt/libfdt.i                             |  18 ++
 tests/.gitignore                              |   1 +
 tests/Makefile.tests                          |   8 +-
 tests/dtflags_default.dtb.expect              |   1 +
 tests/dtflags_default.dts                     |  10 +
 tests/get_prop_offset_w.c                     |  84 +++++++
 tests/meson.build                             |   5 +
 tests/node_offset_by_compatible.c             |   4 +-
 tests/node_offset_by_prop_value.c             |  11 +-
 tests/nopulate.c                              |   3 +
 tests/path_offset.c                           |  13 +-
 tests/pylibfdt_tests.py                       |  10 +-
 tests/root_node.c                             |   6 +-
 tests/run_tests.sh                            | 152 +++++++++++-
 tests/tests.h                                 |   1 +
 tests/testutils.c                             |  20 +-
 tests/treegen.c                               | 219 +++++++++++++++++-
 tests/unknown_tags_can_skip.dtb.dts.expect    |  19 ++
 tests/unknown_tags_can_skip.dtb.expect        |  29 +++
 ...own_tags_can_skip.fdtput.test.dtb.0.expect |  32 +++
 ...own_tags_can_skip.fdtput.test.dtb.1.expect |  36 +++
 ...own_tags_can_skip.fdtput.test.dtb.2.expect |  34 +++
 ...own_tags_can_skip.fdtput.test.dtb.3.expect |  36 +++
 ...own_tags_can_skip.fdtput.test.dtb.4.expect |  35 +++
 ...own_tags_can_skip.fdtput.test.dtb.5.expect |  33 +++
 ...own_tags_can_skip.fdtput.test.dtb.6.expect |  28 +++
 ...nknown_tags_can_skip.wip.test.dtb.0.expect |  32 +++
 ...nknown_tags_can_skip.wip.test.dtb.1.expect |  36 +++
 ...nknown_tags_can_skip.wip.test.dtb.2.expect |  38 +++
 ...nknown_tags_can_skip.wip.test.dtb.3.expect |  39 ++++
 tests/wip_func.c                              | 127 ++++++++++
 44 files changed, 1688 insertions(+), 114 deletions(-)
 create mode 100644 tests/dtflags_default.dtb.expect
 create mode 100644 tests/dtflags_default.dts
 create mode 100644 tests/get_prop_offset_w.c
 create mode 100644 tests/unknown_tags_can_skip.dtb.dts.expect
 create mode 100644 tests/unknown_tags_can_skip.dtb.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.3.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.4.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.5.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.6.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.3.expect
 create mode 100644 tests/wip_func.c
Signature · 1 line
2.55.0
#1 lore raw

PATCH v3 1/15 fdtget: Use libfdt iterators instead of open coded loops

fdtget uses directly fdt_{first,next}_property_offset() with a while(1) loop to iterate over node properties.

It also uses the low level primitive fdt_next_tag() with custom tags, level and depth handling to iterates over subnodes.

It is worth noting that FDT_NOP can be returned by fdt_next_tag() and this tag is not taken into account in the fdtget open coded loop. This will lead to an incorrect error if a FDT_NOP tag is encountered.

libfdt provides iterators to iterate over node properties and subnodes. The subnode iterator provided by libfdt is robust against FDT_NOP tags and will be robust in the future when new tags are introduced.

Replace fdtget open coded loops by iterators provided by libfdt and designed to perform those operations.

---
 fdtget.c | 73 ++++++++++++++++++--------------------------------------
 1 file changed, 23 insertions(+), 50 deletions(-)
fdtget.c +23 -50
index dd709854..c6169691 100644
@@ -138,21 +138,20 @@ static int show_data(struct display_info *disp, const char *data, int len)
 static int list_properties(const void *blob, int node)
 {
 	const char *name;
+	const void *p;
 	int prop;
 
-	prop = fdt_first_property_offset(blob, node);
-	do {
-		/* Stop silently when there are no more properties */
-		if (prop < 0)
-			return prop == -FDT_ERR_NOTFOUND ? 0 : prop;
-		fdt_getprop_by_offset(blob, prop, &name, NULL);
-		if (name)
+	fdt_for_each_property_offset(prop, blob, node) {
+		p = fdt_getprop_by_offset(blob, prop, &name, NULL);
+		if (p && name)
 			puts(name);
-		prop = fdt_next_property_offset(blob, prop);
-	} while (1);
-}
+	}
 
-#define MAX_LEVEL	32		/* how deeply nested we will go */
+	if ((prop < 0) && (prop != -FDT_ERR_NOTFOUND))
+		return prop;
+
+	return 0;
+}
 
 /**
  * List all subnodes in a node, one per line
@@ -163,47 +162,21 @@ static int list_properties(const void *blob, int node)
  */
 static int list_subnodes(const void *blob, int node)
 {
-	int nextoffset;		/* next node offset from libfdt */
-	uint32_t tag;		/* current tag */
-	int level = 0;		/* keep track of nesting level */
 	const char *pathp;
-	int depth = 1;		/* the assumed depth of this node */
-
-	while (level >= 0) {
-		tag = fdt_next_tag(blob, node, &nextoffset);
-		switch (tag) {
-		case FDT_BEGIN_NODE:
-			pathp = fdt_get_name(blob, node, NULL);
-			if (level <= depth) {
-				if (pathp == NULL)
-					pathp = "/* NULL pointer error */";
-				if (*pathp == '\0')
-					pathp = "/";	/* root is nameless */
-				if (level == 1)
-					puts(pathp);
-			}
-			level++;
-			if (level >= MAX_LEVEL) {
-				printf("Nested too deep, aborting.\n");
-				return 1;
-			}
-			break;
-		case FDT_END_NODE:
-			level--;
-			if (level == 0)
-				level = -1;		/* exit the loop */
-			break;
-		case FDT_END:
-			return 1;
-		case FDT_PROP:
-			break;
-		default:
-			if (level <= depth)
-				printf("Unknown tag 0x%08X\n", tag);
-			return 1;
-		}
-		node = nextoffset;
+	int subnode;
+
+	fdt_for_each_subnode(subnode, blob, node) {
+		pathp = fdt_get_name(blob, subnode, NULL);
+		if (pathp == NULL)
+			pathp = "/* NULL pointer error */";
+		if (*pathp == '\0')
+			pathp = "/";	/* root is nameless */
+		puts(pathp);
 	}
+
+	if (subnode < 0 && (subnode != -FDT_ERR_NOTFOUND))
+		return subnode;
+
 	return 0;
 }
 
Signature · 1 line
2.55.0
#2 lore raw

Re: [PATCH v3 01/15] fdtget: Use libfdt iterators instead of open coded loops

Quoted 10 lines · Herve Codina

fdtget uses directly fdt_{first,next}_property_offset() with a while(1) loop to iterate over node properties.

It also uses the low level primitive fdt_next_tag() with custom tags, level and depth handling to iterates over subnodes.

It is worth noting that FDT_NOP can be returned by fdt_next_tag() and this tag is not taken into account in the fdtget open coded loop. This will lead to an incorrect error if a FDT_NOP tag is encountered.

Quoted 8 lines

libfdt provides iterators to iterate over node properties and subnodes. The subnode iterator provided by libfdt is robust against FDT_NOP tags and will be robust in the future when new tags are introduced.

Replace fdtget open coded loops by iterators provided by libfdt and designed to perform those operations.

Nice cleanup, merged. A test case to prevent any regressions on that FDT_NOP bug would be a nice addition.

Quoted 105 lines
---
 fdtget.c | 73 ++++++++++++++++++--------------------------------------
 1 file changed, 23 insertions(+), 50 deletions(-)
fdtget.c +23 -50
index dd709854..c6169691 100644
@@ -138,21 +138,20 @@ static int show_data(struct display_info *disp, const char *data, int len)
 static int list_properties(const void *blob, int node)
 {
 	const char *name;
+	const void *p;
 	int prop;
 
-	prop = fdt_first_property_offset(blob, node);
-	do {
-		/* Stop silently when there are no more properties */
-		if (prop < 0)
-			return prop == -FDT_ERR_NOTFOUND ? 0 : prop;
-		fdt_getprop_by_offset(blob, prop, &name, NULL);
-		if (name)
+	fdt_for_each_property_offset(prop, blob, node) {
+		p = fdt_getprop_by_offset(blob, prop, &name, NULL);
+		if (p && name)
 			puts(name);
-		prop = fdt_next_property_offset(blob, prop);
-	} while (1);
-}
+	}
 
-#define MAX_LEVEL	32		/* how deeply nested we will go */
+	if ((prop < 0) && (prop != -FDT_ERR_NOTFOUND))
+		return prop;
+
+	return 0;
+}
 
 /**
  * List all subnodes in a node, one per line
@@ -163,47 +162,21 @@ static int list_properties(const void *blob, int node)
  */
 static int list_subnodes(const void *blob, int node)
 {
-	int nextoffset;		/* next node offset from libfdt */
-	uint32_t tag;		/* current tag */
-	int level = 0;		/* keep track of nesting level */
 	const char *pathp;
-	int depth = 1;		/* the assumed depth of this node */
-
-	while (level >= 0) {
-		tag = fdt_next_tag(blob, node, &nextoffset);
-		switch (tag) {
-		case FDT_BEGIN_NODE:
-			pathp = fdt_get_name(blob, node, NULL);
-			if (level <= depth) {
-				if (pathp == NULL)
-					pathp = "/* NULL pointer error */";
-				if (*pathp == '\0')
-					pathp = "/";	/* root is nameless */
-				if (level == 1)
-					puts(pathp);
-			}
-			level++;
-			if (level >= MAX_LEVEL) {
-				printf("Nested too deep, aborting.\n");
-				return 1;
-			}
-			break;
-		case FDT_END_NODE:
-			level--;
-			if (level == 0)
-				level = -1;		/* exit the loop */
-			break;
-		case FDT_END:
-			return 1;
-		case FDT_PROP:
-			break;
-		default:
-			if (level <= depth)
-				printf("Unknown tag 0x%08X\n", tag);
-			return 1;
-		}
-		node = nextoffset;
+	int subnode;
+
+	fdt_for_each_subnode(subnode, blob, node) {
+		pathp = fdt_get_name(blob, subnode, NULL);
+		if (pathp == NULL)
+			pathp = "/* NULL pointer error */";
+		if (*pathp == '\0')
+			pathp = "/";	/* root is nameless */
+		puts(pathp);
 	}
+
+	if (subnode < 0 && (subnode != -FDT_ERR_NOTFOUND))
+		return subnode;
+
 	return 0;
 }
 
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#3 lore raw

PATCH v3 2/15 libfdt: Don't assume the root node is available at offset 0

In reply to Herve Codina

In several places, libfdt assumes that the root offset (i.e. the first FDT_BEGIN_NODE tag) is present at the offset 0 of the structure block.

This assumption is not correct. A FDT_NOP can be present at the offset 0 and this is a legit case. Indeed, the device-tree specification [0] defines the FDT_NOP tag as follow:

The FDT_NOP token will be ignored by any program parsing the device tree. This token has no extra data; so it is followed immediately by the next token, which can be any valid token. A property or node definition in the tree can be overwritten with FDT_NOP tokens to remove it from the tree without needing to move other sections of the tree’s representation in the devicetree blob.

Nothing refers to any location for this tag and it has to be simply ignored. Having this tag at offset 0 doesn't make an exception, the tag has to be ignored.

Introduce fdt_root_offset() in order to get the offset of the root node (first FDT_BEGIN_NODE tag) available in a fdt blob taking care of FDT_NOP tags.

Use this function to get the root node offset instead of looking for this node at offset 0.

[0] https://github.com/devicetree-org/devicetree-specification/blob/main/source/chapter5-flattened-format.rst?plain=1#L317

---
 libfdt/fdt.c       | 39 +++++++++++++++++++++++++++++--
 libfdt/fdt_ro.c    | 57 ++++++++++++++++++++++++++++++++++++++--------
 libfdt/fdt_rw.c    | 12 ++++++++++
 libfdt/libfdt.h    | 15 +++++++++++-
 libfdt/version.lds |  1 +
 5 files changed, 111 insertions(+), 13 deletions(-)
libfdt/fdt.c +37 -2
index 56d4dcb2..eb803e8a 100644
@@ -252,13 +252,48 @@ int fdt_check_prop_offset_(const void *fdt, int offset)
 	return offset;
 }
 
-int fdt_next_node(const void *fdt, int offset, int *depth)
+int fdt_root_offset(const void *fdt)
 {
 	int nextoffset = 0;
+	int offset;
+	uint32_t tag;
+
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		switch (tag) {
+		case FDT_END_NODE:
+		case FDT_PROP:
+			return -FDT_ERR_BADSTRUCTURE;
+
+		case FDT_BEGIN_NODE:
+			return offset;
+
+		default:
+			break;
+		}
+	} while (tag != FDT_END);
+
+	return (nextoffset < 0) ? nextoffset : -FDT_ERR_NOTFOUND;
+}
+
+int fdt_next_node(const void *fdt, int offset, int *depth)
+{
+	int nextoffset = offset;
 	uint32_t tag;
 
+	/*
+	 * Get the root node if asked for next node from the root node
+	 * (offset == 0) or if the given offset is not valid (negative).
+	 */
+	if (offset <= 0) {
+		nextoffset = fdt_root_offset(fdt);
+		if (nextoffset < 0)
+			return nextoffset;
+	}
+
 	if (offset >= 0)
-		if ((nextoffset = fdt_check_node_offset_(fdt, offset)) < 0)
+		if ((nextoffset = fdt_check_node_offset_(fdt, nextoffset)) < 0)
 			return nextoffset;
 
 	do {
libfdt/fdt_ro.c +47 -10

125 lines not on this page · raw message

libfdt/fdt_rw.c +12 -0
index 850aafe4..ceef49b8 100644
@@ -226,6 +226,12 @@ static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 	int err;
 	int allocated;
 
+	if (!nodeoffset) {
+		nodeoffset = fdt_root_offset(fdt);
+		if (nodeoffset < 0)
+			return nodeoffset;
+	}
+
 	if ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
 		return nextoffset;
 
@@ -377,6 +383,12 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 
 	FDT_RW_PROBE(fdt);
 
+	if (!parentoffset) {
+		parentoffset = fdt_root_offset(fdt);
+		if (parentoffset < 0)
+			return parentoffset;
+	}
+
 	offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);
 	if (offset >= 0)
 		return -FDT_ERR_EXISTS;
libfdt/libfdt.h +14 -1
index c69a18ed..7a1915a5 100644
@@ -503,6 +503,19 @@ int fdt_num_mem_rsv(const void *fdt);
  */
 int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size);
 
+/**
+ * fdt_root_offset - Get the offset of the root node
+ * @fdt: pointer to the device tree blob
+ *
+ * The root node can be located after the offset 0. Indeed FDT_NOP tags can be
+ * present at offset 0. fdt_root_offset() takes care of those possible FDT_NOP
+ * tags.
+ *
+ * returns: offset of the root node or negative libfdt error value otherwise
+ */
+int fdt_root_offset(const void *fdt);
+
+
 /**
  * fdt_subnode_offset_namelen - find a subnode based on substring
  * @fdt: pointer to the device tree blob
@@ -1025,7 +1038,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen);
  * at a specific depth from the root (where the root itself has depth
  * 0, its immediate subnodes depth 1 and so forth).  So
  *	fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, NULL);
- * will always return 0, the offset of the root node.  If the node at
+ * will always return the offset of the root node.  If the node at
  * nodeoffset has depth D, then:
  *	fdt_supernode_atdepth_offset(fdt, nodeoffset, D, NULL);
  * will return nodeoffset itself.
libfdt/version.lds +1 -0
index cbfef546..d0b71669 100644
@@ -7,6 +7,7 @@ LIBFDT_1.2 {
 		fdt_string;
 		fdt_num_mem_rsv;
 		fdt_get_mem_rsv;
+		fdt_root_offset;
 		fdt_subnode_offset_namelen;
 		fdt_subnode_offset;
 		fdt_path_offset_namelen;
Signature · 1 line
2.55.0
#4 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Quoted 18 lines · Herve Codina

In several places, libfdt assumes that the root offset (i.e. the first FDT_BEGIN_NODE tag) is present at the offset 0 of the structure block.

This assumption is not correct. A FDT_NOP can be present at the offset 0 and this is a legit case. Indeed, the device-tree specification [0] defines the FDT_NOP tag as follow:

The FDT_NOP token will be ignored by any program parsing the device tree. This token has no extra data; so it is followed immediately by the next token, which can be any valid token. A property or node definition in the tree can be overwritten with FDT_NOP tokens to remove it from the tree without needing to move other sections of the tree’s representation in the devicetree blob.

Nothing refers to any location for this tag and it has to be simply ignored. Having this tag at offset 0 doesn't make an exception, the tag has to be ignored.

Quoted 8 lines

Introduce fdt_root_offset() in order to get the offset of the root node (first FDT_BEGIN_NODE tag) available in a fdt blob taking care of FDT_NOP tags.

Use this function to get the root node offset instead of looking for this node at offset 0.

[0] https://github.com/devicetree-org/devicetree-specification/blob/main/source/chapter5-flattened-format.rst?plain=1#L317

You convinced me of the necessity of this the last time around, but I think the implementation could be improbved.

Quoted 32 lines
---
 libfdt/fdt.c       | 39 +++++++++++++++++++++++++++++--
 libfdt/fdt_ro.c    | 57 ++++++++++++++++++++++++++++++++++++++--------
 libfdt/fdt_rw.c    | 12 ++++++++++
 libfdt/libfdt.h    | 15 +++++++++++-
 libfdt/version.lds |  1 +
 5 files changed, 111 insertions(+), 13 deletions(-)
libfdt/fdt.c +11 -1
index 56d4dcb2..eb803e8a 100644
@@ -252,13 +252,48 @@ int fdt_check_prop_offset_(const void *fdt, int offset)
 	return offset;
 }
 
-int fdt_next_node(const void *fdt, int offset, int *depth)
+int fdt_root_offset(const void *fdt)
 {
 	int nextoffset = 0;
+	int offset;
+	uint32_t tag;
+
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		switch (tag) {
+		case FDT_END_NODE:
+		case FDT_PROP:
+			return -FDT_ERR_BADSTRUCTURE;

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 277

Quoted 10 lines
libfdt/fdt.c +10 -0
+
+		case FDT_BEGIN_NODE:
+			return offset;
+
+		default:
+			break;
+		}
+	} while (tag != FDT_END);
+
+	return (nextoffset < 0) ? nextoffset : -FDT_ERR_NOTFOUND;

This should be BADSTRUCTURE rather than NOTFOUND: a dtb without a root node is not validly constructed. (This could matter quite a lot if this error gets propagated up a call chain - a NOTFOUND is usually non-fatal, but BADSTRUCTURE means there's basically nothing that can usefully be done with the dtb, which the caller needs to know as soon as possible).

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 282

Quoted 5 lines
libfdt/fdt.c +5 -0
+}
+
+int fdt_next_node(const void *fdt, int offset, int *depth)
+{
+	int nextoffset = offset;

This initialiser should be omitted, since it is now overwritten in every possible case.

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 294

Quoted 12 lines
libfdt/fdt.c +10 -0
 	uint32_t tag;
 
+	/*
+	 * Get the root node if asked for next node from the root node
+	 * (offset == 0) or if the given offset is not valid (negative).
+	 */
+	if (offset <= 0) {
+		nextoffset = fdt_root_offset(fdt);
+		if (nextoffset < 0)
+			return nextoffset;
+	}
+

The various changes you've made look correct, but I don't love the fact that it requires nearly every function which takes a node offset to be altered non-trivially. As well as making for a large diff, it strikes me as fragile - a bit of logic that could easily be forgotten on a new function.

I think we want to move the offset 0 handling into a common helper. Logically that should be fdt_check_node_offset_(), since that's the standard way of validating a node offset parameter. As you've pointed out, that doesn't work with the current signature/semantics of fdt_check_node_offset_() - but it's a strictly internal function, so we can alter its signature freely.

Quoted 109 lines
libfdt/fdt.c +1 -1
 	if (offset >= 0)
-		if ((nextoffset = fdt_check_node_offset_(fdt, offset)) < 0)
+		if ((nextoffset = fdt_check_node_offset_(fdt, nextoffset)) < 0)
 			return nextoffset;
 
 	do {
libfdt/fdt_ro.c +31 -4
index 11f2e2ee..856c62f1 100644
@@ -231,6 +231,12 @@ int fdt_subnode_offset_namelen(const void *fdt, int offset,
 
 	FDT_RO_PROBE(fdt);
 
+	if (!offset) {
+		offset = fdt_root_offset(fdt);
+		if (offset < 0)
+			return offset;
+	}
+
 	for (depth = 0;
 	     (offset >= 0) && (depth >= 0);
 	     offset = fdt_next_node(fdt, offset, &depth))
@@ -253,13 +259,17 @@ int fdt_path_offset_namelen(const void *fdt, const char *path, int namelen)
 {
 	const char *end = path + namelen;
 	const char *p = path;
-	int offset = 0;
+	int offset;
 
 	FDT_RO_PROBE(fdt);
 
 	if (!can_assume(VALID_INPUT) && namelen <= 0)
 		return -FDT_ERR_BADPATH;
 
+	offset = fdt_root_offset(fdt);
+	if (offset < 0)
+		return offset;
+
 	/* see if we have an alias */
 	if (*path != '/') {
 		const char *q = memchr(path, '/', end - p);
@@ -304,14 +314,24 @@ int fdt_path_offset(const void *fdt, const char *path)
 
 const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
 {
-	const struct fdt_node_header *nh = fdt_offset_ptr_(fdt, nodeoffset);
+	const struct fdt_node_header *nh;
 	const char *nameptr;
 	int err;
 
+	if (!nodeoffset) {
+		nodeoffset = fdt_root_offset(fdt);
+		if (nodeoffset < 0) {
+			err = nodeoffset;
+			goto fail;
+		}
+	}
+
+
 	if (!can_assume(VALID_DTB) && (((err = fdt_ro_probe_(fdt)) < 0)
 	    || ((err = fdt_check_node_offset_(fdt, nodeoffset)) < 0)))
 			goto fail;
 
+	nh = fdt_offset_ptr_(fdt, nodeoffset);
 	nameptr = nh->name;
 
 	if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {
@@ -344,6 +364,12 @@ int fdt_first_property_offset(const void *fdt, int nodeoffset)
 {
 	int offset;
 
+	if (!nodeoffset) {
+		nodeoffset = fdt_root_offset(fdt);
+		if (nodeoffset < 0)
+			return nodeoffset;
+	}
+
 	if ((offset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
 		return offset;
 
@@ -581,7 +607,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
 	if (buflen < 2)
 		return -FDT_ERR_NOSPACE;
 
-	for (offset = 0, depth = 0;
+	for (offset = fdt_root_offset(fdt), depth = 0;
 	     (offset >= 0) && (offset <= nodeoffset);
 	     offset = fdt_next_node(fdt, offset, &depth)) {
 		while (pdepth > depth) {
@@ -619,7 +645,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
 	else if (offset == -FDT_ERR_BADOFFSET)
 		return -FDT_ERR_BADSTRUCTURE;
 
-	return offset; /* error from fdt_next_node() */
+	return offset; /* error from fdt_next_node() or fdt_root_offset() */
 }
 
 int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
@@ -627,13 +653,21 @@ int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
 {
 	int offset, depth;
 	int supernodeoffset = -FDT_ERR_INTERNAL;
+	int root_offset;
 
 	FDT_RO_PROBE(fdt);
 
 	if (supernodedepth < 0)
 		return -FDT_ERR_NOTFOUND;

libfdt/fdt_ro.c int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset, · line 670

Quoted 10 lines
libfdt/fdt_ro.c +8 -1
 
-	for (offset = 0, depth = 0;
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		return root_offset;
+
+	if (!nodeoffset)
+		nodeoffset = root_offset;
+
+	for (offset = root_offset, depth = 0;

Do you need this special casing? Won't the fact you've update fdt_next_node() to handle the offset 0 case be enough?

Quoted 11 lines
libfdt/fdt_ro.c +3 -1
 	     (offset >= 0) && (offset <= nodeoffset);
 	     offset = fdt_next_node(fdt, offset, &depth)) {
 		if (depth == supernodedepth)
@@ -663,12 +697,15 @@ int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
 int fdt_node_depth(const void *fdt, int nodeoffset)
 {
 	int nodedepth;
-	int err;
+	int offset;
+
+	offset = fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, &nodedepth);

libfdt/fdt_ro.c int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset, · line 671

Quoted 10 lines
libfdt/fdt_ro.c +5 -4
+	if (offset < 0)
+		return offset;
+
+	if (!can_assume(LIBFDT_FLAWLESS) && offset != fdt_root_offset(fdt))
+		return -FDT_ERR_INTERNAL;
 
-	err = fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, &nodedepth);
-	if (err)
-		return (can_assume(LIBFDT_FLAWLESS) || err < 0) ? err :
-			-FDT_ERR_INTERNAL;

Replacing the extremly cryptic logic above is a nice byproduct.

Quoted 82 lines
libfdt/fdt_ro.c +0 -0
 	return nodedepth;
 }
 
libfdt/fdt_rw.c +12 -0
index 850aafe4..ceef49b8 100644
@@ -226,6 +226,12 @@ static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 	int err;
 	int allocated;
 
+	if (!nodeoffset) {
+		nodeoffset = fdt_root_offset(fdt);
+		if (nodeoffset < 0)
+			return nodeoffset;
+	}
+
 	if ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
 		return nextoffset;
 
@@ -377,6 +383,12 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 
 	FDT_RW_PROBE(fdt);
 
+	if (!parentoffset) {
+		parentoffset = fdt_root_offset(fdt);
+		if (parentoffset < 0)
+			return parentoffset;
+	}
+
 	offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);
 	if (offset >= 0)
 		return -FDT_ERR_EXISTS;
libfdt/libfdt.h +14 -1
index c69a18ed..7a1915a5 100644
@@ -503,6 +503,19 @@ int fdt_num_mem_rsv(const void *fdt);
  */
 int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size);
 
+/**
+ * fdt_root_offset - Get the offset of the root node
+ * @fdt: pointer to the device tree blob
+ *
+ * The root node can be located after the offset 0. Indeed FDT_NOP tags can be
+ * present at offset 0. fdt_root_offset() takes care of those possible FDT_NOP
+ * tags.
+ *
+ * returns: offset of the root node or negative libfdt error value otherwise
+ */
+int fdt_root_offset(const void *fdt);
+
+
 /**
  * fdt_subnode_offset_namelen - find a subnode based on substring
  * @fdt: pointer to the device tree blob
@@ -1025,7 +1038,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen);
  * at a specific depth from the root (where the root itself has depth
  * 0, its immediate subnodes depth 1 and so forth).  So
  *	fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, NULL);
- * will always return 0, the offset of the root node.  If the node at
+ * will always return the offset of the root node.  If the node at
  * nodeoffset has depth D, then:
  *	fdt_supernode_atdepth_offset(fdt, nodeoffset, D, NULL);
  * will return nodeoffset itself.
libfdt/version.lds +1 -0
index cbfef546..d0b71669 100644
@@ -7,6 +7,7 @@ LIBFDT_1.2 {
 		fdt_string;
 		fdt_num_mem_rsv;
 		fdt_get_mem_rsv;
+		fdt_root_offset;
 		fdt_subnode_offset_namelen;
 		fdt_subnode_offset;
 		fdt_path_offset_namelen;
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#5 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Hi David,

On Sun, 30 Aug 2026 13:21:06 +1000
David Gibson <[email protected]> wrote:

...

Quoted 23 lines
Quoted 23 lines
libfdt/fdt.c +20 -1
-int fdt_next_node(const void *fdt, int offset, int *depth)
+int fdt_root_offset(const void *fdt)
 {
 	int nextoffset = 0;
+	int offset;
+	uint32_t tag;
+
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		switch (tag) {
+		case FDT_END_NODE:
+		case FDT_PROP:
+			return -FDT_ERR_BADSTRUCTURE;
+
+		case FDT_BEGIN_NODE:
+			return offset;
+
+		default:
+			break;
+		}
+	} while (tag != FDT_END);
+
Quoted 8 lines

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 277

Quoted 1 line
libfdt/fdt.c +1 -0
+	return (nextoffset < 0) ? nextoffset : -FDT_ERR_NOTFOUND;  

This should be BADSTRUCTURE rather than NOTFOUND: a dtb without a root node is not validly constructed. (This could matter quite a lot if this error gets propagated up a call chain - a NOTFOUND is usually non-fatal, but BADSTRUCTURE means there's basically nothing that can usefully be done with the dtb, which the caller needs to know as soon as possible).

Now yes, a dtb without a root node is an invalid dtb but soon with addon this will be allowed [1].

addon dtbs will be clearly identified (the dt_flags header field has FDT_FLAG_ADDON set for addon dtbs) and so what do you think if the error code returned depends on this flag.

NOTFOUND in case of addon and BADSTRUCTURE otherwise.

If you are ok with that, I will update this current patch to return BADSTRUCTURE in all case. Indeed, addon are not yet available.

[1] https://lore.kernel.org/all/[email protected]/

Quoted 9 lines

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 282

Quoted 6 lines
libfdt/fdt.c +5 -0
+}
+
+int fdt_next_node(const void *fdt, int offset, int *depth)
+{
+	int nextoffset = offset;  

This initialiser should be omitted, since it is now overwritten in every possible case.

Yes indeed, will be updated in the next iteration.

Quoted 20 lines

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 294

Quoted 13 lines
libfdt/fdt.c +10 -0
 	uint32_t tag;
 
+	/*
+	 * Get the root node if asked for next node from the root node
+	 * (offset == 0) or if the given offset is not valid (negative).
+	 */
+	if (offset <= 0) {
+		nextoffset = fdt_root_offset(fdt);
+		if (nextoffset < 0)
+			return nextoffset;
+	}
+  

The various changes you've made look correct, but I don't love the fact that it requires nearly every function which takes a node offset to be altered non-trivially. As well as making for a large diff, it strikes me as fragile - a bit of logic that could easily be forgotten on a new function.

Quoted 6 lines

I think we want to move the offset 0 handling into a common helper. Logically that should be fdt_check_node_offset_(), since that's the standard way of validating a node offset parameter. As you've pointed out, that doesn't work with the current signature/semantics of fdt_check_node_offset_() - but it's a strictly internal function, so we can alter its signature freely.

Ok, you insist on this point. I will updade fdt_check_node_offset_() to handle the offset 0 case.

Quoted 111 lines
Quoted 111 lines
libfdt/fdt.c +1 -1
 	if (offset >= 0)
-		if ((nextoffset = fdt_check_node_offset_(fdt, offset)) < 0)
+		if ((nextoffset = fdt_check_node_offset_(fdt, nextoffset)) < 0)
 			return nextoffset;
 
 	do {
libfdt/fdt_ro.c +31 -4
index 11f2e2ee..856c62f1 100644
@@ -231,6 +231,12 @@ int fdt_subnode_offset_namelen(const void *fdt, int offset,
 
 	FDT_RO_PROBE(fdt);
 
+	if (!offset) {
+		offset = fdt_root_offset(fdt);
+		if (offset < 0)
+			return offset;
+	}
+
 	for (depth = 0;
 	     (offset >= 0) && (depth >= 0);
 	     offset = fdt_next_node(fdt, offset, &depth))
@@ -253,13 +259,17 @@ int fdt_path_offset_namelen(const void *fdt, const char *path, int namelen)
 {
 	const char *end = path + namelen;
 	const char *p = path;
-	int offset = 0;
+	int offset;
 
 	FDT_RO_PROBE(fdt);
 
 	if (!can_assume(VALID_INPUT) && namelen <= 0)
 		return -FDT_ERR_BADPATH;
 
+	offset = fdt_root_offset(fdt);
+	if (offset < 0)
+		return offset;
+
 	/* see if we have an alias */
 	if (*path != '/') {
 		const char *q = memchr(path, '/', end - p);
@@ -304,14 +314,24 @@ int fdt_path_offset(const void *fdt, const char *path)
 
 const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
 {
-	const struct fdt_node_header *nh = fdt_offset_ptr_(fdt, nodeoffset);
+	const struct fdt_node_header *nh;
 	const char *nameptr;
 	int err;
 
+	if (!nodeoffset) {
+		nodeoffset = fdt_root_offset(fdt);
+		if (nodeoffset < 0) {
+			err = nodeoffset;
+			goto fail;
+		}
+	}
+
+
 	if (!can_assume(VALID_DTB) && (((err = fdt_ro_probe_(fdt)) < 0)
 	    || ((err = fdt_check_node_offset_(fdt, nodeoffset)) < 0)))
 			goto fail;
 
+	nh = fdt_offset_ptr_(fdt, nodeoffset);
 	nameptr = nh->name;
 
 	if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {
@@ -344,6 +364,12 @@ int fdt_first_property_offset(const void *fdt, int nodeoffset)
 {
 	int offset;
 
+	if (!nodeoffset) {
+		nodeoffset = fdt_root_offset(fdt);
+		if (nodeoffset < 0)
+			return nodeoffset;
+	}
+
 	if ((offset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
 		return offset;
 
@@ -581,7 +607,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
 	if (buflen < 2)
 		return -FDT_ERR_NOSPACE;
 
-	for (offset = 0, depth = 0;
+	for (offset = fdt_root_offset(fdt), depth = 0;
 	     (offset >= 0) && (offset <= nodeoffset);
 	     offset = fdt_next_node(fdt, offset, &depth)) {
 		while (pdepth > depth) {
@@ -619,7 +645,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
 	else if (offset == -FDT_ERR_BADOFFSET)
 		return -FDT_ERR_BADSTRUCTURE;
 
-	return offset; /* error from fdt_next_node() */
+	return offset; /* error from fdt_next_node() or fdt_root_offset() */
 }
 
 int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
@@ -627,13 +653,21 @@ int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
 {
 	int offset, depth;
 	int supernodeoffset = -FDT_ERR_INTERNAL;
+	int root_offset;
 
 	FDT_RO_PROBE(fdt);
 
 	if (supernodedepth < 0)
 		return -FDT_ERR_NOTFOUND;
 
Quoted 12 lines

libfdt/fdt_ro.c int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset, · line 670

Quoted 9 lines
libfdt/fdt_ro.c +8 -1
-	for (offset = 0, depth = 0;
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		return root_offset;
+
+	if (!nodeoffset)
+		nodeoffset = root_offset;
+
+	for (offset = root_offset, depth = 0;  

Do you need this special casing? Won't the fact you've update fdt_next_node() to handle the offset 0 case be enough?

The full loop is the following:
--- 8< ---

	for (offset = root_offset, depth = 0;
	     (offset >= 0) && (offset <= nodeoffset);
	     offset = fdt_next_node(fdt, offset, &depth)) {
		if (depth == supernodedepth)
			supernodeoffset = offset;

		if (offset == nodeoffset) {
			if (nodedepth)
				*nodedepth = depth;

			if (supernodedepth > depth)
				return -FDT_ERR_NOTFOUND;
			else
				return supernodeoffset;
		}
	}

--- 8< ---

The test 'offset == nodeoffset' is the problematic one. nodeoffset is the parameter passed to the function.

I have chosen to avoid offset 0 for the root node and I have updated 'nodeoffset' previously if it is 0.

Even if fdt_next_node() updates 'offset' if it is 0, 'nodeoffset' has also to be update if it is 0. Indeed, 'offset' will be updated from 0 to the real root node offset. In all case to have the test be correct, 'nodeoffset' should be updated to the real root node offset if it is 0.

Having fdt_next_node() updating 'offset' if it is 0 will not handle all case. When offsets comparison is done, both offsets should consider the real offset of the root node instead of the 0 value.

Also the fdt_supernode_atdepth_offset() can be called with 'nodeoffset' set to the real root node offset instead of 0. Indeed, fdt_root_offset() is available (and needed).

My feeling was that it is less error prone to have offset 0 converted to the real root node offset as soon as possible and then consider only the real offset of the root node instead of a mix between the real offset and the offset 0.

I think that "for (offset = root_offset, ..." will still be needed.

Best regards,
Hervé

#6 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Quoted 39 lines · Herve Codina

Hi David,

On Sun, 30 Aug 2026 13:21:06 +1000
David Gibson <[email protected]> wrote:

...

Quoted 23 lines
Quoted 23 lines
libfdt/fdt.c +20 -1
-int fdt_next_node(const void *fdt, int offset, int *depth)
+int fdt_root_offset(const void *fdt)
 {
 	int nextoffset = 0;
+	int offset;
+	uint32_t tag;
+
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		switch (tag) {
+		case FDT_END_NODE:
+		case FDT_PROP:
+			return -FDT_ERR_BADSTRUCTURE;
+
+		case FDT_BEGIN_NODE:
+			return offset;
+
+		default:
+			break;
+		}
+	} while (tag != FDT_END);
+
Quoted 8 lines

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 277

Quoted 1 line
libfdt/fdt.c +1 -0
+	return (nextoffset < 0) ? nextoffset : -FDT_ERR_NOTFOUND;  

This should be BADSTRUCTURE rather than NOTFOUND: a dtb without a root node is not validly constructed. (This could matter quite a lot if this error gets propagated up a call chain - a NOTFOUND is usually non-fatal, but BADSTRUCTURE means there's basically nothing that can usefully be done with the dtb, which the caller needs to know as soon as possible).

Quoted 2 lines

Now yes, a dtb without a root node is an invalid dtb but soon with addon this will be allowed [1].

Ah, ok. I haven't looked at the addon stuff yet. I do intend to, but it will certainly take a while (70+ patches!).

So, I'm guessing here, but it still seems odd to me that an addon with no BEGIN_NODE tags at all could be useful.

Quoted 5 lines

addon dtbs will be clearly identified (the dt_flags header field has FDT_FLAG_ADDON set for addon dtbs) and so what do you think if the error code returned depends on this flag.

NOTFOUND in case of addon and BADSTRUCTURE otherwise.

I'd need to look at the details of addons to figure out if this makes sense but I'm not opposed to the approach in principle.

Quoted 2 lines

If you are ok with that, I will update this current patch to return BADSTRUCTURE in all case. Indeed, addon are not yet available.

Right, regardless of where we go with addons eventually, I think it's preferable to return BADSTRUCTURE for now. That can be changed once addons are actually implemented.

Quoted 42 lines

[1] https://lore.kernel.org/all/[email protected]/

Quoted 9 lines

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 282

Quoted 6 lines
libfdt/fdt.c +5 -0
+}
+
+int fdt_next_node(const void *fdt, int offset, int *depth)
+{
+	int nextoffset = offset;  

This initialiser should be omitted, since it is now overwritten in every possible case.

Yes indeed, will be updated in the next iteration.

Quoted 20 lines

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 294

Quoted 13 lines
libfdt/fdt.c +10 -0
 	uint32_t tag;
 
+	/*
+	 * Get the root node if asked for next node from the root node
+	 * (offset == 0) or if the given offset is not valid (negative).
+	 */
+	if (offset <= 0) {
+		nextoffset = fdt_root_offset(fdt);
+		if (nextoffset < 0)
+			return nextoffset;
+	}
+  

The various changes you've made look correct, but I don't love the fact that it requires nearly every function which takes a node offset to be altered non-trivially. As well as making for a large diff, it strikes me as fragile - a bit of logic that could easily be forgotten on a new function.

Quoted 6 lines

I think we want to move the offset 0 handling into a common helper. Logically that should be fdt_check_node_offset_(), since that's the standard way of validating a node offset parameter. As you've pointed out, that doesn't work with the current signature/semantics of fdt_check_node_offset_() - but it's a strictly internal function, so we can alter its signature freely.

Quoted 2 lines

Ok, you insist on this point. I will updade fdt_check_node_offset_() to handle the offset 0 case.

Great.

Quoted 151 lines
Quoted 112 lines
Quoted 112 lines
libfdt/fdt.c +1 -1
 	if (offset >= 0)
-		if ((nextoffset = fdt_check_node_offset_(fdt, offset)) < 0)
+		if ((nextoffset = fdt_check_node_offset_(fdt, nextoffset)) < 0)
 			return nextoffset;
 
 	do {
libfdt/fdt_ro.c +31 -4
index 11f2e2ee..856c62f1 100644
@@ -231,6 +231,12 @@ int fdt_subnode_offset_namelen(const void *fdt, int offset,
 
 	FDT_RO_PROBE(fdt);
 
+	if (!offset) {
+		offset = fdt_root_offset(fdt);
+		if (offset < 0)
+			return offset;
+	}
+
 	for (depth = 0;
 	     (offset >= 0) && (depth >= 0);
 	     offset = fdt_next_node(fdt, offset, &depth))
@@ -253,13 +259,17 @@ int fdt_path_offset_namelen(const void *fdt, const char *path, int namelen)
 {
 	const char *end = path + namelen;
 	const char *p = path;
-	int offset = 0;
+	int offset;
 
 	FDT_RO_PROBE(fdt);
 
 	if (!can_assume(VALID_INPUT) && namelen <= 0)
 		return -FDT_ERR_BADPATH;
 
+	offset = fdt_root_offset(fdt);
+	if (offset < 0)
+		return offset;
+
 	/* see if we have an alias */
 	if (*path != '/') {
 		const char *q = memchr(path, '/', end - p);
@@ -304,14 +314,24 @@ int fdt_path_offset(const void *fdt, const char *path)
 
 const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
 {
-	const struct fdt_node_header *nh = fdt_offset_ptr_(fdt, nodeoffset);
+	const struct fdt_node_header *nh;
 	const char *nameptr;
 	int err;
 
+	if (!nodeoffset) {
+		nodeoffset = fdt_root_offset(fdt);
+		if (nodeoffset < 0) {
+			err = nodeoffset;
+			goto fail;
+		}
+	}
+
+
 	if (!can_assume(VALID_DTB) && (((err = fdt_ro_probe_(fdt)) < 0)
 	    || ((err = fdt_check_node_offset_(fdt, nodeoffset)) < 0)))
 			goto fail;
 
+	nh = fdt_offset_ptr_(fdt, nodeoffset);
 	nameptr = nh->name;
 
 	if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {
@@ -344,6 +364,12 @@ int fdt_first_property_offset(const void *fdt, int nodeoffset)
 {
 	int offset;
 
+	if (!nodeoffset) {
+		nodeoffset = fdt_root_offset(fdt);
+		if (nodeoffset < 0)
+			return nodeoffset;
+	}
+
 	if ((offset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
 		return offset;
 
@@ -581,7 +607,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
 	if (buflen < 2)
 		return -FDT_ERR_NOSPACE;
 
-	for (offset = 0, depth = 0;
+	for (offset = fdt_root_offset(fdt), depth = 0;
 	     (offset >= 0) && (offset <= nodeoffset);
 	     offset = fdt_next_node(fdt, offset, &depth)) {
 		while (pdepth > depth) {
@@ -619,7 +645,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
 	else if (offset == -FDT_ERR_BADOFFSET)
 		return -FDT_ERR_BADSTRUCTURE;
 
-	return offset; /* error from fdt_next_node() */
+	return offset; /* error from fdt_next_node() or fdt_root_offset() */
 }
 
 int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
@@ -627,13 +653,21 @@ int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
 {
 	int offset, depth;
 	int supernodeoffset = -FDT_ERR_INTERNAL;
+	int root_offset;
 
 	FDT_RO_PROBE(fdt);
 
 	if (supernodedepth < 0)
 		return -FDT_ERR_NOTFOUND;
 
Quoted 12 lines

libfdt/fdt_ro.c int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset, · line 670

Quoted 9 lines
libfdt/fdt_ro.c +8 -1
-	for (offset = 0, depth = 0;
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		return root_offset;
+
+	if (!nodeoffset)
+		nodeoffset = root_offset;
+
+	for (offset = root_offset, depth = 0;  

Do you need this special casing? Won't the fact you've update fdt_next_node() to handle the offset 0 case be enough?

The full loop is the following:
--- 8< ---

	for (offset = root_offset, depth = 0;
	     (offset >= 0) && (offset <= nodeoffset);
	     offset = fdt_next_node(fdt, offset, &depth)) {
		if (depth == supernodedepth)
			supernodeoffset = offset;

		if (offset == nodeoffset) {
			if (nodedepth)
				*nodedepth = depth;

			if (supernodedepth > depth)
				return -FDT_ERR_NOTFOUND;
			else
				return supernodeoffset;
		}
	}

--- 8< ---

The test 'offset == nodeoffset' is the problematic one. nodeoffset is the parameter passed to the function.

I have chosen to avoid offset 0 for the root node and I have updated 'nodeoffset' previously if it is 0.

Quoted 8 lines

Even if fdt_next_node() updates 'offset' if it is 0, 'nodeoffset' has also to be update if it is 0. Indeed, 'offset' will be updated from 0 to the real root node offset. In all case to have the test be correct, 'nodeoffset' should be updated to the real root node offset if it is 0.

Having fdt_next_node() updating 'offset' if it is 0 will not handle all case. When offsets comparison is done, both offsets should consider the real offset of the root node instead of the 0 value.

Ah, right. I missed the fact it was updating the nodeoffset parameter, rather than the working/starting offset.

Quoted 3 lines

Also the fdt_supernode_atdepth_offset() can be called with 'nodeoffset' set to the real root node offset instead of 0. Indeed, fdt_root_offset() is available (and needed).

Theoretically we could avoid explicitly looking at the root offset for 'offset', by starting 'offset' negative and moving the fdt_next_node() to the start of the loop body instead of the end. That would handle the nodeoffset == root_offset case, not not the nodeoffset == 0 case. Arguably we could disallow the later - finding the non-existent supernode of something we know at compile time to be the root node isn't very useful - if it only turned out to be the root node at runtime, I'd expect it to have come from another function, which should give us root_offset rather than 0.

But.. it's certainly safer to keep it working whether passed 0 or the real root offset. There are other ways we could do it, but I think they'd turn out equally inelegant.

Ok, makes sense to me.

Quoted 3 lines

My feeling was that it is less error prone to have offset 0 converted to the real root node offset as soon as possible and then consider only the real offset of the root node instead of a mix between the real offset and the offset 0.

That's fair.

Quoted 5 lines

I think that "for (offset = root_offset, ..." will still be needed.

Best regards,
Hervé

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#7 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Hi David,

Quoted 40 lines · On Tue, 1 Sep 2026 17:42:02 +1000 David Gibson <[email protected]>…
Quoted 39 lines · Herve Codina

Hi David,

On Sun, 30 Aug 2026 13:21:06 +1000
David Gibson <[email protected]> wrote:

...

Quoted 31 lines
Quoted 14 lines
libfdt/fdt.c +11 -1
-int fdt_next_node(const void *fdt, int offset, int *depth)
+int fdt_root_offset(const void *fdt)
 {
 	int nextoffset = 0;
+	int offset;
+	uint32_t tag;
+
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		switch (tag) {
+		case FDT_END_NODE:
+		case FDT_PROP:
+			return -FDT_ERR_BADSTRUCTURE;

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 277

Quoted 10 lines
libfdt/fdt.c +10 -0
+
+		case FDT_BEGIN_NODE:
+			return offset;
+
+		default:
+			break;
+		}
+	} while (tag != FDT_END);
+
+	return (nextoffset < 0) ? nextoffset : -FDT_ERR_NOTFOUND;    

This should be BADSTRUCTURE rather than NOTFOUND: a dtb without a root node is not validly constructed. (This could matter quite a lot if this error gets propagated up a call chain - a NOTFOUND is usually non-fatal, but BADSTRUCTURE means there's basically nothing that can usefully be done with the dtb, which the caller needs to know as soon as possible).

Quoted 8 lines
Quoted 2 lines

Now yes, a dtb without a root node is an invalid dtb but soon with addon this will be allowed [1].

Ah, ok. I haven't looked at the addon stuff yet. I do intend to, but it will certainly take a while (70+ patches!).

So, I'm guessing here, but it still seems odd to me that an addon with no BEGIN_NODE tags at all could be useful.

No BEGIN_NODE doesn't mean and empty addon.

Addons can have only orphan nodes without any root node. Those orphan nodes are nodes existing in the base devicetree the addon is applied to. Addon needs to refer those existing node and this reference is the orphan node. --- 8< ---
/addon/

&node_from_base_dtb { /* <--- Orphan node. Node defined in the base DT */
node_defined_in_addon { /* <--- Node added by the addon once applied */

      ...

};
};
--- 8< ---

In the addon, those orphans are identified with BEGIN_NODE_REF [2] and cannot be considered as root nodes.

[2] addon series, patch 51/74

    https://lore.kernel.org/all/[email protected]/
Quoted 10 lines
Quoted 6 lines

addon dtbs will be clearly identified (the dt_flags header field has FDT_FLAG_ADDON set for addon dtbs) and so what do you think if the error code returned depends on this flag.

NOTFOUND in case of addon and BADSTRUCTURE otherwise.

I'd need to look at the details of addons to figure out if this makes sense but I'm not opposed to the approach in principle.

Quoted 6 lines
Quoted 2 lines

If you are ok with that, I will update this current patch to return BADSTRUCTURE in all case. Indeed, addon are not yet available.

Right, regardless of where we go with addons eventually, I think it's preferable to return BADSTRUCTURE for now. That can be changed once addons are actually implemented.

Exactly!

Quoted 4 lines
Quoted 4 lines

[1] https://lore.kernel.org/all/[email protected]/

...

Quoted 56 lines
Quoted 30 lines
Quoted 3 lines

Do you need this special casing? Won't the fact you've update fdt_next_node() to handle the offset 0 case be enough?

The full loop is the following:
--- 8< ---

	for (offset = root_offset, depth = 0;
	     (offset >= 0) && (offset <= nodeoffset);
	     offset = fdt_next_node(fdt, offset, &depth)) {
		if (depth == supernodedepth)
			supernodeoffset = offset;

		if (offset == nodeoffset) {
			if (nodedepth)
				*nodedepth = depth;

			if (supernodedepth > depth)
				return -FDT_ERR_NOTFOUND;
			else
				return supernodeoffset;
		}
	}

--- 8< ---

The test 'offset == nodeoffset' is the problematic one. nodeoffset is the parameter passed to the function.

I have chosen to avoid offset 0 for the root node and I have updated 'nodeoffset' previously if it is 0.

Quoted 8 lines

Even if fdt_next_node() updates 'offset' if it is 0, 'nodeoffset' has also to be update if it is 0. Indeed, 'offset' will be updated from 0 to the real root node offset. In all case to have the test be correct, 'nodeoffset' should be updated to the real root node offset if it is 0.

Having fdt_next_node() updating 'offset' if it is 0 will not handle all case. When offsets comparison is done, both offsets should consider the real offset of the root node instead of the 0 value.

Ah, right. I missed the fact it was updating the nodeoffset parameter, rather than the working/starting offset.

Quoted 3 lines

Also the fdt_supernode_atdepth_offset() can be called with 'nodeoffset' set to the real root node offset instead of 0. Indeed, fdt_root_offset() is available (and needed).

Theoretically we could avoid explicitly looking at the root offset for 'offset', by starting 'offset' negative and moving the fdt_next_node() to the start of the loop body instead of the end. That would handle the nodeoffset == root_offset case, not not the nodeoffset == 0 case. Arguably we could disallow the later - finding the non-existent supernode of something we know at compile time to be the root node isn't very useful - if it only turned out to be the root node at runtime, I'd expect it to have come from another function, which should give us root_offset rather than 0.

Quoted 6 lines

But.. it's certainly safer to keep it working whether passed 0 or the real root offset. There are other ways we could do it, but I think they'd turn out equally inelegant.

Ok, makes sense to me.

Ok, I will update fdt_check_node_offset_() to have it updating its offset parameter to the real offset of the root node when its value is 0.

Based on this update, will see where it goes. I mean, impacts on callers, if it simplifies things or not, if the offset update needs also to be propagate to caller's parameter or any other similar point that we can see during the implementation.

Having something implemented and available in a patch will be the best to compare changes and impacts related to fdt_check_node_offset_() update.

Here we have a version of handling offset 0 vs real root node without any offset update done in fdt_check_node_offset_(). In the next iteration we will have the version with update done in fdt_check_node_offset_().

I think the golden rules to follow on this point is "keep it as simple as possible".

Best regards,
Hervé

#8 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Quoted 64 lines · Herve Codina

Hi David,

Quoted 40 lines · On Tue, 1 Sep 2026 17:42:02 +1000 David Gibson <[email protected]>…
Quoted 39 lines · Herve Codina

Hi David,

On Sun, 30 Aug 2026 13:21:06 +1000
David Gibson <[email protected]> wrote:

...

Quoted 31 lines
Quoted 14 lines
libfdt/fdt.c +11 -1
-int fdt_next_node(const void *fdt, int offset, int *depth)
+int fdt_root_offset(const void *fdt)
 {
 	int nextoffset = 0;
+	int offset;
+	uint32_t tag;
+
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		switch (tag) {
+		case FDT_END_NODE:
+		case FDT_PROP:
+			return -FDT_ERR_BADSTRUCTURE;

libfdt/fdt.c int fdt_check_prop_offset_(const void *fdt, int offset) · line 277

Quoted 10 lines
libfdt/fdt.c +10 -0
+
+		case FDT_BEGIN_NODE:
+			return offset;
+
+		default:
+			break;
+		}
+	} while (tag != FDT_END);
+
+	return (nextoffset < 0) ? nextoffset : -FDT_ERR_NOTFOUND;    

This should be BADSTRUCTURE rather than NOTFOUND: a dtb without a root node is not validly constructed. (This could matter quite a lot if this error gets propagated up a call chain - a NOTFOUND is usually non-fatal, but BADSTRUCTURE means there's basically nothing that can usefully be done with the dtb, which the caller needs to know as soon as possible).

Quoted 8 lines
Quoted 2 lines

Now yes, a dtb without a root node is an invalid dtb but soon with addon this will be allowed [1].

Ah, ok. I haven't looked at the addon stuff yet. I do intend to, but it will certainly take a while (70+ patches!).

So, I'm guessing here, but it still seems odd to me that an addon with no BEGIN_NODE tags at all could be useful.

No BEGIN_NODE doesn't mean and empty addon.

Addons can have only orphan nodes without any root node. Those orphan nodes are nodes existing in the base devicetree the addon is applied to. Addon needs to refer those existing node and this reference is the orphan node. --- 8< ---
/addon/

&node_from_base_dtb { /* <--- Orphan node. Node defined in the base DT */
node_defined_in_addon { /* <--- Node added by the addon once applied */

Quoted 7 lines
      ...

};
};
--- 8< ---

In the addon, those orphans are identified with BEGIN_NODE_REF [2] and cannot be considered as root nodes.

Ok. So, in any case fdt_root_offset() would need modification to handle this: otherwise it will ignore the BEGIN_NODE_REF tag and continue on, possibly finding a BEGIN_NODE *within* one of the pieces and incorrectly reporting that as the root.

Quoted 101 lines

[2] addon series, patch 51/74

    https://lore.kernel.org/all/[email protected]/
Quoted 10 lines
Quoted 6 lines

addon dtbs will be clearly identified (the dt_flags header field has FDT_FLAG_ADDON set for addon dtbs) and so what do you think if the error code returned depends on this flag.

NOTFOUND in case of addon and BADSTRUCTURE otherwise.

I'd need to look at the details of addons to figure out if this makes sense but I'm not opposed to the approach in principle.

Quoted 6 lines
Quoted 2 lines

If you are ok with that, I will update this current patch to return BADSTRUCTURE in all case. Indeed, addon are not yet available.

Right, regardless of where we go with addons eventually, I think it's preferable to return BADSTRUCTURE for now. That can be changed once addons are actually implemented.

Exactly!

Quoted 4 lines
Quoted 4 lines

[1] https://lore.kernel.org/all/[email protected]/

...

Quoted 56 lines
Quoted 30 lines
Quoted 3 lines

Do you need this special casing? Won't the fact you've update fdt_next_node() to handle the offset 0 case be enough?

The full loop is the following:
--- 8< ---

	for (offset = root_offset, depth = 0;
	     (offset >= 0) && (offset <= nodeoffset);
	     offset = fdt_next_node(fdt, offset, &depth)) {
		if (depth == supernodedepth)
			supernodeoffset = offset;

		if (offset == nodeoffset) {
			if (nodedepth)
				*nodedepth = depth;

			if (supernodedepth > depth)
				return -FDT_ERR_NOTFOUND;
			else
				return supernodeoffset;
		}
	}

--- 8< ---

The test 'offset == nodeoffset' is the problematic one. nodeoffset is the parameter passed to the function.

I have chosen to avoid offset 0 for the root node and I have updated 'nodeoffset' previously if it is 0.

Quoted 8 lines

Even if fdt_next_node() updates 'offset' if it is 0, 'nodeoffset' has also to be update if it is 0. Indeed, 'offset' will be updated from 0 to the real root node offset. In all case to have the test be correct, 'nodeoffset' should be updated to the real root node offset if it is 0.

Having fdt_next_node() updating 'offset' if it is 0 will not handle all case. When offsets comparison is done, both offsets should consider the real offset of the root node instead of the 0 value.

Ah, right. I missed the fact it was updating the nodeoffset parameter, rather than the working/starting offset.

Quoted 3 lines

Also the fdt_supernode_atdepth_offset() can be called with 'nodeoffset' set to the real root node offset instead of 0. Indeed, fdt_root_offset() is available (and needed).

Theoretically we could avoid explicitly looking at the root offset for 'offset', by starting 'offset' negative and moving the fdt_next_node() to the start of the loop body instead of the end. That would handle the nodeoffset == root_offset case, not not the nodeoffset == 0 case. Arguably we could disallow the later - finding the non-existent supernode of something we know at compile time to be the root node isn't very useful - if it only turned out to be the root node at runtime, I'd expect it to have come from another function, which should give us root_offset rather than 0.

Quoted 5 lines

But.. it's certainly safer to keep it working whether passed 0 or the real root offset. There are other ways we could do it, but I think they'd turn out equally inelegant.

Ok, makes sense to me.

Ok, I will update fdt_check_node_offset_() to have it updating its offset parameter to the real offset of the root node when its value is 0.

Based on this update, will see where it goes. I mean, impacts on callers, if it simplifies things or not, if the offset update needs also to be propagate to caller's parameter or any other similar point that we can see during the implementation.

Having something implemented and available in a patch will be the best to compare changes and impacts related to fdt_check_node_offset_() update.

Quoted 6 lines

Here we have a version of handling offset 0 vs real root node without any offset update done in fdt_check_node_offset_(). In the next iteration we will have the version with update done in fdt_check_node_offset_().

I think the golden rules to follow on this point is "keep it as simple as possible".

Agreed. Feel free to repost just the NOP before root patches on their own. At this time, frequent small series is easier for me to tackle than occasional large series.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#9 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Hi David,

On Wed, 2 Sep 2026 17:06:03 +1000
David Gibson <[email protected]> wrote:

...

Quoted 16 lines
Quoted 16 lines

Ok, I will update fdt_check_node_offset_() to have it updating its offset parameter to the real offset of the root node when its value is 0.

Based on this update, will see where it goes. I mean, impacts on callers, if it simplifies things or not, if the offset update needs also to be propagate to caller's parameter or any other similar point that we can see during the implementation.

Having something implemented and available in a patch will be the best to compare changes and impacts related to fdt_check_node_offset_() update.

Here we have a version of handling offset 0 vs real root node without any offset update done in fdt_check_node_offset_(). In the next iteration we will have the version with update done in fdt_check_node_offset_().

Quoted 7 lines
Quoted 2 lines

I think the golden rules to follow on this point is "keep it as simple as possible".

Agreed. Feel free to repost just the NOP before root patches on their own. At this time, frequent small series is easier for me to tackle than occasional large series.

I've moved forward on the fdt_check_node_offset_() update.

The new fdt_check_node_offset_() looks like this:
--- 8< ---
int fdt_check_node_offset_(const void *fdt, int *offset)

{
	int nextoffset;

	if (!can_assume(VALID_INPUT)
	    && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
		return -FDT_ERR_BADOFFSET;

	if (*offset == 0) {
		*offset = fdt_root_offset(fdt);
		if (*offset < 0)
			return *offset;
	}

	if (fdt_next_tag(fdt, *offset, &nextoffset) != FDT_BEGIN_NODE)
		return -FDT_ERR_BADOFFSET;

	return nextoffset;
}

--- 8< ---

If the given offset is 0, fdt_check_node_offset_() considers we want to check the root node and so update offset to the real root node offset.

Ok, I still need some fdt_root_offset() calls from some other parts but that's not my main issue.

My main issue comes with orphan nodes in addons. fdt_check_node_offset_() is called with offset pointing to an orphan node and this offset can be 0.

The offset 0 seen by fdt_check_node_offset_() can be the "fake" offset of a root node and in that case fdt_check_node_offset_() should update offset to the real root node offset but it can also be the offset of the orphan node we want to check and in that case the offset should not be updated.

fdt_check_node_offset_() cannot determine whether or not the offset should be updated.

With orphan nodes in the loop, fdt_check_node_offset_() becomes:
--- 8< ---
int fdt_check_node_offset_(const void *fdt, int *offset)

{
        int nextoffset;
        uint32_t tag;

        if (!can_assume(VALID_INPUT)
            && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
                return -FDT_ERR_BADOFFSET;

        if (*offset == 0) {
#pragma message "We have a problem!"
                /*
                 * An orphan node can be present at offset 0.
                 * In that case, looking for the root node may or may not be
                 * correct.
                 * Indeed is offset = 0 requested because we want the root
                 * node and sadly an orphan node is available at offset 0 or
                 * is it requested because we want to really check the orphan
                 * node available at offset 0. How to determine the correct
                 * case?
                 */
                tag = fdt_next_tag(fdt, *offset, &nextoffset);
                if (tag == FDT_BEGIN_NODE || tag == FDT_BEGIN_NODE_REF)
                        return nextoffset;

                *offset = fdt_root_offset(fdt);
                if (*offset < 0)
                        return *offset;
        }

        tag = fdt_next_tag(fdt, *offset, &nextoffset);
        if (tag != FDT_BEGIN_NODE && tag != FDT_BEGIN_NODE_REF)
                return -FDT_ERR_BADOFFSET;

        return nextoffset;
}

--- 8< ---

Of course, extra complexity could be added such as an additional parameter but I don't think it would make sense.

The simplest way to handle the case is to not update the offset in fdt_check_node_offset_() and let callers to pass the offset pointing to the real node offset expected to be checked. This is my initial proposal.

Of course, I am still open to other ideas.

For information, without addons and orphan nodes, just to compare against my original proposal, the full patch ("libfdt: Don't assume the root node is available at offset 0") with the offset update done in fdt_check_node_offset_() becomes:
--- 8< ---

libfdt/fdt.c +38 -5
index 56d4dcb2..d4d4b64b 100644
@@ -228,16 +228,24 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 	return tag;
 }
 
-int fdt_check_node_offset_(const void *fdt, int offset)
+int fdt_check_node_offset_(const void *fdt, int *offset)
 {
+	int nextoffset;
+
 	if (!can_assume(VALID_INPUT)
-	    && ((offset < 0) || (offset % FDT_TAGSIZE)))
+	    && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
 		return -FDT_ERR_BADOFFSET;
 
-	if (fdt_next_tag(fdt, offset, &offset) != FDT_BEGIN_NODE)
+	if (*offset == 0) {
+		*offset = fdt_root_offset(fdt);
+		if (*offset < 0)
+			return *offset;
+	}
+
+	if (fdt_next_tag(fdt, *offset, &nextoffset) != FDT_BEGIN_NODE)
 		return -FDT_ERR_BADOFFSET;
 
-	return offset;
+	return nextoffset;
 }
 
 int fdt_check_prop_offset_(const void *fdt, int offset)
@@ -252,13 +260,38 @@ int fdt_check_prop_offset_(const void *fdt, int offset)
 	return offset;
 }
 
+int fdt_root_offset(const void *fdt)
+{
+	int nextoffset = 0;
+	int offset;
+	uint32_t tag;
+
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		switch (tag) {
+		case FDT_END_NODE:
+		case FDT_PROP:
+			return -FDT_ERR_BADSTRUCTURE;
+
+		case FDT_BEGIN_NODE:
+			return offset;
+
+		default:
+			break;
+		}
+	} while (tag != FDT_END);
+
+	return (nextoffset < 0) ? nextoffset : -FDT_ERR_NOTFOUND;
+}
+
 int fdt_next_node(const void *fdt, int offset, int *depth)
 {
 	int nextoffset = 0;
 	uint32_t tag;
 
 	if (offset >= 0)
-		if ((nextoffset = fdt_check_node_offset_(fdt, offset)) < 0)
+		if ((nextoffset = fdt_check_node_offset_(fdt, &offset)) < 0)
 			return nextoffset;
 
 	do {
libfdt/fdt_ro.c +42 -14

115 lines not on this page · raw message

libfdt/fdt_rw.c +7 -1
index 850aafe4..a1a07f01 100644
@@ -226,7 +226,7 @@ static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 	int err;
 	int allocated;
 
-	if ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
+	if ((nextoffset = fdt_check_node_offset_(fdt, &nodeoffset)) < 0)
 		return nextoffset;
 
 	namestroff = fdt_find_add_string_(fdt, name, namelen, &allocated);
@@ -377,6 +377,12 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 
 	FDT_RW_PROBE(fdt);
 
+	if (!parentoffset) {
+		parentoffset = fdt_root_offset(fdt);
+		if (parentoffset < 0)
+			return parentoffset;
+	}
+
 	offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);
 	if (offset >= 0)
 		return -FDT_ERR_EXISTS;
libfdt/libfdt.h +14 -1
index c69a18ed..7a1915a5 100644
@@ -503,6 +503,19 @@ int fdt_num_mem_rsv(const void *fdt);
  */
 int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size);
 
+/**
+ * fdt_root_offset - Get the offset of the root node
+ * @fdt: pointer to the device tree blob
+ *
+ * The root node can be located after the offset 0. Indeed FDT_NOP tags can be
+ * present at offset 0. fdt_root_offset() takes care of those possible FDT_NOP
+ * tags.
+ *
+ * returns: offset of the root node or negative libfdt error value otherwise
+ */
+int fdt_root_offset(const void *fdt);
+
+
 /**
  * fdt_subnode_offset_namelen - find a subnode based on substring
  * @fdt: pointer to the device tree blob
@@ -1025,7 +1038,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen);
  * at a specific depth from the root (where the root itself has depth
  * 0, its immediate subnodes depth 1 and so forth).  So
  *	fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, NULL);
- * will always return 0, the offset of the root node.  If the node at
+ * will always return the offset of the root node.  If the node at
  * nodeoffset has depth D, then:
  *	fdt_supernode_atdepth_offset(fdt, nodeoffset, D, NULL);
  * will return nodeoffset itself.
libfdt/libfdt_internal.h +1 -1
index 0e103caf..d5072279 100644
@@ -20,7 +20,7 @@ int32_t fdt_ro_probe_(const void *fdt);
 		}							\
 	}
 
-int fdt_check_node_offset_(const void *fdt, int offset);
+int fdt_check_node_offset_(const void *fdt, int *offset);
 int fdt_check_prop_offset_(const void *fdt, int offset);
 
 const char *fdt_find_string_len_(const char *strtab, int tabsize, const char *s,
libfdt/version.lds +1 -0
index cbfef546..d0b71669 100644
@@ -7,6 +7,7 @@ LIBFDT_1.2 {
 		fdt_string;
 		fdt_num_mem_rsv;
 		fdt_get_mem_rsv;
+		fdt_root_offset;
 		fdt_subnode_offset_namelen;
 		fdt_subnode_offset;
 		fdt_path_offset_namelen;

--- 8< ---

I hope all of those details will help to move forward.

Best regards,
Hervé

#10 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Quoted 53 lines · Herve Codina

Hi David,

On Wed, 2 Sep 2026 17:06:03 +1000
David Gibson <[email protected]> wrote:

...

Quoted 16 lines
Quoted 16 lines

Ok, I will update fdt_check_node_offset_() to have it updating its offset parameter to the real offset of the root node when its value is 0.

Based on this update, will see where it goes. I mean, impacts on callers, if it simplifies things or not, if the offset update needs also to be propagate to caller's parameter or any other similar point that we can see during the implementation.

Having something implemented and available in a patch will be the best to compare changes and impacts related to fdt_check_node_offset_() update.

Here we have a version of handling offset 0 vs real root node without any offset update done in fdt_check_node_offset_(). In the next iteration we will have the version with update done in fdt_check_node_offset_().

Quoted 7 lines
Quoted 2 lines

I think the golden rules to follow on this point is "keep it as simple as possible".

Agreed. Feel free to repost just the NOP before root patches on their own. At this time, frequent small series is easier for me to tackle than occasional large series.

I've moved forward on the fdt_check_node_offset_() update.

The new fdt_check_node_offset_() looks like this:
--- 8< ---
int fdt_check_node_offset_(const void *fdt, int *offset)

{
	int nextoffset;

	if (!can_assume(VALID_INPUT)
	    && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
		return -FDT_ERR_BADOFFSET;

	if (*offset == 0) {
		*offset = fdt_root_offset(fdt);
		if (*offset < 0)
			return *offset;
	}

	if (fdt_next_tag(fdt, *offset, &nextoffset) != FDT_BEGIN_NODE)
		return -FDT_ERR_BADOFFSET;

	return nextoffset;
}
Quoted 1 line

--- 8< ---

That looks fine. If it was an exposed function I'd want to look for a better interface, but as an internal function it's fine.

Quoted 9 lines

If the given offset is 0, fdt_check_node_offset_() considers we want to check the root node and so update offset to the real root node offset.

Ok, I still need some fdt_root_offset() calls from some other parts but that's not my main issue.

My main issue comes with orphan nodes in addons. fdt_check_node_offset_() is called with offset pointing to an orphan node and this offset can be 0.

Quoted 7 lines

The offset 0 seen by fdt_check_node_offset_() can be the "fake" offset of a root node and in that case fdt_check_node_offset_() should update offset to the real root node offset but it can also be the offset of the orphan node we want to check and in that case the offset should not be updated.

fdt_check_node_offset_() cannot determine whether or not the offset should be updated.

Hrm. But if offset 0 has an orphan node, we can see that with the FDT_BEGIN_NODE or FDT_BEGIN_NODE_REF there, right?

Quoted 38 lines

With orphan nodes in the loop, fdt_check_node_offset_() becomes:
--- 8< ---
int fdt_check_node_offset_(const void *fdt, int *offset)

{
        int nextoffset;
        uint32_t tag;

        if (!can_assume(VALID_INPUT)
            && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
                return -FDT_ERR_BADOFFSET;

        if (*offset == 0) {
#pragma message "We have a problem!"
                /*
                 * An orphan node can be present at offset 0.
                 * In that case, looking for the root node may or may not be
                 * correct.
                 * Indeed is offset = 0 requested because we want the root
                 * node and sadly an orphan node is available at offset 0 or
                 * is it requested because we want to really check the orphan
                 * node available at offset 0. How to determine the correct
                 * case?
                 */
                tag = fdt_next_tag(fdt, *offset, &nextoffset);
                if (tag == FDT_BEGIN_NODE || tag == FDT_BEGIN_NODE_REF)
                        return nextoffset;

                *offset = fdt_root_offset(fdt);
                if (*offset < 0)
                        return *offset;
        }

        tag = fdt_next_tag(fdt, *offset, &nextoffset);
        if (tag != FDT_BEGIN_NODE && tag != FDT_BEGIN_NODE_REF)
                return -FDT_ERR_BADOFFSET;

        return nextoffset;
}
Quoted 1 line

--- 8< ---

Right.. like that. Except simpler would be to have fdt_root_offset() stop when it sees a FDT_BEGIN_NODE_REF as well as a FDT_BEGIN_NODE. Or maybe that should be, say, fdt_root_offset_(), and fdt_root_offset() will wrap it to return an error on an addon tree with no root.

Quoted 6 lines

Of course, extra complexity could be added such as an additional parameter but I don't think it would make sense.

The simplest way to handle the case is to not update the offset in fdt_check_node_offset_() and let callers to pass the offset pointing to the real node offset expected to be checked. This is my initial proposal.

Even with the bulky fdt_check_node_offset_() above that doesn't seem simpler to me. fdt_check_node_offset_() is largish, but the complexity is all in one place rather than distributed everywhere.

Quoted 299 lines

Of course, I am still open to other ideas.

For information, without addons and orphan nodes, just to compare against my original proposal, the full patch ("libfdt: Don't assume the root node is available at offset 0") with the offset update done in fdt_check_node_offset_() becomes:
--- 8< ---

libfdt/fdt.c +38 -5
index 56d4dcb2..d4d4b64b 100644
@@ -228,16 +228,24 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 	return tag;
 }
 
-int fdt_check_node_offset_(const void *fdt, int offset)
+int fdt_check_node_offset_(const void *fdt, int *offset)
 {
+	int nextoffset;
+
 	if (!can_assume(VALID_INPUT)
-	    && ((offset < 0) || (offset % FDT_TAGSIZE)))
+	    && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
 		return -FDT_ERR_BADOFFSET;
 
-	if (fdt_next_tag(fdt, offset, &offset) != FDT_BEGIN_NODE)
+	if (*offset == 0) {
+		*offset = fdt_root_offset(fdt);
+		if (*offset < 0)
+			return *offset;
+	}
+
+	if (fdt_next_tag(fdt, *offset, &nextoffset) != FDT_BEGIN_NODE)
 		return -FDT_ERR_BADOFFSET;
 
-	return offset;
+	return nextoffset;
 }
 
 int fdt_check_prop_offset_(const void *fdt, int offset)
@@ -252,13 +260,38 @@ int fdt_check_prop_offset_(const void *fdt, int offset)
 	return offset;
 }
 
+int fdt_root_offset(const void *fdt)
+{
+	int nextoffset = 0;
+	int offset;
+	uint32_t tag;
+
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		switch (tag) {
+		case FDT_END_NODE:
+		case FDT_PROP:
+			return -FDT_ERR_BADSTRUCTURE;
+
+		case FDT_BEGIN_NODE:
+			return offset;
+
+		default:
+			break;
+		}
+	} while (tag != FDT_END);
+
+	return (nextoffset < 0) ? nextoffset : -FDT_ERR_NOTFOUND;
+}
+
 int fdt_next_node(const void *fdt, int offset, int *depth)
 {
 	int nextoffset = 0;
 	uint32_t tag;
 
 	if (offset >= 0)
-		if ((nextoffset = fdt_check_node_offset_(fdt, offset)) < 0)
+		if ((nextoffset = fdt_check_node_offset_(fdt, &offset)) < 0)
 			return nextoffset;
 
 	do {
libfdt/fdt_ro.c +42 -14
index 11f2e2ee..ec8af835 100644
@@ -281,7 +281,7 @@ int fdt_path_offset_namelen(const void *fdt, const char *path, int namelen)
 		while (*p == '/') {
 			p++;
 			if (p == end)
-				return offset;
+				goto terminate;
 		}
 		q = memchr(p, '/', end - p);
 		if (! q)
@@ -294,7 +294,13 @@ int fdt_path_offset_namelen(const void *fdt, const char *path, int namelen)
 		p = q;
 	}
 
-	return offset;
+terminate:
+        /*
+         * Avoid returning offset 0 or the real root offset.
+         * Be sure to return one and only one offset for the root node, its
+         * real offset.
+         */
+	return offset ? offset : fdt_root_offset(fdt);
 }
 
 int fdt_path_offset(const void *fdt, const char *path)
@@ -304,14 +310,17 @@ int fdt_path_offset(const void *fdt, const char *path)
 
 const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
 {
-	const struct fdt_node_header *nh = fdt_offset_ptr_(fdt, nodeoffset);
+	const struct fdt_node_header *nh;
 	const char *nameptr;
 	int err;
 
-	if (!can_assume(VALID_DTB) && (((err = fdt_ro_probe_(fdt)) < 0)
-	    || ((err = fdt_check_node_offset_(fdt, nodeoffset)) < 0)))
-			goto fail;
+	if (!can_assume(VALID_DTB) && (err = fdt_ro_probe_(fdt)) < 0)
+		goto fail;
+
+	if ((err = fdt_check_node_offset_(fdt, &nodeoffset)) < 0)
+		goto fail;
 
+	nh = fdt_offset_ptr_(fdt, nodeoffset);
 	nameptr = nh->name;
 
 	if (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {
@@ -344,7 +353,7 @@ int fdt_first_property_offset(const void *fdt, int nodeoffset)
 {
 	int offset;
 
-	if ((offset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
+	if ((offset = fdt_check_node_offset_(fdt, &nodeoffset)) < 0)
 		return offset;
 
 	return nextprop_(fdt, offset);
@@ -574,6 +583,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
 {
 	int pdepth = 0, p = 0;
 	int offset, depth, namelen;
+	int root_offset;
 	const char *name;
 
 	FDT_RO_PROBE(fdt);
@@ -581,7 +591,14 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
 	if (buflen < 2)
 		return -FDT_ERR_NOSPACE;
 
-	for (offset = 0, depth = 0;
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		return root_offset;
+
+	if (!nodeoffset)
+		nodeoffset = root_offset;
+
+	for (offset = root_offset, depth = 0;
 	     (offset >= 0) && (offset <= nodeoffset);
 	     offset = fdt_next_node(fdt, offset, &depth)) {
 		while (pdepth > depth) {
@@ -627,13 +644,21 @@ int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
 {
 	int offset, depth;
 	int supernodeoffset = -FDT_ERR_INTERNAL;
+	int root_offset;
 
 	FDT_RO_PROBE(fdt);
 
 	if (supernodedepth < 0)
 		return -FDT_ERR_NOTFOUND;
 
-	for (offset = 0, depth = 0;
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		return root_offset;
+
+	if (!nodeoffset)
+		nodeoffset = root_offset;
+
+	for (offset = root_offset, depth = 0;
 	     (offset >= 0) && (offset <= nodeoffset);
 	     offset = fdt_next_node(fdt, offset, &depth)) {
 		if (depth == supernodedepth)
@@ -663,12 +688,15 @@ int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
 int fdt_node_depth(const void *fdt, int nodeoffset)
 {
 	int nodedepth;
-	int err;
+	int offset;
+
+	offset = fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, &nodedepth);
+	if (offset < 0)
+		return offset;
+
+	if (!can_assume(LIBFDT_FLAWLESS) && offset != fdt_root_offset(fdt))
+		return -FDT_ERR_INTERNAL;
 
-	err = fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, &nodedepth);
-	if (err)
-		return (can_assume(LIBFDT_FLAWLESS) || err < 0) ? err :
-			-FDT_ERR_INTERNAL;
 	return nodedepth;
 }
 
libfdt/fdt_rw.c +7 -1
index 850aafe4..a1a07f01 100644
@@ -226,7 +226,7 @@ static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 	int err;
 	int allocated;
 
-	if ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
+	if ((nextoffset = fdt_check_node_offset_(fdt, &nodeoffset)) < 0)
 		return nextoffset;
 
 	namestroff = fdt_find_add_string_(fdt, name, namelen, &allocated);
@@ -377,6 +377,12 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 
 	FDT_RW_PROBE(fdt);
 
+	if (!parentoffset) {
+		parentoffset = fdt_root_offset(fdt);
+		if (parentoffset < 0)
+			return parentoffset;
+	}
+
 	offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);
 	if (offset >= 0)
 		return -FDT_ERR_EXISTS;
libfdt/libfdt.h +14 -1
index c69a18ed..7a1915a5 100644
@@ -503,6 +503,19 @@ int fdt_num_mem_rsv(const void *fdt);
  */
 int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size);
 
+/**
+ * fdt_root_offset - Get the offset of the root node
+ * @fdt: pointer to the device tree blob
+ *
+ * The root node can be located after the offset 0. Indeed FDT_NOP tags can be
+ * present at offset 0. fdt_root_offset() takes care of those possible FDT_NOP
+ * tags.
+ *
+ * returns: offset of the root node or negative libfdt error value otherwise
+ */
+int fdt_root_offset(const void *fdt);
+
+
 /**
  * fdt_subnode_offset_namelen - find a subnode based on substring
  * @fdt: pointer to the device tree blob
@@ -1025,7 +1038,7 @@ int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen);
  * at a specific depth from the root (where the root itself has depth
  * 0, its immediate subnodes depth 1 and so forth).  So
  *	fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, NULL);
- * will always return 0, the offset of the root node.  If the node at
+ * will always return the offset of the root node.  If the node at
  * nodeoffset has depth D, then:
  *	fdt_supernode_atdepth_offset(fdt, nodeoffset, D, NULL);
  * will return nodeoffset itself.
libfdt/libfdt_internal.h +1 -1
index 0e103caf..d5072279 100644
@@ -20,7 +20,7 @@ int32_t fdt_ro_probe_(const void *fdt);
 		}							\
 	}
 
-int fdt_check_node_offset_(const void *fdt, int offset);
+int fdt_check_node_offset_(const void *fdt, int *offset);
 int fdt_check_prop_offset_(const void *fdt, int offset);
 
 const char *fdt_find_string_len_(const char *strtab, int tabsize, const char *s,
libfdt/version.lds +1 -1
index cbfef546..d0b71669 100644
@@ -7,6 +7,7 @@ LIBFDT_1.2 {
 		fdt_string;
 		fdt_num_mem_rsv;
 		fdt_get_mem_rsv;
+		fdt_root_offset;
 		fdt_subnode_offset_namelen;
 		fdt_subnode_offset;
 		fdt_path_offset_namelen;
--- 8< ---

I hope all of those details will help to move forward.

Best regards,
Hervé

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#11 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Quoted 119 lines · On Tue, 8 Sep 2026 16:41:06 +1000 David Gibson <[email protected]>…
Quoted 53 lines · Herve Codina

Hi David,

On Wed, 2 Sep 2026 17:06:03 +1000
David Gibson <[email protected]> wrote:

...

Quoted 16 lines
Quoted 16 lines

Ok, I will update fdt_check_node_offset_() to have it updating its offset parameter to the real offset of the root node when its value is 0.

Based on this update, will see where it goes. I mean, impacts on callers, if it simplifies things or not, if the offset update needs also to be propagate to caller's parameter or any other similar point that we can see during the implementation.

Having something implemented and available in a patch will be the best to compare changes and impacts related to fdt_check_node_offset_() update.

Here we have a version of handling offset 0 vs real root node without any offset update done in fdt_check_node_offset_(). In the next iteration we will have the version with update done in fdt_check_node_offset_().

Quoted 7 lines
Quoted 2 lines

I think the golden rules to follow on this point is "keep it as simple as possible".

Agreed. Feel free to repost just the NOP before root patches on their own. At this time, frequent small series is easier for me to tackle than occasional large series.

I've moved forward on the fdt_check_node_offset_() update.

The new fdt_check_node_offset_() looks like this:
--- 8< ---
int fdt_check_node_offset_(const void *fdt, int *offset)

{
	int nextoffset;

	if (!can_assume(VALID_INPUT)
	    && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
		return -FDT_ERR_BADOFFSET;

	if (*offset == 0) {
		*offset = fdt_root_offset(fdt);
		if (*offset < 0)
			return *offset;
	}

	if (fdt_next_tag(fdt, *offset, &nextoffset) != FDT_BEGIN_NODE)
		return -FDT_ERR_BADOFFSET;

	return nextoffset;
}
Quoted 1 line

--- 8< ---

That looks fine. If it was an exposed function I'd want to look for a better interface, but as an internal function it's fine.

Quoted 9 lines

If the given offset is 0, fdt_check_node_offset_() considers we want to check the root node and so update offset to the real root node offset.

Ok, I still need some fdt_root_offset() calls from some other parts but that's not my main issue.

My main issue comes with orphan nodes in addons. fdt_check_node_offset_() is called with offset pointing to an orphan node and this offset can be 0.

Quoted 7 lines

The offset 0 seen by fdt_check_node_offset_() can be the "fake" offset of a root node and in that case fdt_check_node_offset_() should update offset to the real root node offset but it can also be the offset of the orphan node we want to check and in that case the offset should not be updated.

fdt_check_node_offset_() cannot determine whether or not the offset should be updated.

Hrm. But if offset 0 has an orphan node, we can see that with the FDT_BEGIN_NODE or FDT_BEGIN_NODE_REF there, right?

Quoted 38 lines

With orphan nodes in the loop, fdt_check_node_offset_() becomes:
--- 8< ---
int fdt_check_node_offset_(const void *fdt, int *offset)

{
        int nextoffset;
        uint32_t tag;

        if (!can_assume(VALID_INPUT)
            && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
                return -FDT_ERR_BADOFFSET;

        if (*offset == 0) {
#pragma message "We have a problem!"
                /*
                 * An orphan node can be present at offset 0.
                 * In that case, looking for the root node may or may not be
                 * correct.
                 * Indeed is offset = 0 requested because we want the root
                 * node and sadly an orphan node is available at offset 0 or
                 * is it requested because we want to really check the orphan
                 * node available at offset 0. How to determine the correct
                 * case?
                 */
                tag = fdt_next_tag(fdt, *offset, &nextoffset);
                if (tag == FDT_BEGIN_NODE || tag == FDT_BEGIN_NODE_REF)
                        return nextoffset;

                *offset = fdt_root_offset(fdt);
                if (*offset < 0)
                        return *offset;
        }

        tag = fdt_next_tag(fdt, *offset, &nextoffset);
        if (tag != FDT_BEGIN_NODE && tag != FDT_BEGIN_NODE_REF)
                return -FDT_ERR_BADOFFSET;

        return nextoffset;
}
Quoted 1 line

--- 8< ---

Quoted 5 lines

Right.. like that. Except simpler would be to have fdt_root_offset() stop when it sees a FDT_BEGIN_NODE_REF as well as a FDT_BEGIN_NODE. Or maybe that should be, say, fdt_root_offset_(), and fdt_root_offset() will wrap it to return an error on an addon tree with no root.

No, fdt_root_offset() must get the root node offset. An orphan node identified with FDT_BEGIN_NODE_REF cannot be a root node.

An addon can have, a root node only, orphan nodes only or both a root node and orphan nodes.

fdt_root_offset() looks for the root node (i.e. the first FDT_BEGIN_NODE at top level). If not found, -ERRNOTFOUND (addon) or -ERRBADSTRUCTURE (not addon).

Having a fdt_root_offset() stop at either FDT_BEGIN_NODE_REF or FDT_BEGIN_NODE is "fdt_first_node_offset()".

Let me introduce the internal fdt_first_node_offset_()
- fdt_root_offset()
It calls fdt_first_node_offset_() and check that this node is a FDT_BEGIN_NODE node.

- fdt_check_node_offset_()
if the offset == 0, it updates the value with the offset returned by fdt_first_node_offset_()

And so, a node offset 0 doesn't means the root node but the first node in the dtb (root or orphan). I am totally fine with this definition.

At some point, maybe users of the API (when addon are involved) will have to take care of that and perform something like:
root = fdt_root_offset();
fdt_get_property(fdt, root, "prop", NULL);

Or

  fdt_for_each_orphan(orphan, fdt) {
     fdt_get_property(fdt, orphan, "prop", NULL);
     ...

}

Here also, I am totally fine with that an I already use this kind of sequence in libfdt/fdt_addon.c to apply an addon on a base dtb.

I will introduce fdt_first_node_offset_() but let me know if you prefer having fdt_first_node_offset_() introduced right now in this "structure tags" series or later in the addon series.

Best regards,
Hervé

#12 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Quoted 140 lines · Herve Codina
Quoted 119 lines · On Tue, 8 Sep 2026 16:41:06 +1000 David Gibson <[email protected]>…
Quoted 53 lines · Herve Codina

Hi David,

On Wed, 2 Sep 2026 17:06:03 +1000
David Gibson <[email protected]> wrote:

...

Quoted 16 lines
Quoted 16 lines

Ok, I will update fdt_check_node_offset_() to have it updating its offset parameter to the real offset of the root node when its value is 0.

Based on this update, will see where it goes. I mean, impacts on callers, if it simplifies things or not, if the offset update needs also to be propagate to caller's parameter or any other similar point that we can see during the implementation.

Having something implemented and available in a patch will be the best to compare changes and impacts related to fdt_check_node_offset_() update.

Here we have a version of handling offset 0 vs real root node without any offset update done in fdt_check_node_offset_(). In the next iteration we will have the version with update done in fdt_check_node_offset_().

Quoted 7 lines
Quoted 2 lines

I think the golden rules to follow on this point is "keep it as simple as possible".

Agreed. Feel free to repost just the NOP before root patches on their own. At this time, frequent small series is easier for me to tackle than occasional large series.

I've moved forward on the fdt_check_node_offset_() update.

The new fdt_check_node_offset_() looks like this:
--- 8< ---
int fdt_check_node_offset_(const void *fdt, int *offset)

{
	int nextoffset;

	if (!can_assume(VALID_INPUT)
	    && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
		return -FDT_ERR_BADOFFSET;

	if (*offset == 0) {
		*offset = fdt_root_offset(fdt);
		if (*offset < 0)
			return *offset;
	}

	if (fdt_next_tag(fdt, *offset, &nextoffset) != FDT_BEGIN_NODE)
		return -FDT_ERR_BADOFFSET;

	return nextoffset;
}
Quoted 1 line

--- 8< ---

That looks fine. If it was an exposed function I'd want to look for a better interface, but as an internal function it's fine.

Quoted 9 lines

If the given offset is 0, fdt_check_node_offset_() considers we want to check the root node and so update offset to the real root node offset.

Ok, I still need some fdt_root_offset() calls from some other parts but that's not my main issue.

My main issue comes with orphan nodes in addons. fdt_check_node_offset_() is called with offset pointing to an orphan node and this offset can be 0.

Quoted 7 lines

The offset 0 seen by fdt_check_node_offset_() can be the "fake" offset of a root node and in that case fdt_check_node_offset_() should update offset to the real root node offset but it can also be the offset of the orphan node we want to check and in that case the offset should not be updated.

fdt_check_node_offset_() cannot determine whether or not the offset should be updated.

Hrm. But if offset 0 has an orphan node, we can see that with the FDT_BEGIN_NODE or FDT_BEGIN_NODE_REF there, right?

Quoted 38 lines

With orphan nodes in the loop, fdt_check_node_offset_() becomes:
--- 8< ---
int fdt_check_node_offset_(const void *fdt, int *offset)

{
        int nextoffset;
        uint32_t tag;

        if (!can_assume(VALID_INPUT)
            && ((*offset < 0) || (*offset % FDT_TAGSIZE)))
                return -FDT_ERR_BADOFFSET;

        if (*offset == 0) {
#pragma message "We have a problem!"
                /*
                 * An orphan node can be present at offset 0.
                 * In that case, looking for the root node may or may not be
                 * correct.
                 * Indeed is offset = 0 requested because we want the root
                 * node and sadly an orphan node is available at offset 0 or
                 * is it requested because we want to really check the orphan
                 * node available at offset 0. How to determine the correct
                 * case?
                 */
                tag = fdt_next_tag(fdt, *offset, &nextoffset);
                if (tag == FDT_BEGIN_NODE || tag == FDT_BEGIN_NODE_REF)
                        return nextoffset;

                *offset = fdt_root_offset(fdt);
                if (*offset < 0)
                        return *offset;
        }

        tag = fdt_next_tag(fdt, *offset, &nextoffset);
        if (tag != FDT_BEGIN_NODE && tag != FDT_BEGIN_NODE_REF)
                return -FDT_ERR_BADOFFSET;

        return nextoffset;
}
Quoted 1 line

--- 8< ---

Quoted 5 lines

Right.. like that. Except simpler would be to have fdt_root_offset() stop when it sees a FDT_BEGIN_NODE_REF as well as a FDT_BEGIN_NODE. Or maybe that should be, say, fdt_root_offset_(), and fdt_root_offset() will wrap it to return an error on an addon tree with no root.

No, fdt_root_offset() must get the root node offset. An orphan node identified with FDT_BEGIN_NODE_REF cannot be a root node.

An addon can have, a root node only, orphan nodes only or both a root node and orphan nodes.

fdt_root_offset() looks for the root node (i.e. the first FDT_BEGIN_NODE at top level). If not found, -ERRNOTFOUND (addon) or -ERRBADSTRUCTURE (not addon).

Having a fdt_root_offset() stop at either FDT_BEGIN_NODE_REF or FDT_BEGIN_NODE is "fdt_first_node_offset()".

Quoted 8 lines

Let me introduce the internal fdt_first_node_offset_()
- fdt_root_offset()
It calls fdt_first_node_offset_() and check that this node is a FDT_BEGIN_NODE node.

- fdt_check_node_offset_()
if the offset == 0, it updates the value with the offset returned by fdt_first_node_offset_()

Right, that's exactly what I'd suggest.

A possible tweak would be to have fdt_check_node_offset_() only apply special case 0 handling if the _actual_ offset 0 doesn't look like a valid node offset. Not sure if that will make things messier or cleaner.

Quoted 2 lines

And so, a node offset 0 doesn't means the root node but the first node in the dtb (root or orphan). I am totally fine with this definition.

Right. If you don't want that behaviour for addon dtbs, then I think the way to go would be to explicitly avoid all special case handling of 0 if the header flags an addon. Handling addons requires new code, so we don't have to maintain backwards compatibliity for things that used 0 assuming it meant root node.

Quoted 9 lines

At some point, maybe users of the API (when addon are involved) will have to take care of that and perform something like:
root = fdt_root_offset();
fdt_get_property(fdt, root, "prop", NULL);

Or

  fdt_for_each_orphan(orphan, fdt) {
     fdt_get_property(fdt, orphan, "prop", NULL);
     ...
Quoted 8 lines

}

Here also, I am totally fine with that an I already use this kind of sequence in libfdt/fdt_addon.c to apply an addon on a base dtb.

I will introduce fdt_first_node_offset_() but let me know if you prefer having fdt_first_node_offset_() introduced right now in this "structure tags" series or later in the addon series.

Either is fine; do whichever results in less code churn.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#13 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Hi David,

On Wed, 9 Sep 2026 16:18:22 +1000
David Gibson <[email protected]> wrote:

...

Quoted 40 lines
Quoted 4 lines

Having a fdt_root_offset() stop at either FDT_BEGIN_NODE_REF or FDT_BEGIN_NODE is "fdt_first_node_offset()".

Quoted 8 lines

Let me introduce the internal fdt_first_node_offset_()
- fdt_root_offset()
It calls fdt_first_node_offset_() and check that this node is a FDT_BEGIN_NODE node.

- fdt_check_node_offset_()
if the offset == 0, it updates the value with the offset returned by fdt_first_node_offset_()

Right, that's exactly what I'd suggest.

A possible tweak would be to have fdt_check_node_offset_() only apply special case 0 handling if the _actual_ offset 0 doesn't look like a valid node offset. Not sure if that will make things messier or cleaner.

Quoted 2 lines

And so, a node offset 0 doesn't means the root node but the first node in the dtb (root or orphan). I am totally fine with this definition.

Right. If you don't want that behaviour for addon dtbs, then I think the way to go would be to explicitly avoid all special case handling of 0 if the header flags an addon. Handling addons requires new code, so we don't have to maintain backwards compatibliity for things that used 0 assuming it meant root node.

Quoted 11 lines

At some point, maybe users of the API (when addon are involved) will have to take care of that and perform something like:
root = fdt_root_offset();
fdt_get_property(fdt, root, "prop", NULL);

Or

  fdt_for_each_orphan(orphan, fdt) {
     fdt_get_property(fdt, orphan, "prop", NULL);
     ...

}

Quoted 9 lines
Quoted 6 lines

Here also, I am totally fine with that an I already use this kind of sequence in libfdt/fdt_addon.c to apply an addon on a base dtb.

I will introduce fdt_first_node_offset_() but let me know if you prefer having fdt_first_node_offset_() introduced right now in this "structure tags" series or later in the addon series.

Either is fine; do whichever results in less code churn.

Ok, I will do that.

Do you want to have an early version of that or having it in the next iteration of the series is fine on you side ?

Of course, before sending a new iteration of the series, I am waiting for your feedback on the "structured tags" part. This part is not going to be impacted by the "offset 0 vs real root offset" we have discussed here and so what is available in this current series is still valid.

Best regards,
Hervé

#14 lore raw

Re: [PATCH v3 02/15] libfdt: Don't assume the root node is available at offset 0

Quoted 54 lines · Herve Codina

Hi David,

On Wed, 9 Sep 2026 16:18:22 +1000
David Gibson <[email protected]> wrote:

...

Quoted 47 lines
Quoted 4 lines

Having a fdt_root_offset() stop at either FDT_BEGIN_NODE_REF or FDT_BEGIN_NODE is "fdt_first_node_offset()".

Quoted 8 lines

Let me introduce the internal fdt_first_node_offset_()
- fdt_root_offset()
It calls fdt_first_node_offset_() and check that this node is a FDT_BEGIN_NODE node.

- fdt_check_node_offset_()
if the offset == 0, it updates the value with the offset returned by fdt_first_node_offset_()

Right, that's exactly what I'd suggest.

A possible tweak would be to have fdt_check_node_offset_() only apply special case 0 handling if the _actual_ offset 0 doesn't look like a valid node offset. Not sure if that will make things messier or cleaner.

Quoted 2 lines

And so, a node offset 0 doesn't means the root node but the first node in the dtb (root or orphan). I am totally fine with this definition.

Right. If you don't want that behaviour for addon dtbs, then I think the way to go would be to explicitly avoid all special case handling of 0 if the header flags an addon. Handling addons requires new code, so we don't have to maintain backwards compatibliity for things that used 0 assuming it meant root node.

Quoted 17 lines

At some point, maybe users of the API (when addon are involved) will have to take care of that and perform something like:
root = fdt_root_offset();
fdt_get_property(fdt, root, "prop", NULL);

Or

  fdt_for_each_orphan(orphan, fdt) {
     fdt_get_property(fdt, orphan, "prop", NULL);
     ...

}

Here also, I am totally fine with that an I already use this kind of sequence in libfdt/fdt_addon.c to apply an addon on a base dtb.

I will introduce fdt_first_node_offset_() but let me know if you prefer having fdt_first_node_offset_() introduced right now in this "structure tags" series or later in the addon series.

Quoted 7 lines
Quoted 2 lines

Either is fine; do whichever results in less code churn.

Ok, I will do that.

Do you want to have an early version of that or having it in the next iteration of the series is fine on you side ?

Early is good. Smaller series are easier to review, and getting them fully sorted and merged also makes things easier.

Quoted 5 lines

Of course, before sending a new iteration of the series, I am waiting for your feedback on the "structured tags" part. This part is not going to be impacted by the "offset 0 vs real root offset" we have discussed here and so what is available in this current series is still valid.

Right, the root offset stuff stands on its own, so it can sensibly be split off. Splitting series in such a way that they don't have enough context to understand the wouldn't be helpful, of course.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#15 lore raw

PATCH v3 3/15 tests: Don't assume the root node is available at offset 0

In reply to Herve Codina

Several tests uses offset 0 as the offset of the root node. Either to check the offset returned by tested functions or to directly manipulate the root node retrieved using fdt_offset_ptr(fdt, 0, ...).

The root node is not always at offset 0. Indeed, a FDT_NOP tag can be present at offset 0. fdt_root_offset() returns the offset of the root node taking care of possible FDT_NOP tag.

Use fdt_root_offset() to get the offset of the root node and use this value whenever the offset of the root node is expected.

---
 tests/node_offset_by_compatible.c |  4 +++-
 tests/node_offset_by_prop_value.c | 11 +++++++----
 tests/path_offset.c               | 13 +++++++++----
 tests/root_node.c                 |  6 +++++-
 4 files changed, 24 insertions(+), 10 deletions(-)
tests/node_offset_by_compatible.c +3 -1
index a9e67835..1278a562 100644
@@ -39,12 +39,14 @@ static void check_search(void *fdt, const char *compat, ...)
 int main(int argc, char *argv[])
 {
 	void *fdt;
+	int root_offset;
 	int subnode1_offset, subnode2_offset;
 	int subsubnode1_offset, subsubnode2_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
+	root_offset = fdt_root_offset(fdt);
 	subnode1_offset = fdt_path_offset(fdt, "/subnode@1");
 	subnode2_offset = fdt_path_offset(fdt, "/subnode@2");
 	subsubnode1_offset = fdt_path_offset(fdt, "/subnode@1/subsubnode");
@@ -54,7 +56,7 @@ int main(int argc, char *argv[])
 	    || (subsubnode1_offset < 0) || (subsubnode2_offset < 0))
 		FAIL("Can't find required nodes");
 
-	check_search(fdt, "test_tree1", 0, -FDT_ERR_NOTFOUND);
+	check_search(fdt, "test_tree1", root_offset, -FDT_ERR_NOTFOUND);
 	check_search(fdt, "subnode1", subnode1_offset, -FDT_ERR_NOTFOUND);
 	check_search(fdt, "subsubnode1", subsubnode1_offset, -FDT_ERR_NOTFOUND);
 	check_search(fdt, "subsubnode2", subsubnode2_offset, -FDT_ERR_NOTFOUND);
tests/node_offset_by_prop_value.c +7 -4
index 48ab1d93..329409b9 100644
@@ -64,12 +64,14 @@ static void check_search_str(void *fdt, const char *propname,
 int main(int argc, char *argv[])
 {
 	void *fdt;
+	int root_offset;
 	int subnode1_offset, subnode2_offset;
 	int subsubnode1_offset, subsubnode2_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
+	root_offset = fdt_root_offset(fdt);
 	subnode1_offset = fdt_path_offset(fdt, "/subnode@1");
 	subnode2_offset = fdt_path_offset(fdt, "/subnode@2");
 	subsubnode1_offset = fdt_path_offset(fdt, "/subnode@1/subsubnode");
@@ -79,19 +81,20 @@ int main(int argc, char *argv[])
 	    || (subsubnode1_offset < 0) || (subsubnode2_offset < 0))
 		FAIL("Can't find required nodes");
 
-	check_search_cell(fdt, "prop-int", TEST_VALUE_1, 0, subnode1_offset,
-			  subsubnode1_offset, -FDT_ERR_NOTFOUND);
+	check_search_cell(fdt, "prop-int", TEST_VALUE_1, root_offset,
+			  subnode1_offset, subsubnode1_offset, -FDT_ERR_NOTFOUND);
 
 	check_search_cell(fdt, "prop-int", TEST_VALUE_2, subnode2_offset,
 			  subsubnode2_offset, -FDT_ERR_NOTFOUND);
 
-	check_search_str(fdt, "prop-str", TEST_STRING_1, 0, -FDT_ERR_NOTFOUND);
+	check_search_str(fdt, "prop-str", TEST_STRING_1, root_offset,
+			  -FDT_ERR_NOTFOUND);
 
 	check_search_str(fdt, "prop-str", "no such string", -FDT_ERR_NOTFOUND);
 
 	check_search_cell(fdt, "prop-int", TEST_VALUE_1+1, -FDT_ERR_NOTFOUND);
 
-	check_search(fdt, "no-such-prop", NULL, 0, -FDT_ERR_NOTFOUND);
+	check_search(fdt, "no-such-prop", NULL, root_offset, -FDT_ERR_NOTFOUND);
 
 	PASS();
 }
tests/path_offset.c +9 -4
index ad8db833..d4f6553b 100644
@@ -84,11 +84,16 @@ int main(int argc, char *argv[])
 	void *fdt;
 	int subnode1_offset, subnode2_offset;
 	int subsubnode1_offset, subsubnode2_offset, subsubnode2_offset2;
+	int root_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
-	check_path_offset(fdt, "/", 0);
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		FAIL("fdt_root_offset()) failed: %s", fdt_strerror(root_offset));
+
+	check_path_offset(fdt, "/", root_offset);
 
 	subnode1_offset = check_subnode(fdt, 0, "subnode@1");
 	subnode2_offset = check_subnode(fdt, 0, "subnode@2");
@@ -106,8 +111,8 @@ int main(int argc, char *argv[])
 
 	/* Test paths with extraneous separators */
 	check_path_offset(fdt, "", -FDT_ERR_BADPATH);
-	check_path_offset(fdt, "//", 0);
-	check_path_offset(fdt, "///", 0);
+	check_path_offset(fdt, "//", root_offset);
+	check_path_offset(fdt, "///", root_offset);
 	check_path_offset(fdt, "//subnode@1", subnode1_offset);
 	check_path_offset(fdt, "/subnode@1/", subnode1_offset);
 	check_path_offset(fdt, "//subnode@1///", subnode1_offset);
@@ -116,7 +121,7 @@ int main(int argc, char *argv[])
 	/* Test fdt_path_offset_namelen() */
 	check_path_offset_namelen(fdt, "/subnode@1", -1, -FDT_ERR_BADPATH);
 	check_path_offset_namelen(fdt, "/subnode@1", 0, -FDT_ERR_BADPATH);
-	check_path_offset_namelen(fdt, "/subnode@1", 1, 0);
+	check_path_offset_namelen(fdt, "/subnode@1", 1, root_offset);
 	check_path_offset_namelen(fdt, "/subnode@1/subsubnode", 10, subnode1_offset);
 	check_path_offset_namelen(fdt, "/subnode@1/subsubnode", 11, subnode1_offset);
 	check_path_offset_namelen(fdt, "/subnode@2TRAILINGGARBAGE", 10, subnode2_offset);
tests/root_node.c +5 -1
index 37e6f059..30903f2b 100644
@@ -19,12 +19,16 @@ int main(int argc, char *argv[])
 {
 	void *fdt;
 	const struct fdt_node_header *nh;
+	int root_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
-	nh = fdt_offset_ptr(fdt, 0, sizeof(*nh));
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		FAIL("fdt_root_offset() returns %d", root_offset);
 
+	nh = fdt_offset_ptr(fdt, root_offset, sizeof(*nh));
 	if (! nh)
 		FAIL("NULL retrieving root node");
 
Signature · 1 line
2.55.0
#16 lore raw

Re: [PATCH v3 03/15] tests: Don't assume the root node is available at offset 0

Quoted 39 lines · Herve Codina

Several tests uses offset 0 as the offset of the root node. Either to check the offset returned by tested functions or to directly manipulate the root node retrieved using fdt_offset_ptr(fdt, 0, ...).

The root node is not always at offset 0. Indeed, a FDT_NOP tag can be present at offset 0. fdt_root_offset() returns the offset of the root node taking care of possible FDT_NOP tag.

Use fdt_root_offset() to get the offset of the root node and use this value whenever the offset of the root node is expected.

---
 tests/node_offset_by_compatible.c |  4 +++-
 tests/node_offset_by_prop_value.c | 11 +++++++----
 tests/path_offset.c               | 13 +++++++++----
 tests/root_node.c                 |  6 +++++-
 4 files changed, 24 insertions(+), 10 deletions(-)
tests/node_offset_by_compatible.c +2 -0
index a9e67835..1278a562 100644
@@ -39,12 +39,14 @@ static void check_search(void *fdt, const char *compat, ...)
 int main(int argc, char *argv[])
 {
 	void *fdt;
+	int root_offset;
 	int subnode1_offset, subnode2_offset;
 	int subsubnode1_offset, subsubnode2_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
+	root_offset = fdt_root_offset(fdt);
 	subnode1_offset = fdt_path_offset(fdt, "/subnode@1");
 	subnode2_offset = fdt_path_offset(fdt, "/subnode@2");
 	subsubnode1_offset = fdt_path_offset(fdt, "/subnode@1/subsubnode");

tests/node_offset_by_compatible.c int main(int argc, char *argv[]) · line 59

Quoted 5 lines
tests/node_offset_by_compatible.c +1 -1
@@ -54,7 +56,7 @@ int main(int argc, char *argv[])
 	    || (subsubnode1_offset < 0) || (subsubnode2_offset < 0))
 		FAIL("Can't find required nodes");
 
-	check_search(fdt, "test_tree1", 0, -FDT_ERR_NOTFOUND);
+	check_search(fdt, "test_tree1", root_offset, -FDT_ERR_NOTFOUND);

This does highlight that even with the compatibility changes introduced here, allowing NOPs before the root node can potentially break things. We now handle _passing_ 0 to any of the functions as a node offset, but anything that expects a _returned_ offset to be 0 if it's the root node will break.

I think that's probably an acceptable breakage, but it's something to be aware of.

Quoted 96 lines
tests/node_offset_by_compatible.c +0 -0
 	check_search(fdt, "subnode1", subnode1_offset, -FDT_ERR_NOTFOUND);
 	check_search(fdt, "subsubnode1", subsubnode1_offset, -FDT_ERR_NOTFOUND);
 	check_search(fdt, "subsubnode2", subsubnode2_offset, -FDT_ERR_NOTFOUND);
tests/node_offset_by_prop_value.c +7 -4
index 48ab1d93..329409b9 100644
@@ -64,12 +64,14 @@ static void check_search_str(void *fdt, const char *propname,
 int main(int argc, char *argv[])
 {
 	void *fdt;
+	int root_offset;
 	int subnode1_offset, subnode2_offset;
 	int subsubnode1_offset, subsubnode2_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
+	root_offset = fdt_root_offset(fdt);
 	subnode1_offset = fdt_path_offset(fdt, "/subnode@1");
 	subnode2_offset = fdt_path_offset(fdt, "/subnode@2");
 	subsubnode1_offset = fdt_path_offset(fdt, "/subnode@1/subsubnode");
@@ -79,19 +81,20 @@ int main(int argc, char *argv[])
 	    || (subsubnode1_offset < 0) || (subsubnode2_offset < 0))
 		FAIL("Can't find required nodes");
 
-	check_search_cell(fdt, "prop-int", TEST_VALUE_1, 0, subnode1_offset,
-			  subsubnode1_offset, -FDT_ERR_NOTFOUND);
+	check_search_cell(fdt, "prop-int", TEST_VALUE_1, root_offset,
+			  subnode1_offset, subsubnode1_offset, -FDT_ERR_NOTFOUND);
 
 	check_search_cell(fdt, "prop-int", TEST_VALUE_2, subnode2_offset,
 			  subsubnode2_offset, -FDT_ERR_NOTFOUND);
 
-	check_search_str(fdt, "prop-str", TEST_STRING_1, 0, -FDT_ERR_NOTFOUND);
+	check_search_str(fdt, "prop-str", TEST_STRING_1, root_offset,
+			  -FDT_ERR_NOTFOUND);
 
 	check_search_str(fdt, "prop-str", "no such string", -FDT_ERR_NOTFOUND);
 
 	check_search_cell(fdt, "prop-int", TEST_VALUE_1+1, -FDT_ERR_NOTFOUND);
 
-	check_search(fdt, "no-such-prop", NULL, 0, -FDT_ERR_NOTFOUND);
+	check_search(fdt, "no-such-prop", NULL, root_offset, -FDT_ERR_NOTFOUND);
 
 	PASS();
 }
tests/path_offset.c +9 -4
index ad8db833..d4f6553b 100644
@@ -84,11 +84,16 @@ int main(int argc, char *argv[])
 	void *fdt;
 	int subnode1_offset, subnode2_offset;
 	int subsubnode1_offset, subsubnode2_offset, subsubnode2_offset2;
+	int root_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
-	check_path_offset(fdt, "/", 0);
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		FAIL("fdt_root_offset()) failed: %s", fdt_strerror(root_offset));
+
+	check_path_offset(fdt, "/", root_offset);
 
 	subnode1_offset = check_subnode(fdt, 0, "subnode@1");
 	subnode2_offset = check_subnode(fdt, 0, "subnode@2");
@@ -106,8 +111,8 @@ int main(int argc, char *argv[])
 
 	/* Test paths with extraneous separators */
 	check_path_offset(fdt, "", -FDT_ERR_BADPATH);
-	check_path_offset(fdt, "//", 0);
-	check_path_offset(fdt, "///", 0);
+	check_path_offset(fdt, "//", root_offset);
+	check_path_offset(fdt, "///", root_offset);
 	check_path_offset(fdt, "//subnode@1", subnode1_offset);
 	check_path_offset(fdt, "/subnode@1/", subnode1_offset);
 	check_path_offset(fdt, "//subnode@1///", subnode1_offset);
@@ -116,7 +121,7 @@ int main(int argc, char *argv[])
 	/* Test fdt_path_offset_namelen() */
 	check_path_offset_namelen(fdt, "/subnode@1", -1, -FDT_ERR_BADPATH);
 	check_path_offset_namelen(fdt, "/subnode@1", 0, -FDT_ERR_BADPATH);
-	check_path_offset_namelen(fdt, "/subnode@1", 1, 0);
+	check_path_offset_namelen(fdt, "/subnode@1", 1, root_offset);
 	check_path_offset_namelen(fdt, "/subnode@1/subsubnode", 10, subnode1_offset);
 	check_path_offset_namelen(fdt, "/subnode@1/subsubnode", 11, subnode1_offset);
 	check_path_offset_namelen(fdt, "/subnode@2TRAILINGGARBAGE", 10, subnode2_offset);
tests/root_node.c +0 -0
index 37e6f059..30903f2b 100644
@@ -19,12 +19,16 @@ int main(int argc, char *argv[])
 {
 	void *fdt;

tests/root_node.c int main(int argc, char *argv[]) · line 29

Quoted 10 lines
tests/root_node.c +4 -1
 	const struct fdt_node_header *nh;
+	int root_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
-	nh = fdt_offset_ptr(fdt, 0, sizeof(*nh));
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		FAIL("fdt_root_offset() returns %d", root_offset);

Hm. It's been a long time, but I suspect the purpose of this testcase was to be super low-level, checking the contents of the root node _without_ relying on iteration or lookup functions first. Putting the lookup call here arguably defeats that purpose: certainly the test that nh->tag == FDT_BEGIN_NODE is no longer meaningful, since fdt_root_offset() will explicitly look for a location where that's true.

Or perhaps another way to look at it is that this test is explicitly verifying that the root node is at offset 0, so does it make snese for this test to even exist any more. I guess the test for the name of the root node is still meaningful, if minor.

Nonetheless, to maintain as best we can this test's goal as working independent of lookup functions, I think it might be worth open coding something to skip FDT_NOP tags (not using fdt_next_tag(), even), then construct nh immediately after that.

Quoted 9 lines
tests/root_node.c +1 -0
+	nh = fdt_offset_ptr(fdt, root_offset, sizeof(*nh));
 	if (! nh)
 		FAIL("NULL retrieving root node");
 
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#17 lore raw

Re: [PATCH v3 03/15] tests: Don't assume the root node is available at offset 0

Hi David,

Quoted 52 lines · On Tue, 1 Sep 2026 18:03:09 +1000 David Gibson <[email protected]>…
Quoted 39 lines · Herve Codina

Several tests uses offset 0 as the offset of the root node. Either to check the offset returned by tested functions or to directly manipulate the root node retrieved using fdt_offset_ptr(fdt, 0, ...).

The root node is not always at offset 0. Indeed, a FDT_NOP tag can be present at offset 0. fdt_root_offset() returns the offset of the root node taking care of possible FDT_NOP tag.

Use fdt_root_offset() to get the offset of the root node and use this value whenever the offset of the root node is expected.

---
 tests/node_offset_by_compatible.c |  4 +++-
 tests/node_offset_by_prop_value.c | 11 +++++++----
 tests/path_offset.c               | 13 +++++++++----
 tests/root_node.c                 |  6 +++++-
 4 files changed, 24 insertions(+), 10 deletions(-)
tests/node_offset_by_compatible.c +2 -0
index a9e67835..1278a562 100644
@@ -39,12 +39,14 @@ static void check_search(void *fdt, const char *compat, ...)
 int main(int argc, char *argv[])
 {
 	void *fdt;
+	int root_offset;
 	int subnode1_offset, subnode2_offset;
 	int subsubnode1_offset, subsubnode2_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
+	root_offset = fdt_root_offset(fdt);
 	subnode1_offset = fdt_path_offset(fdt, "/subnode@1");
 	subnode2_offset = fdt_path_offset(fdt, "/subnode@2");
 	subsubnode1_offset = fdt_path_offset(fdt, "/subnode@1/subsubnode");

tests/node_offset_by_compatible.c int main(int argc, char *argv[]) · line 59

Quoted 5 lines
tests/node_offset_by_compatible.c +1 -1
@@ -54,7 +56,7 @@ int main(int argc, char *argv[])
 	    || (subsubnode1_offset < 0) || (subsubnode2_offset < 0))
 		FAIL("Can't find required nodes");
 
-	check_search(fdt, "test_tree1", 0, -FDT_ERR_NOTFOUND);
+	check_search(fdt, "test_tree1", root_offset, -FDT_ERR_NOTFOUND);  

This does highlight that even with the compatibility changes introduced here, allowing NOPs before the root node can potentially break things. We now handle _passing_ 0 to any of the functions as a node offset, but anything that expects a _returned_ offset to be 0 if it's the root node will break.

Quoted 2 lines

I think that's probably an acceptable breakage, but it's something to be aware of.

Yes, I know but I wouldn't say it is a breakage. NOPs are allowed by the specification. In current version dtc/libfdt, having a NOP before the root node is already broken.

I agree with you we need to be aware of.

...

Quoted 31 lines
Quoted 7 lines
tests/root_node.c +0 -0
index 37e6f059..30903f2b 100644
@@ -19,12 +19,16 @@ int main(int argc, char *argv[])
 {
 	void *fdt;

tests/root_node.c int main(int argc, char *argv[]) · line 29

Quoted 10 lines
tests/root_node.c +4 -1
 	const struct fdt_node_header *nh;
+	int root_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
-	nh = fdt_offset_ptr(fdt, 0, sizeof(*nh));
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		FAIL("fdt_root_offset() returns %d", root_offset);  

Hm. It's been a long time, but I suspect the purpose of this testcase was to be super low-level, checking the contents of the root node _without_ relying on iteration or lookup functions first. Putting the lookup call here arguably defeats that purpose: certainly the test that nh->tag == FDT_BEGIN_NODE is no longer meaningful, since fdt_root_offset() will explicitly look for a location where that's true.

Or perhaps another way to look at it is that this test is explicitly verifying that the root node is at offset 0, so does it make snese for this test to even exist any more. I guess the test for the name of the root node is still meaningful, if minor.

Quoted 4 lines

Nonetheless, to maintain as best we can this test's goal as working independent of lookup functions, I think it might be worth open coding something to skip FDT_NOP tags (not using fdt_next_tag(), even), then construct nh immediately after that.

Well "structured tags" are going to be introduced and so the open coding here will need to take care of that. Later some new tags could be introduced and could also have impacts on the test.

To be honest, I hesitated to just remove this root_node test.

I kept it because at least it checks that the offset returned by fdt_root_offset() looks like a root node (i.e tag BEGIN_NODE and empty name).

Adding an open coded loop here without fdt_next_tag() call will looks like a copy/paste of the loop available in fdtdump.c. I am not sure that this is what we want to see here.

The question is: How to be sure that the offset returned by fdt_root_offset() is really the root node offset without having an open code loop here?

Maybe we can add a new test, root_offset, and build dtbs where we exactly know where the root is (2 dtbs, with and without FDT_NOP). treegen could build those dtbs.
---- 8< ----

/ {
    offset = <real_root_node_offset>;
};

---- 8< ----

The treegen tool should be able to add a property where the value is the offset of the root node.

The new test could get the root node offset thanks to fdt_root_offset(), read the 'offset' property available at this root node offset and check that the property value matches the root node offset returned by fdt_root_offset().

The root_node is kept as it is with this current patch applied:
- use fdt_root_offset()
- Check BEGIN_NODE
- Check empty name

What do you think about this solution ?

Should the 'root_offset' test need to be implemented or does it look over-engineered ?

Best regards,
Hervé

Quoted 13 lines
Quoted 12 lines
tests/root_node.c +1 -0
+	nh = fdt_offset_ptr(fdt, root_offset, sizeof(*nh));
 	if (! nh)
 		FAIL("NULL retrieving root node");
 
 
Signature · 1 line
2.55.0
Signature · 3 lines
Hervé Codina, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#18 lore raw

Re: [PATCH v3 03/15] tests: Don't assume the root node is available at offset 0

Quoted 57 lines · Herve Codina

Hi David,

Quoted 52 lines · On Tue, 1 Sep 2026 18:03:09 +1000 David Gibson <[email protected]>…
Quoted 39 lines · Herve Codina

Several tests uses offset 0 as the offset of the root node. Either to check the offset returned by tested functions or to directly manipulate the root node retrieved using fdt_offset_ptr(fdt, 0, ...).

The root node is not always at offset 0. Indeed, a FDT_NOP tag can be present at offset 0. fdt_root_offset() returns the offset of the root node taking care of possible FDT_NOP tag.

Use fdt_root_offset() to get the offset of the root node and use this value whenever the offset of the root node is expected.

---
 tests/node_offset_by_compatible.c |  4 +++-
 tests/node_offset_by_prop_value.c | 11 +++++++----
 tests/path_offset.c               | 13 +++++++++----
 tests/root_node.c                 |  6 +++++-
 4 files changed, 24 insertions(+), 10 deletions(-)
tests/node_offset_by_compatible.c +2 -0
index a9e67835..1278a562 100644
@@ -39,12 +39,14 @@ static void check_search(void *fdt, const char *compat, ...)
 int main(int argc, char *argv[])
 {
 	void *fdt;
+	int root_offset;
 	int subnode1_offset, subnode2_offset;
 	int subsubnode1_offset, subsubnode2_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
+	root_offset = fdt_root_offset(fdt);
 	subnode1_offset = fdt_path_offset(fdt, "/subnode@1");
 	subnode2_offset = fdt_path_offset(fdt, "/subnode@2");
 	subsubnode1_offset = fdt_path_offset(fdt, "/subnode@1/subsubnode");

tests/node_offset_by_compatible.c int main(int argc, char *argv[]) · line 59

Quoted 5 lines
tests/node_offset_by_compatible.c +1 -1
@@ -54,7 +56,7 @@ int main(int argc, char *argv[])
 	    || (subsubnode1_offset < 0) || (subsubnode2_offset < 0))
 		FAIL("Can't find required nodes");
 
-	check_search(fdt, "test_tree1", 0, -FDT_ERR_NOTFOUND);
+	check_search(fdt, "test_tree1", root_offset, -FDT_ERR_NOTFOUND);  

This does highlight that even with the compatibility changes introduced here, allowing NOPs before the root node can potentially break things. We now handle _passing_ 0 to any of the functions as a node offset, but anything that expects a _returned_ offset to be 0 if it's the root node will break.

Quoted 6 lines
Quoted 2 lines

I think that's probably an acceptable breakage, but it's something to be aware of.

Yes, I know but I wouldn't say it is a breakage. NOPs are allowed by the specification. In current version dtc/libfdt, having a NOP before the root node is already broken.

Yes, but (usually) not breaking existing users of real software is more important than not breaking compliance with an abstract spec. Especially when the spec was written from the software, not the other way around.

Quoted 35 lines

I agree with you we need to be aware of.

...

Quoted 31 lines
Quoted 7 lines
tests/root_node.c +0 -0
index 37e6f059..30903f2b 100644
@@ -19,12 +19,16 @@ int main(int argc, char *argv[])
 {
 	void *fdt;

tests/root_node.c int main(int argc, char *argv[]) · line 29

Quoted 10 lines
tests/root_node.c +4 -1
 	const struct fdt_node_header *nh;
+	int root_offset;
 
 	test_init(argc, argv);
 	fdt = load_blob_arg(argc, argv);
 
-	nh = fdt_offset_ptr(fdt, 0, sizeof(*nh));
+	root_offset = fdt_root_offset(fdt);
+	if (root_offset < 0)
+		FAIL("fdt_root_offset() returns %d", root_offset);  

Hm. It's been a long time, but I suspect the purpose of this testcase was to be super low-level, checking the contents of the root node _without_ relying on iteration or lookup functions first. Putting the lookup call here arguably defeats that purpose: certainly the test that nh->tag == FDT_BEGIN_NODE is no longer meaningful, since fdt_root_offset() will explicitly look for a location where that's true.

Or perhaps another way to look at it is that this test is explicitly verifying that the root node is at offset 0, so does it make snese for this test to even exist any more. I guess the test for the name of the root node is still meaningful, if minor.

Quoted 8 lines
Quoted 4 lines

Nonetheless, to maintain as best we can this test's goal as working independent of lookup functions, I think it might be worth open coding something to skip FDT_NOP tags (not using fdt_next_tag(), even), then construct nh immediately after that.

Well "structured tags" are going to be introduced and so the open coding here will need to take care of that. Later some new tags could be introduced and could also have impacts on the test.

If structured tags are allowed before the root node. There might be a case for that (and maybe you've already made it in the addon series), but so far it's not obvious to me that's useful.

Quoted 4 lines

To be honest, I hesitated to just remove this root_node test.

I kept it because at least it checks that the offset returned by fdt_root_offset() looks like a root node (i.e tag BEGIN_NODE and empty name).

empty name checks something, but the BEGIN_NODE test is meaningless if we're found our offset by searching for a BEGIN_NODE tag.

Quoted 3 lines

Adding an open coded loop here without fdt_next_tag() call will looks like a copy/paste of the loop available in fdtdump.c. I am not sure that this is what we want to see here.

Usually I'd agree (DRY principle). But as I say, the purpose of this test is a special case - it's trying to test things piece by piece with a minimum of circular dependencies. That tends to make it clearer what's gone wrong when somethin gbreaks.

Quoted 23 lines

The question is: How to be sure that the offset returned by fdt_root_offset() is really the root node offset without having an open code loop here?

Maybe we can add a new test, root_offset, and build dtbs where we exactly know where the root is (2 dtbs, with and without FDT_NOP). treegen could build those dtbs.
---- 8< ----

/ {
    offset = <real_root_node_offset>;
};

---- 8< ----

The treegen tool should be able to add a property where the value is the offset of the root node.

The new test could get the root node offset thanks to fdt_root_offset(), read the 'offset' property available at this root node offset and check that the property value matches the root node offset returned by fdt_root_offset(). The root_node is kept as it is with this current patch applied:
- use fdt_root_offset()
- Check BEGIN_NODE
- Check empty name

Quoted 1 line

What do you think about this solution ?

One test that's safe on any tree just checking the empty name, another that's checking the low-level construction with a known offset. That's a good idea.

Encoding that know offset in a property is overcomplicating things though, and it makes this very low-level test rely on parsing a property, which we want to do even less that searching for the root offset. But that's ok - we're only calling it on specifically constructed trees, so we can pass in the expected offset as an another parameter.

Quoted 2 lines

Should the 'root_offset' test need to be implemented or does it look over-engineered ?

No, it's good. I'm less concerned about over-engineering in the tests since, in a way, they test themselves.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#19 lore raw

PATCH v3 4/15 tests/nopulate: Add a FDT_NOP before the root node

In reply to Herve Codina

A FDT_NOP tag can be present at the offset 0 and so before the root node. This is a legit case.

The nopulate tool adds FDT_NOP tag after each tag encountered but it doesn't add a FDT_NOP tag at offset 0.

Improve nopulate to fix this lack and add a FDT_NOP tag at offset 0.

---
 tests/nopulate.c | 3 +++
 1 file changed, 3 insertions(+)
tests/nopulate.c +3 -0
index 06f8369a..050e69fb 100644
@@ -22,7 +22,10 @@ static int nopulate_struct(char *buf, const char *fdt)
 	uint32_t tag;
 	char *p;
 
+	/* Add a FDT_NOP before the root node (first node) */
 	p = buf;
+	*((fdt32_t *)p) = cpu_to_fdt32(FDT_NOP);
+	p += FDT_TAGSIZE;
 
 	do {
 		offset = nextoffset;
Signature · 1 line
2.55.0
Reviewed-by on v3 4/15
#20 lore raw

Re: [PATCH v3 04/15] tests/nopulate: Add a FDT_NOP before the root node

Quoted 9 lines · Herve Codina

A FDT_NOP tag can be present at the offset 0 and so before the root node. This is a legit case.

The nopulate tool adds FDT_NOP tag after each tag encountered but it doesn't add a FDT_NOP tag at offset 0.

Improve nopulate to fix this lack and add a FDT_NOP tag at offset 0.

Quoted 23 lines
---
 tests/nopulate.c | 3 +++
 1 file changed, 3 insertions(+)
tests/nopulate.c +3 -0
index 06f8369a..050e69fb 100644
@@ -22,7 +22,10 @@ static int nopulate_struct(char *buf, const char *fdt)
 	uint32_t tag;
 	char *p;
 
+	/* Add a FDT_NOP before the root node (first node) */
 	p = buf;
+	*((fdt32_t *)p) = cpu_to_fdt32(FDT_NOP);
+	p += FDT_TAGSIZE;
 
 	do {
 		offset = nextoffset;
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#21 lore raw

PATCH v3 5/15 tests: treegen: Introduce emit_fdt_header_vers()

In reply to Herve Codina

treegen is used to generate custom dtbs. It uses emit_fdt_header() to generate the header part.

The current definition of this function doesn't allow to set custom settings related to version fields.

In order to easily generate some dtb with custom version values, introduce emit_fdt_header_vers().

The modification doesn't introduce any functional changes.

---
 tests/treegen.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
tests/treegen.c +9 -3
index 6891bfd6..28943d43 100644
@@ -105,7 +105,8 @@ static void fill_prop_name(struct buf *b, size_t strs, size_t prop, size_t strof
 
 /* FDT structure helpers */
 
-static size_t emit_fdt_header(struct buf *b)
+static size_t emit_fdt_header_vers(struct buf *b, uint32_t version,
+				   uint32_t last_comp_version)
 {
 	size_t off = emit_u32(b, FDT_MAGIC);
 
@@ -113,14 +114,19 @@ static size_t emit_fdt_header(struct buf *b)
 	emit_u32(b, 0);	/* off_dt_struct */
 	emit_u32(b, 0);	/* off_dt_strings */
 	emit_u32(b, 0);	/* off_mem_rsvmap */
-	emit_u32(b, 0x11);	/* version */
-	emit_u32(b, 0x10);	/* last_comp_version */
+	emit_u32(b, version);	/* version */
+	emit_u32(b, last_comp_version);	/* last_comp_version */
 	emit_u32(b, 0);	/* boot_cpuid_phys */
 	emit_u32(b, 0);	/* size_dt_strings */
 	emit_u32(b, 0);	/* size_dt_struct */
 	return off;
 }
 
+static size_t emit_fdt_header(struct buf *b)
+{
+	return emit_fdt_header_vers(b, 0x11, 0x10);
+}
+
 static void finish_rsvmap(struct buf *b, size_t hdr, size_t rsvmap)
 {
 	struct fdt_header *fh = (struct fdt_header *)(b->data + hdr);
Signature · 1 line
2.55.0
Reviewed-by on v3 5/15
#22 lore raw

Re: [PATCH v3 05/15] tests: treegen: Introduce emit_fdt_header_vers()

On Wed, Aug 26, 2026 at 10:31:36AM +0200, Herve Codina wrote:
11;rgb:1c1c/1c1c/1f1f> treegen is used to generate custom dtbs. It uses emit_fdt_header()

Quoted 11 lines

to generate the header part.

The current definition of this function doesn't allow to set custom settings related to version fields.

In order to easily generate some dtb with custom version values, introduce emit_fdt_header_vers().

The modification doesn't introduce any functional changes.

Quoted 44 lines
---
 tests/treegen.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
tests/treegen.c +9 -3
index 6891bfd6..28943d43 100644
@@ -105,7 +105,8 @@ static void fill_prop_name(struct buf *b, size_t strs, size_t prop, size_t strof
 
 /* FDT structure helpers */
 
-static size_t emit_fdt_header(struct buf *b)
+static size_t emit_fdt_header_vers(struct buf *b, uint32_t version,
+				   uint32_t last_comp_version)
 {
 	size_t off = emit_u32(b, FDT_MAGIC);
 
@@ -113,14 +114,19 @@ static size_t emit_fdt_header(struct buf *b)
 	emit_u32(b, 0);	/* off_dt_struct */
 	emit_u32(b, 0);	/* off_dt_strings */
 	emit_u32(b, 0);	/* off_mem_rsvmap */
-	emit_u32(b, 0x11);	/* version */
-	emit_u32(b, 0x10);	/* last_comp_version */
+	emit_u32(b, version);	/* version */
+	emit_u32(b, last_comp_version);	/* last_comp_version */
 	emit_u32(b, 0);	/* boot_cpuid_phys */
 	emit_u32(b, 0);	/* size_dt_strings */
 	emit_u32(b, 0);	/* size_dt_struct */
 	return off;
 }
 
+static size_t emit_fdt_header(struct buf *b)
+{
+	return emit_fdt_header_vers(b, 0x11, 0x10);
+}
+
 static void finish_rsvmap(struct buf *b, size_t hdr, size_t rsvmap)
 {
 	struct fdt_header *fh = (struct fdt_header *)(b->data + hdr);
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#23 lore raw

PATCH v3 6/15 Introduce structured tag value definition

In reply to Herve Codina

The goal of structured tag values is to ease the introduction of new tags in future releases with the capability for an already existing release to ignore those structured tags. In order to do that data length related to the unknown tag needs to be identified.

Also add a flag to tell an old release if this tag can be simply skipped or must lead to an error.

Structured tag value is defined on 32bit and is defined as follow:

Bits | 31 | 30 | 29 28 | 27 0|
------+----+-----------+-------------------+--------+
Fields| 1 | SKIP_SAFE | DATA_LEN_ENCODING | TAG_ID |
------+----+-----------+-------------------+--------+

Bit 31 is always set to 1 to identify a structured tag value.

Bit 30 (SKIP_SAFE) is set to 1 if the tag can be safely ignored when its TAG_ID value is not a known value (unknown tag). If the SKIP_SAFE bit is set to 0 this tag must not be ignored and an error should be reported when its TAG_ID value is not a known value (unknown tag).

Bits 29..28 (DATA_LEN_ENCODING) indicates the length of the data related to the tag. Following values are possible:
- 0b00: No data.
The tag is followed by the next tag value.

- 0b01: 1 cell data
The tag is followed by a 1 cell (u32) data. The next tag is available after this cell.

- 0b10: 2 cells data
The tag is followed by a 2 cells (2 * u32) data. The next tag is available after those two cells.

- 0b11: Data length encoding
The tag is followed by a cell (u32) indicating the size of the data. This size is given in bytes. Data are available right after this cell.

The next tag is available after the data. Padding is present after the data in order to have the next tag aligned on 32bits. This padding is not included in the size of the data.

Bits 27..0 (TAG_ID) is the tag identifier defining a specific tag.

Introduce the structured tag values definition and some specific tags reserved for tests based on this structure definition.

---
 libfdt/fdt.h | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
libfdt/fdt.h +23 -0
index a07abfcc..f41a355f 100644
@@ -49,6 +49,7 @@ struct fdt_property {
 
 #define FDT_MAGIC	0xd00dfeed	/* 4: version, 4: total size */
 #define FDT_TAGSIZE	sizeof(fdt32_t)
+#define FDT_CELLSIZE	sizeof(fdt32_t)
 
 #define FDT_BEGIN_NODE	0x1		/* Start node: full name */
 #define FDT_END_NODE	0x2		/* End node */
@@ -57,6 +58,28 @@ struct fdt_property {
 #define FDT_NOP		0x4		/* nop */
 #define FDT_END		0x9
 
+/* Tag values flags */
+#define FDT_TAG_STRUCTURED	(1U<<31)
+#define FDT_TAG_SKIP_SAFE	(1U<<30)
+#define FDT_TAG_DATA_MASK	(3U<<28)
+#define FDT_TAG_DATA_NONE	(0U<<28)
+#define FDT_TAG_DATA_1CELL	(1U<<28)
+#define FDT_TAG_DATA_2CELLS	(2U<<28)
+#define FDT_TAG_DATA_VARLEN	(3U<<28)
+
+#define FDT_TAG_NO_SKIP(tag_data, tag_id) \
+		(FDT_TAG_STRUCTURED | tag_data | tag_id)
+
+#define FDT_TAG_CAN_SKIP(tag_data, tag_id) \
+		(FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE | tag_data | tag_id)
+
+/* Tests reserved tags */
+#define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
+#define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
+#define FDT_TEST_2CELLS_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_2CELLS, 0)
+#define FDT_TEST_VARLEN_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_VARLEN, 0)
+#define FDT_TEST_NONE_NO_SKIP		FDT_TAG_NO_SKIP(FDT_TAG_DATA_NONE, 0)
+
 #define FDT_V1_SIZE	(7*sizeof(fdt32_t))
 #define FDT_V2_SIZE	(FDT_V1_SIZE + sizeof(fdt32_t))
 #define FDT_V3_SIZE	(FDT_V2_SIZE + sizeof(fdt32_t))
Signature · 1 line
2.55.0
#24 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 7 lines · Herve Codina

The goal of structured tag values is to ease the introduction of new tags in future releases with the capability for an already existing release to ignore those structured tags. In order to do that data length related to the unknown tag needs to be identified.

Also add a flag to tell an old release if this tag can be simply skipped or must lead to an error.

I suggested/insisted on this in the past, but I've since realised this isn't actually useful. The "structured tag" format is only useful because it allows you to skip over unknown tags, which means there's no point using it for ags that can't be skipped. If we need new tags that can't be safely skipped, they can be added as old-style tags instead.

In which case "old style" versus "new style" is no longer a good
characterization: they would exist side by side, so the distinction is more "skippable" versus "non skippable" tags. Which suggests that "skippable tags" or "metadata tags" might be a better term than "structured tags" - that would focus more on the why than the how.

Quoted 14 lines

Structured tag value is defined on 32bit and is defined as follow:

Bits | 31 | 30 | 29 28 | 27 0|
------+----+-----------+-------------------+--------+
Fields| 1 | SKIP_SAFE | DATA_LEN_ENCODING | TAG_ID |
------+----+-----------+-------------------+--------+

Bit 31 is always set to 1 to identify a structured tag value.

Bit 30 (SKIP_SAFE) is set to 1 if the tag can be safely ignored when its TAG_ID value is not a known value (unknown tag). If the SKIP_SAFE bit is set to 0 this tag must not be ignored and an error should be reported when its TAG_ID value is not a known value (unknown tag).

Quoted 4 lines

Bits 29..28 (DATA_LEN_ENCODING) indicates the length of the data related to the tag. Following values are possible:
- 0b00: No data.
The tag is followed by the next tag value.

I think "next tag." would be clearer than "next tag value." - "next tag value" could be confused as meaning the data that comes after the tag.

Quoted 3 lines

- 0b01: 1 cell data
The tag is followed by a 1 cell (u32) data. The next tag is available after this cell.

Remove "available", it doesn't add any information.

Quoted 3 lines

- 0b10: 2 cells data
The tag is followed by a 2 cells (2 * u32) data. The next tag is available after those two cells.

Ditto.

Quoted 8 lines

- 0b11: Data length encoding
The tag is followed by a cell (u32) indicating the size of the data. This size is given in bytes. Data are available right after this cell.

The next tag is available after the data. Padding is present after the data in order to have the next tag aligned on 32bits. This padding is not included in the size of the data.

I'm guessing the 1 & 2 cell cases are pretty common so it saves a moderate amount of dtb size to have this encoding. However, it does come at the cost of greater code complexity. Is it worth it? I'm willing to believe it is, but I think the case needs to be made.

I'd also avoid the term "cell" here. To me a "cell" is specifically a term applying to a 32-bit value _within a device tree property_. These are 32-bits, but not part of a property. Plus if Segher reappears, he'll complain that in the old days of OF, a cell wasn't necessarily 32-bits :).

Quoted 16 lines

Bits 27..0 (TAG_ID) is the tag identifier defining a specific tag.

Introduce the structured tag values definition and some specific tags reserved for tests based on this structure definition.

---
 libfdt/fdt.h | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
libfdt/fdt.h +0 -0
index a07abfcc..f41a355f 100644

libfdt/fdt.h struct fdt_property { · line 52

Quoted 4 lines
libfdt/fdt.h +1 -0
@@ -49,6 +49,7 @@ struct fdt_property {
 
 #define FDT_MAGIC	0xd00dfeed	/* 4: version, 4: total size */
 #define FDT_TAGSIZE	sizeof(fdt32_t)
+#define FDT_CELLSIZE	sizeof(fdt32_t)

I'd avoid creating this constant for similar reasons to avoid the term "cell" above.

Quoted 35 lines
libfdt/fdt.h +22 -0
 #define FDT_BEGIN_NODE	0x1		/* Start node: full name */
 #define FDT_END_NODE	0x2		/* End node */
@@ -57,6 +58,28 @@ struct fdt_property {
 #define FDT_NOP		0x4		/* nop */
 #define FDT_END		0x9
 
+/* Tag values flags */
+#define FDT_TAG_STRUCTURED	(1U<<31)
+#define FDT_TAG_SKIP_SAFE	(1U<<30)
+#define FDT_TAG_DATA_MASK	(3U<<28)
+#define FDT_TAG_DATA_NONE	(0U<<28)
+#define FDT_TAG_DATA_1CELL	(1U<<28)
+#define FDT_TAG_DATA_2CELLS	(2U<<28)
+#define FDT_TAG_DATA_VARLEN	(3U<<28)
+
+#define FDT_TAG_NO_SKIP(tag_data, tag_id) \
+		(FDT_TAG_STRUCTURED | tag_data | tag_id)
+
+#define FDT_TAG_CAN_SKIP(tag_data, tag_id) \
+		(FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE | tag_data | tag_id)
+
+/* Tests reserved tags */
+#define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
+#define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
+#define FDT_TEST_2CELLS_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_2CELLS, 0)
+#define FDT_TEST_VARLEN_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_VARLEN, 0)
+#define FDT_TEST_NONE_NO_SKIP		FDT_TAG_NO_SKIP(FDT_TAG_DATA_NONE, 0)
+
 #define FDT_V1_SIZE	(7*sizeof(fdt32_t))
 #define FDT_V2_SIZE	(FDT_V1_SIZE + sizeof(fdt32_t))
 #define FDT_V3_SIZE	(FDT_V2_SIZE + sizeof(fdt32_t))
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#25 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Hi David,

Quoted 16 lines · On Thu, 10 Sep 2026 14:51:08 +1000 David Gibson <[email protected]>…
Quoted 7 lines · Herve Codina

The goal of structured tag values is to ease the introduction of new tags in future releases with the capability for an already existing release to ignore those structured tags. In order to do that data length related to the unknown tag needs to be identified.

Also add a flag to tell an old release if this tag can be simply skipped or must lead to an error.

I suggested/insisted on this in the past, but I've since realised this isn't actually useful. The "structured tag" format is only useful because it allows you to skip over unknown tags, which means there's no point using it for ags that can't be skipped. If we need new tags that can't be safely skipped, they can be added as old-style tags instead.

Quoted 5 lines

In which case "old style" versus "new style" is no longer a good
characterization: they would exist side by side, so the distinction is more "skippable" versus "non skippable" tags. Which suggests that "skippable tags" or "metadata tags" might be a better term than "structured tags" - that would focus more on the why than the how.

Do you mean that the SKIP_SAFE bit should be removed ?

I like the defined structure with the DATA_LEN_ENCODING part. Even for tags which are not "skippable".

This ensures a kind of standardized format for all future tags instead of a specific definition (related to the length of the data) for each new tag.

For this kind of information related to the length of data, I prefer a global rule instead of tag-specific rules.

Quoted 16 lines
Quoted 16 lines

Structured tag value is defined on 32bit and is defined as follow:

Bits | 31 | 30 | 29 28 | 27 0|
------+----+-----------+-------------------+--------+
Fields| 1 | SKIP_SAFE | DATA_LEN_ENCODING | TAG_ID |
------+----+-----------+-------------------+--------+

Bit 31 is always set to 1 to identify a structured tag value.

Bit 30 (SKIP_SAFE) is set to 1 if the tag can be safely ignored when its TAG_ID value is not a known value (unknown tag). If the SKIP_SAFE bit is set to 0 this tag must not be ignored and an error should be reported when its TAG_ID value is not a known value (unknown tag).

Quoted 8 lines
Quoted 4 lines

Bits 29..28 (DATA_LEN_ENCODING) indicates the length of the data related to the tag. Following values are possible:
- 0b00: No data.
The tag is followed by the next tag value.

I think "next tag." would be clearer than "next tag value." - "next tag value" could be confused as meaning the data that comes after the tag.

Ok, will be updated.

Quoted 6 lines
Quoted 4 lines

- 0b01: 1 cell data
The tag is followed by a 1 cell (u32) data. The next tag is available after this cell.

Remove "available", it doesn't add any information.

Ok, will be updated.

Quoted 6 lines
Quoted 4 lines

- 0b10: 2 cells data
The tag is followed by a 2 cells (2 * u32) data. The next tag is available after those two cells.

Ditto.

Will be update as well.

Quoted 6 lines
Quoted 6 lines

- 0b11: Data length encoding
The tag is followed by a cell (u32) indicating the size of the data. This size is given in bytes. Data are available right after this cell.

Quoted 8 lines
Quoted 3 lines

The next tag is available after the data. Padding is present after the data in order to have the next tag aligned on 32bits. This padding is not included in the size of the data.

I'm guessing the 1 & 2 cell cases are pretty common so it saves a moderate amount of dtb size to have this encoding. However, it does come at the cost of greater code complexity. Is it worth it? I'm willing to believe it is, but I think the case needs to be made.

In term of code complexity, FDT_PROPDATA_PHANDLE introduced in the addons series, patch 7/74 [0], is a 1-cell (or 1-fdt32) "structured" tag.

It can be compared with FDT_PROPDATA_PHANDLE_REF, introduced in patch 11/74 [1]. FDT_PROPDATA_PHANDLE_REF is a "Data length encoding" tag.

Modifications in libfdt/fdt.c are pretty similar for both tags.

[0] https://lore.kernel.org/all/[email protected]/
[1] https://lore.kernel.org/all/[email protected]/

Quoted 6 lines

I'd also avoid the term "cell" here. To me a "cell" is specifically a term applying to a 32-bit value _within a device tree property_. These are 32-bits, but not part of a property. Plus if Segher reappears, he'll complain that in the old days of OF, a cell wasn't necessarily 32-bits :).

ok, I will avoid the term "cell" in the next iteration.

Quoted 18 lines
Quoted 18 lines

Bits 27..0 (TAG_ID) is the tag identifier defining a specific tag.

Introduce the structured tag values definition and some specific tags reserved for tests based on this structure definition.

---
 libfdt/fdt.h | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
libfdt/fdt.h +0 -0
index a07abfcc..f41a355f 100644
@@ -49,6 +49,7 @@ struct fdt_property {
 
Quoted 6 lines

libfdt/fdt.h struct fdt_property { · line 52

Quoted 3 lines
libfdt/fdt.h +1 -0
 #define FDT_MAGIC	0xd00dfeed	/* 4: version, 4: total size */
 #define FDT_TAGSIZE	sizeof(fdt32_t)
+#define FDT_CELLSIZE	sizeof(fdt32_t)  

I'd avoid creating this constant for similar reasons to avoid the term "cell" above.

Ok, I will avoid the constant and use sizeof(fdt32_t) directly when needed in the code.

Also, I will avoid the CELL in all other part of this file.

Best regards,
Hervé

#26 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 21 lines · Herve Codina

Hi David,

Quoted 16 lines · On Thu, 10 Sep 2026 14:51:08 +1000 David Gibson <[email protected]>…
Quoted 7 lines · Herve Codina

The goal of structured tag values is to ease the introduction of new tags in future releases with the capability for an already existing release to ignore those structured tags. In order to do that data length related to the unknown tag needs to be identified.

Also add a flag to tell an old release if this tag can be simply skipped or must lead to an error.

I suggested/insisted on this in the past, but I've since realised this isn't actually useful. The "structured tag" format is only useful because it allows you to skip over unknown tags, which means there's no point using it for ags that can't be skipped. If we need new tags that can't be safely skipped, they can be added as old-style tags instead.

Quoted 7 lines
Quoted 5 lines

In which case "old style" versus "new style" is no longer a good
characterization: they would exist side by side, so the distinction is more "skippable" versus "non skippable" tags. Which suggests that "skippable tags" or "metadata tags" might be a better term than "structured tags" - that would focus more on the why than the how.

Do you mean that the SKIP_SAFE bit should be removed ?

Yes.

Quoted 5 lines

I like the defined structure with the DATA_LEN_ENCODING part. Even for tags which are not "skippable".

This ensures a kind of standardized format for all future tags instead of a specific definition (related to the length of the data) for each new tag.

If we were designing the dtb format from scratch, I'd agree. But given we already have what we have I think the drawbacks of introducing a second way of doing tags outweighs the benefits.

Quoted 2 lines

For this kind of information related to the length of data, I prefer a global rule instead of tag-specific rules.

Right, but it can't truly be global, because we have the existing tags.

Quoted 58 lines
Quoted 14 lines
Quoted 14 lines

Structured tag value is defined on 32bit and is defined as follow:

Bits | 31 | 30 | 29 28 | 27 0|
------+----+-----------+-------------------+--------+
Fields| 1 | SKIP_SAFE | DATA_LEN_ENCODING | TAG_ID |
------+----+-----------+-------------------+--------+

Bit 31 is always set to 1 to identify a structured tag value.

Bit 30 (SKIP_SAFE) is set to 1 if the tag can be safely ignored when its TAG_ID value is not a known value (unknown tag). If the SKIP_SAFE bit is set to 0 this tag must not be ignored and an error should be reported when its TAG_ID value is not a known value (unknown tag).

Quoted 8 lines
Quoted 4 lines

Bits 29..28 (DATA_LEN_ENCODING) indicates the length of the data related to the tag. Following values are possible:
- 0b00: No data.
The tag is followed by the next tag value.

I think "next tag." would be clearer than "next tag value." - "next tag value" could be confused as meaning the data that comes after the tag.

Ok, will be updated.

Quoted 6 lines
Quoted 4 lines

- 0b01: 1 cell data
The tag is followed by a 1 cell (u32) data. The next tag is available after this cell.

Remove "available", it doesn't add any information.

Ok, will be updated.

Quoted 6 lines
Quoted 4 lines

- 0b10: 2 cells data
The tag is followed by a 2 cells (2 * u32) data. The next tag is available after those two cells.

Ditto.

Will be update as well.

Quoted 6 lines
Quoted 6 lines

- 0b11: Data length encoding
The tag is followed by a cell (u32) indicating the size of the data. This size is given in bytes. Data are available right after this cell.

Quoted 8 lines
Quoted 3 lines

The next tag is available after the data. Padding is present after the data in order to have the next tag aligned on 32bits. This padding is not included in the size of the data.

I'm guessing the 1 & 2 cell cases are pretty common so it saves a moderate amount of dtb size to have this encoding. However, it does come at the cost of greater code complexity. Is it worth it? I'm willing to believe it is, but I think the case needs to be made.

Quoted 7 lines

In term of code complexity, FDT_PROPDATA_PHANDLE introduced in the addons series, patch 7/74 [0], is a 1-cell (or 1-fdt32) "structured" tag.

It can be compared with FDT_PROPDATA_PHANDLE_REF, introduced in patch 11/74 [1]. FDT_PROPDATA_PHANDLE_REF is a "Data length encoding" tag.

Modifications in libfdt/fdt.c are pretty similar for both tags.

Right, it won't be in the case of specific tag handling. It's the general case skipping that's more complex, because it has to consider both cases.

Quoted 45 lines

[0] https://lore.kernel.org/all/[email protected]/
[1] https://lore.kernel.org/all/[email protected]/

Quoted 6 lines

I'd also avoid the term "cell" here. To me a "cell" is specifically a term applying to a 32-bit value _within a device tree property_. These are 32-bits, but not part of a property. Plus if Segher reappears, he'll complain that in the old days of OF, a cell wasn't necessarily 32-bits :).

ok, I will avoid the term "cell" in the next iteration.

Quoted 18 lines
Quoted 18 lines

Bits 27..0 (TAG_ID) is the tag identifier defining a specific tag.

Introduce the structured tag values definition and some specific tags reserved for tests based on this structure definition.

---
 libfdt/fdt.h | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
libfdt/fdt.h +0 -0
index a07abfcc..f41a355f 100644
@@ -49,6 +49,7 @@ struct fdt_property {
 
Quoted 6 lines

libfdt/fdt.h struct fdt_property { · line 52

Quoted 3 lines
libfdt/fdt.h +1 -0
 #define FDT_MAGIC	0xd00dfeed	/* 4: version, 4: total size */
 #define FDT_TAGSIZE	sizeof(fdt32_t)
+#define FDT_CELLSIZE	sizeof(fdt32_t)  

I'd avoid creating this constant for similar reasons to avoid the term "cell" above.

Ok, I will avoid the constant and use sizeof(fdt32_t) directly when needed in the code.

Also, I will avoid the CELL in all other part of this file.

Best regards,
Hervé

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#27 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Hi David,

Quoted 28 lines · On Thu, 10 Sep 2026 19:32:48 +1000 David Gibson <[email protected]>…
Quoted 27 lines · Herve Codina

Hi David,

Quoted 21 lines · On Thu, 10 Sep 2026 14:51:08 +1000 David Gibson <[email protected]>…
Quoted 7 lines · Herve Codina

The goal of structured tag values is to ease the introduction of new tags in future releases with the capability for an already existing release to ignore those structured tags. In order to do that data length related to the unknown tag needs to be identified.

Also add a flag to tell an old release if this tag can be simply skipped or must lead to an error.

I suggested/insisted on this in the past, but I've since realised this isn't actually useful. The "structured tag" format is only useful because it allows you to skip over unknown tags, which means there's no point using it for ags that can't be skipped. If we need new tags that can't be safely skipped, they can be added as old-style tags instead.

In which case "old style" versus "new style" is no longer a good
characterization: they would exist side by side, so the distinction is more "skippable" versus "non skippable" tags. Which suggests that "skippable tags" or "metadata tags" might be a better term than "structured tags" - that would focus more on the why than the how.

Quoted 3 lines
Quoted 1 line

Do you mean that the SKIP_SAFE bit should be removed ?

Yes.

So, in that case the term "skippable" tags makes sense.

Any non-skippable tag are then defined using the "old style".

The only non-skippable tag that will be introduce later by addons is FDT_BEGIN_NODE_REF (patch 51/71 [1]).

Data related to this tag is the symbol name and so a string.

Using the "old style" for this tag, I will remove the 32-bit data lengh. The next tag will be after the end of string '\0' + potential alignment.

This is consistent with "old style" tags which have a string as data. Indedd no 32-bit data lengh were present for those "old style" tags.

Does it make sense on your side?

[1] https://lore.kernel.org/all/[email protected]/

Quoted 36 lines
Quoted 6 lines

I like the defined structure with the DATA_LEN_ENCODING part. Even for tags which are not "skippable".

This ensures a kind of standardized format for all future tags instead of a specific definition (related to the length of the data) for each new tag.

If we were designing the dtb format from scratch, I'd agree. But given we already have what we have I think the drawbacks of introducing a second way of doing tags outweighs the benefits.

Quoted 2 lines

For this kind of information related to the length of data, I prefer a global rule instead of tag-specific rules.

Right, but it can't truly be global, because we have the existing tags.

Quoted 19 lines
Quoted 19 lines
Quoted 18 lines

Structured tag value is defined on 32bit and is defined as follow:

Bits | 31 | 30 | 29 28 | 27 0|
------+----+-----------+-------------------+--------+
Fields| 1 | SKIP_SAFE | DATA_LEN_ENCODING | TAG_ID |
------+----+-----------+-------------------+--------+

Bit 31 is always set to 1 to identify a structured tag value.

Bit 30 (SKIP_SAFE) is set to 1 if the tag can be safely ignored when its TAG_ID value is not a known value (unknown tag). If the SKIP_SAFE bit is set to 0 this tag must not be ignored and an error should be reported when its TAG_ID value is not a known value (unknown tag).

Bits 29..28 (DATA_LEN_ENCODING) indicates the length of the data related to the tag. Following values are possible:
- 0b00: No data.
The tag is followed by the next tag value.

...

Quoted 17 lines
Quoted 17 lines
Quoted 5 lines
Quoted 5 lines

- 0b11: Data length encoding
The tag is followed by a cell (u32) indicating the size of the data. This size is given in bytes. Data are available right after this cell.

Quoted 8 lines
Quoted 3 lines

The next tag is available after the data. Padding is present after the data in order to have the next tag aligned on 32bits. This padding is not included in the size of the data.

I'm guessing the 1 & 2 cell cases are pretty common so it saves a moderate amount of dtb size to have this encoding. However, it does come at the cost of greater code complexity. Is it worth it? I'm willing to believe it is, but I think the case needs to be made.

In term of code complexity, FDT_PROPDATA_PHANDLE introduced in the addons series, patch 7/74 [0], is a 1-cell (or 1-fdt32) "structured" tag.

Quoted 8 lines
Quoted 4 lines

It can be compared with FDT_PROPDATA_PHANDLE_REF, introduced in patch 11/74 [1]. FDT_PROPDATA_PHANDLE_REF is a "Data length encoding" tag.

Modifications in libfdt/fdt.c are pretty similar for both tags.

Right, it won't be in the case of specific tag handling. It's the general case skipping that's more complex, because it has to consider both cases.

I don't understand. What do you mean ?

Current implementation for skipping tags is not so complex.

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Best regards,
Hervé

#28 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 33 lines · Herve Codina

Hi David,

Quoted 28 lines · On Thu, 10 Sep 2026 19:32:48 +1000 David Gibson <[email protected]>…
Quoted 27 lines · Herve Codina

Hi David,

Quoted 21 lines · On Thu, 10 Sep 2026 14:51:08 +1000 David Gibson <[email protected]>…
Quoted 7 lines · Herve Codina

The goal of structured tag values is to ease the introduction of new tags in future releases with the capability for an already existing release to ignore those structured tags. In order to do that data length related to the unknown tag needs to be identified.

Also add a flag to tell an old release if this tag can be simply skipped or must lead to an error.

I suggested/insisted on this in the past, but I've since realised this isn't actually useful. The "structured tag" format is only useful because it allows you to skip over unknown tags, which means there's no point using it for ags that can't be skipped. If we need new tags that can't be safely skipped, they can be added as old-style tags instead.

In which case "old style" versus "new style" is no longer a good
characterization: they would exist side by side, so the distinction is more "skippable" versus "non skippable" tags. Which suggests that "skippable tags" or "metadata tags" might be a better term than "structured tags" - that would focus more on the why than the how.

Quoted 7 lines
Quoted 3 lines
Quoted 1 line

Do you mean that the SKIP_SAFE bit should be removed ?

Yes.

So, in that case the term "skippable" tags makes sense.

Any non-skippable tag are then defined using the "old style".

Right. I kind of prefer the term "metadata" *if* it's actually accurate, but I'm not sure it is.

Quoted 2 lines

The only non-skippable tag that will be introduce later by addons is FDT_BEGIN_NODE_REF (patch 51/71 [1]).

Ok.

Quoted 9 lines

Data related to this tag is the symbol name and so a string.

Using the "old style" for this tag, I will remove the 32-bit data lengh. The next tag will be after the end of string '\0' + potential alignment.

This is consistent with "old style" tags which have a string as data. Indedd no 32-bit data lengh were present for those "old style" tags.

Does it make sense on your side?

Yes, that makes sense.

Quoted 61 lines

[1] https://lore.kernel.org/all/[email protected]/

Quoted 36 lines
Quoted 6 lines

I like the defined structure with the DATA_LEN_ENCODING part. Even for tags which are not "skippable".

This ensures a kind of standardized format for all future tags instead of a specific definition (related to the length of the data) for each new tag.

If we were designing the dtb format from scratch, I'd agree. But given we already have what we have I think the drawbacks of introducing a second way of doing tags outweighs the benefits.

Quoted 2 lines

For this kind of information related to the length of data, I prefer a global rule instead of tag-specific rules.

Right, but it can't truly be global, because we have the existing tags.

Quoted 19 lines
Quoted 19 lines
Quoted 18 lines

Structured tag value is defined on 32bit and is defined as follow:

Bits | 31 | 30 | 29 28 | 27 0|
------+----+-----------+-------------------+--------+
Fields| 1 | SKIP_SAFE | DATA_LEN_ENCODING | TAG_ID |
------+----+-----------+-------------------+--------+

Bit 31 is always set to 1 to identify a structured tag value.

Bit 30 (SKIP_SAFE) is set to 1 if the tag can be safely ignored when its TAG_ID value is not a known value (unknown tag). If the SKIP_SAFE bit is set to 0 this tag must not be ignored and an error should be reported when its TAG_ID value is not a known value (unknown tag).

Bits 29..28 (DATA_LEN_ENCODING) indicates the length of the data related to the tag. Following values are possible:
- 0b00: No data.
The tag is followed by the next tag value.

...

Quoted 22 lines
Quoted 21 lines
Quoted 5 lines
Quoted 5 lines

- 0b11: Data length encoding
The tag is followed by a cell (u32) indicating the size of the data. This size is given in bytes. Data are available right after this cell.

Quoted 8 lines
Quoted 3 lines

The next tag is available after the data. Padding is present after the data in order to have the next tag aligned on 32bits. This padding is not included in the size of the data.

I'm guessing the 1 & 2 cell cases are pretty common so it saves a moderate amount of dtb size to have this encoding. However, it does come at the cost of greater code complexity. Is it worth it? I'm willing to believe it is, but I think the case needs to be made.

In term of code complexity, FDT_PROPDATA_PHANDLE introduced in the addons series, patch 7/74 [0], is a 1-cell (or 1-fdt32) "structured" tag.

It can be compared with FDT_PROPDATA_PHANDLE_REF, introduced in patch 11/74 [1]. FDT_PROPDATA_PHANDLE_REF is a "Data length encoding" tag.

Modifications in libfdt/fdt.c are pretty similar for both tags.

Quoted 7 lines
Quoted 3 lines

Right, it won't be in the case of specific tag handling. It's the general case skipping that's more complex, because it has to consider both cases.

I don't understand. What do you mean ?

Current implementation for skipping tags is not so complex.

Not that complex, no, but still more complex than it would be if we always have the 32-bit length field.

Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#29 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

[0] https://elixir.bootlin.com/linux/v7.2.5/source/arch/arm64/boot/dts/arm/juno.dts

Best regards,
Hervé

#30 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 34 lines · Herve Codina

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Quoted 6 lines

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

Yeah, those proportions are high enough that I think it's worth it.

Quoted 9 lines

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

Quoted 3 lines

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

Well, I'm convinced we want some sort of compact encoding of the length, but I think we can do better than the current proposal. It seems implausible to me that we'll need 2^29 different metadata tags, so I think we can spend some more of the tag bits on the length. How about:

0x80000000 structured tag bit
0x7fff0000 tag type
0x0000ffff tag length

So we have up to 2^15 (32k) different structured tags each with a length of [0..65534] bytes (length==65535 reserved for those that need a full 32-bit length word).

I believe that will avoid the extra length word for everything you have currently drafted.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#31 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Hi David,

Quoted 66 lines · On Wed, 16 Sep 2026 15:21:15 +1000 David Gibson <[email protected]>…
Quoted 34 lines · Herve Codina

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Quoted 6 lines

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

Yeah, those proportions are high enough that I think it's worth it.

Quoted 9 lines

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

Quoted 3 lines

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

Well, I'm convinced we want some sort of compact encoding of the length, but I think we can do better than the current proposal. It seems implausible to me that we'll need 2^29 different metadata tags, so I think we can spend some more of the tag bits on the length. How about:

   0x80000000		structured tag bit
   0x7fff0000		tag type
   0x0000ffff		tag length
Quoted 7 lines

So we have up to 2^15 (32k) different structured tags each with a length of [0..65534] bytes (length==65535 reserved for those that need a full 32-bit length word).

I believe that will avoid the extra length word for everything you have currently drafted.

Yes, this will avoid the extra length field. The drawback is the that the tag value is no more a well fixed value. Each time we have to check the tag value we have to filter out the tag length.

For instance:
- FDT_PROPDATA_PHANDLE
fixed data size 4 bytes for offset
tag value: 0x80010004

- FDT_PROPDATA_PHANDLE_REF
data: 4 bytes for offset + N bytes for a string
tag value 0x8002ssss with ssss for the size

This will lead to code like this:
tag = fdt_next_tag();
if (tag == FDT_PROPDATA_PHANDLE)

    /* Do something */

if (TAG_GET_ID(tag) == FDT_PROPDATA_PHANDLE_REF)

    /* Do something */

Further more, in the code you will both a mix of both construction:
while (tag == FDT_NOP || tag == FDT_BEGIN_NODE ||

         TAG_GET_ID(tag) == FDT_BEGIN_NODE_REF);

with #define TAG_GET_ID(tag) ((tag) & 0xffff0000)

Also when we write dtbs either in libfdt or dtc, tags value have to be built with the length when needed.

#define TAG_VALUE(tag_id, length) (((tag_id) & 0xffff0000) || \
                                   ((length) & 0x0000ffff))

I am totally fine with that but we need to have it in mind.

Of course, I can encode FDT_PROPDATA_PHANDLE_REF with 0x8002ffff + length field but we lose all the benefits

Ready to see TAG_GET_ID(tag) and TAG_VALUE(tag_id, length) when needed in the code?

Best regards,
Hervé

#32 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 92 lines · Herve Codina

Hi David,

Quoted 66 lines · On Wed, 16 Sep 2026 15:21:15 +1000 David Gibson <[email protected]>…
Quoted 34 lines · Herve Codina

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Quoted 6 lines

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

Yeah, those proportions are high enough that I think it's worth it.

Quoted 9 lines

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

Quoted 3 lines

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

Well, I'm convinced we want some sort of compact encoding of the length, but I think we can do better than the current proposal. It seems implausible to me that we'll need 2^29 different metadata tags, so I think we can spend some more of the tag bits on the length. How about:

   0x80000000		structured tag bit
   0x7fff0000		tag type
   0x0000ffff		tag length
Quoted 7 lines

So we have up to 2^15 (32k) different structured tags each with a length of [0..65534] bytes (length==65535 reserved for those that need a full 32-bit length word).

I believe that will avoid the extra length word for everything you have currently drafted.

Yes, this will avoid the extra length field. The drawback is the that the tag value is no more a well fixed value. Each time we have to check the tag value we have to filter out the tag length.

For instance:
- FDT_PROPDATA_PHANDLE
fixed data size 4 bytes for offset
tag value: 0x80010004

- FDT_PROPDATA_PHANDLE_REF
data: 4 bytes for offset + N bytes for a string
tag value 0x8002ssss with ssss for the size

Quoted 7 lines

This will lead to code like this:
tag = fdt_next_tag();
if (tag == FDT_PROPDATA_PHANDLE)

    /* Do something */

if (TAG_GET_ID(tag) == FDT_PROPDATA_PHANDLE_REF)

    /* Do something */

True. But.. a similar problem kind of exists with the original proposed encoding too: we *expect* a tag with fixed 4-byte contents to use the "1 cell" flags, but we need to consider the case of encoding it as VARLEN with a length field of 4. We could choose to make that forbidden, but we'd still need to consider who's responsible for enforcing that.

Similarly, if a variable length metadata tag happens to have length 4 or 8 in a particular place, is it valid to encode it with the 1-cell or 2-cell flag?

As a variant on my proposal, I'd also be fine with dividing the structed tags into several classes with bits indicating which is which. Either:

* "short" vs "long": "short" always has the length within the tag word (and so cannot exceed 64k, or however many bits we set aside) whereas long always has a length word
* "fixed" vs "variable", fixed length tag types always have the same length, so the length can be considered part of the tag. Variable would have a length word.

Not sure if that makes things any easier, but they might, and I'd be fine with either option (or some combination). In any of these cases we do need to spell out what the requirements are: for dtb writers, for dtb readers and for whoever defines a new tag.

Quoted 4 lines

Further more, in the code you will both a mix of both construction:
while (tag == FDT_NOP || tag == FDT_BEGIN_NODE ||

         TAG_GET_ID(tag) == FDT_BEGIN_NODE_REF);
Quoted 8 lines

with #define TAG_GET_ID(tag) ((tag) & 0xffff0000)

Also when we write dtbs either in libfdt or dtc, tags value have to be built with the length when needed.

#define TAG_VALUE(tag_id, length) (((tag_id) & 0xffff0000) || \
                                   ((length) & 0x0000ffff))

I am totally fine with that but we need to have it in mind.

Right, that's not a deal breaker for me - especially since I think we'll need some similar stuff even with the original proposal.

Quoted 5 lines

Of course, I can encode FDT_PROPDATA_PHANDLE_REF with 0x8002ffff + length field but we lose all the benefits

Ready to see TAG_GET_ID(tag) and TAG_VALUE(tag_id, length) when needed in the code?

I think so, though that could change depending on what it ends up looking like in practice.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#33 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Hi David,

Quoted 108 lines · On Fri, 18 Sep 2026 14:41:11 +1000 David Gibson <[email protected]>…
Quoted 92 lines · Herve Codina

Hi David,

Quoted 66 lines · On Wed, 16 Sep 2026 15:21:15 +1000 David Gibson <[email protected]>…
Quoted 34 lines · Herve Codina

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Quoted 6 lines

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

Yeah, those proportions are high enough that I think it's worth it.

Quoted 9 lines

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

Quoted 3 lines

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

Well, I'm convinced we want some sort of compact encoding of the length, but I think we can do better than the current proposal. It seems implausible to me that we'll need 2^29 different metadata tags, so I think we can spend some more of the tag bits on the length. How about:

   0x80000000		structured tag bit
   0x7fff0000		tag type
   0x0000ffff		tag length
Quoted 7 lines

So we have up to 2^15 (32k) different structured tags each with a length of [0..65534] bytes (length==65535 reserved for those that need a full 32-bit length word).

I believe that will avoid the extra length word for everything you have currently drafted.

Yes, this will avoid the extra length field. The drawback is the that the tag value is no more a well fixed value. Each time we have to check the tag value we have to filter out the tag length.

For instance:
- FDT_PROPDATA_PHANDLE
fixed data size 4 bytes for offset
tag value: 0x80010004

- FDT_PROPDATA_PHANDLE_REF
data: 4 bytes for offset + N bytes for a string
tag value 0x8002ssss with ssss for the size

Quoted 7 lines

This will lead to code like this:
tag = fdt_next_tag();
if (tag == FDT_PROPDATA_PHANDLE)

    /* Do something */

if (TAG_GET_ID(tag) == FDT_PROPDATA_PHANDLE_REF)

    /* Do something */  

True. But.. a similar problem kind of exists with the original proposed encoding too: we *expect* a tag with fixed 4-byte contents to use the "1 cell" flags, but we need to consider the case of encoding it as VARLEN with a length field of 4. We could choose to make that forbidden, but we'd still need to consider who's responsible for enforcing that.

Quoted 3 lines

Similarly, if a variable length metadata tag happens to have length 4 or 8 in a particular place, is it valid to encode it with the 1-cell or 2-cell flag?

My position was: if we expect a tag with "1-cell" flag, using varlen field encoding is considered as an other tag and so either an error or a skippable unknown tag.

The same apply for varlen defined tag. Even if the data is, let's say 8 bytes, the tag cannot be moved to a "2-cells" tag.

The kind of data length encoding (1-cell, 2-cells, varlength) is done when the tag is defined and cannot be changed.

Who is responsible for enforcing that ?
I would say the documentation of the tag should clearly set the data encoding used for the tag and the documentation of the "skippable" format should say that data encoding is fixed for a given tag. It is set when the tag is defined and any changes at runtime should be considered as a different tag.

Of course we can introduce dynamic length encoding to set the data length encoding in the tag according to the exact data length found at runtime.

Quoted 11 lines

As a variant on my proposal, I'd also be fine with dividing the structed tags into several classes with bits indicating which is which. Either:

* "short" vs "long": "short" always has the length within the tag word (and so cannot exceed 64k, or however many bits we set aside) whereas long always has a length word
* "fixed" vs "variable", fixed length tag types always have the same length, so the length can be considered part of the tag. Variable would have a length word.

Well, only strings, or more generally arrays, need a varlen. For those item, I would use the varlen word and so "long" in your definition.

For all others where the sizeof(data) is well known when the tag is defined, I would use "fixed" and "long" only if sizeof(data) cannot be encoded by "fixed" (lengh > limit of dedicated bits).

Without any additional bits for any category, all of these fit with the following length encoding:
000...00: No data
000...01: 1 x 32-bit
111...10: N x 32-bit
111...11: varlen word

Quoted 22 lines

Not sure if that makes things any easier, but they might, and I'd be fine with either option (or some combination). In any of these cases we do need to spell out what the requirements are: for dtb writers, for dtb readers and for whoever defines a new tag.

Quoted 4 lines

Further more, in the code you will both a mix of both construction:
while (tag == FDT_NOP || tag == FDT_BEGIN_NODE ||

         TAG_GET_ID(tag) == FDT_BEGIN_NODE_REF);
Quoted 8 lines

with #define TAG_GET_ID(tag) ((tag) & 0xffff0000)

Also when we write dtbs either in libfdt or dtc, tags value have to be built with the length when needed.

#define TAG_VALUE(tag_id, length) (((tag_id) & 0xffff0000) || \
                                   ((length) & 0x0000ffff))

I am totally fine with that but we need to have it in mind.

Right, that's not a deal breaker for me - especially since I think we'll need some similar stuff even with the original proposal.

Quoted 9 lines
Quoted 5 lines

Of course, I can encode FDT_PROPDATA_PHANDLE_REF with 0x8002ffff + length field but we lose all the benefits

Ready to see TAG_GET_ID(tag) and TAG_VALUE(tag_id, length) when needed in the code?

I think so, though that could change depending on what it ends up looking like in practice.

Best regards,
Hervé

#34 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 113 lines · Herve Codina

Hi David,

Quoted 108 lines · On Fri, 18 Sep 2026 14:41:11 +1000 David Gibson <[email protected]>…
Quoted 92 lines · Herve Codina

Hi David,

Quoted 66 lines · On Wed, 16 Sep 2026 15:21:15 +1000 David Gibson <[email protected]>…
Quoted 34 lines · Herve Codina

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Quoted 6 lines

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

Yeah, those proportions are high enough that I think it's worth it.

Quoted 9 lines

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

Quoted 3 lines

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

Well, I'm convinced we want some sort of compact encoding of the length, but I think we can do better than the current proposal. It seems implausible to me that we'll need 2^29 different metadata tags, so I think we can spend some more of the tag bits on the length. How about:

   0x80000000		structured tag bit
   0x7fff0000		tag type
   0x0000ffff		tag length
Quoted 7 lines

So we have up to 2^15 (32k) different structured tags each with a length of [0..65534] bytes (length==65535 reserved for those that need a full 32-bit length word).

I believe that will avoid the extra length word for everything you have currently drafted.

Yes, this will avoid the extra length field. The drawback is the that the tag value is no more a well fixed value. Each time we have to check the tag value we have to filter out the tag length.

For instance:
- FDT_PROPDATA_PHANDLE
fixed data size 4 bytes for offset
tag value: 0x80010004

- FDT_PROPDATA_PHANDLE_REF
data: 4 bytes for offset + N bytes for a string
tag value 0x8002ssss with ssss for the size

Quoted 7 lines

This will lead to code like this:
tag = fdt_next_tag();
if (tag == FDT_PROPDATA_PHANDLE)

    /* Do something */

if (TAG_GET_ID(tag) == FDT_PROPDATA_PHANDLE_REF)

    /* Do something */  

True. But.. a similar problem kind of exists with the original proposed encoding too: we *expect* a tag with fixed 4-byte contents to use the "1 cell" flags, but we need to consider the case of encoding it as VARLEN with a length field of 4. We could choose to make that forbidden, but we'd still need to consider who's responsible for enforcing that.

Quoted 7 lines
Quoted 3 lines

Similarly, if a variable length metadata tag happens to have length 4 or 8 in a particular place, is it valid to encode it with the 1-cell or 2-cell flag?

My position was: if we expect a tag with "1-cell" flag, using varlen field encoding is considered as an other tag and so either an error or a skippable unknown tag.

So essentially tags of different (fixed) length live in different namespaces. Ok, that makes good sense to me, but wasn't initially obvious to me. So, I think we need to spell this out a bit better.

Quoted 27 lines

The same apply for varlen defined tag. Even if the data is, let's say 8 bytes, the tag cannot be moved to a "2-cells" tag.

The kind of data length encoding (1-cell, 2-cells, varlength) is done when the tag is defined and cannot be changed.

Who is responsible for enforcing that ?
I would say the documentation of the tag should clearly set the data encoding used for the tag and the documentation of the "skippable" format should say that data encoding is fixed for a given tag. It is set when the tag is defined and any changes at runtime should be considered as a different tag.

Of course we can introduce dynamic length encoding to set the data length encoding in the tag according to the exact data length found at runtime.

Quoted 10 lines

As a variant on my proposal, I'd also be fine with dividing the structed tags into several classes with bits indicating which is which. Either:

* "short" vs "long": "short" always has the length within the tag word (and so cannot exceed 64k, or however many bits we set aside) whereas long always has a length word
* "fixed" vs "variable", fixed length tag types always have the same length, so the length can be considered part of the tag. Variable would have a length word.

Quoted 6 lines

Well, only strings, or more generally arrays, need a varlen. For those item, I would use the varlen word and so "long" in your definition.

For all others where the sizeof(data) is well known when the tag is defined, I would use "fixed" and "long" only if sizeof(data) cannot be encoded by "fixed" (lengh > limit of dedicated bits).

Right, now understanding your thoughts on the originally proposed encoding, the "fixed" versus "variable" distinction makes more sense I think. I do see the advantage of never having a variable length encoded within the tag word.

Quoted 6 lines

Without any additional bits for any category, all of these fit with the following length encoding:
000...00: No data
000...01: 1 x 32-bit
111...10: N x 32-bit
111...11: varlen word

Right, so revising my suggestions in light of a better understanding of what you had in mind originally, it comes down to:

* I think adding more bits to the size field would be worthwhile to allow a wider variety of future fixed length metadata tags.

* Originally I was thinking that having a length in bytes rather than just a length in 32-bit words would be worth it. But thinking further, there's probably no benefit. The length rounded up to 32-bit words is all we need for skipping over it when unknown. Even if we want a fixed length tag with, say, 3 bytes of data, we can pad that out to a 1-word tag with a reserved byte.

Ok, so more length bits and better documentation of the fixed vs. variable distinction are the only remaming suggestions.

Quoted 34 lines
Quoted 21 lines

Not sure if that makes things any easier, but they might, and I'd be fine with either option (or some combination). In any of these cases we do need to spell out what the requirements are: for dtb writers, for dtb readers and for whoever defines a new tag.

Quoted 4 lines

Further more, in the code you will both a mix of both construction:
while (tag == FDT_NOP || tag == FDT_BEGIN_NODE ||

         TAG_GET_ID(tag) == FDT_BEGIN_NODE_REF);
Quoted 8 lines

with #define TAG_GET_ID(tag) ((tag) & 0xffff0000)

Also when we write dtbs either in libfdt or dtc, tags value have to be built with the length when needed.

#define TAG_VALUE(tag_id, length) (((tag_id) & 0xffff0000) || \
                                   ((length) & 0x0000ffff))

I am totally fine with that but we need to have it in mind.

Right, that's not a deal breaker for me - especially since I think we'll need some similar stuff even with the original proposal.

Quoted 9 lines
Quoted 5 lines

Of course, I can encode FDT_PROPDATA_PHANDLE_REF with 0x8002ffff + length field but we lose all the benefits

Ready to see TAG_GET_ID(tag) and TAG_VALUE(tag_id, length) when needed in the code?

I think so, though that could change depending on what it ends up looking like in practice.

Best regards,
Hervé

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#35 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 172 lines · On Sat, 19 Sep 2026 14:22:09 +1000 David Gibson <[email protected]>…
Quoted 113 lines · Herve Codina

Hi David,

Quoted 108 lines · On Fri, 18 Sep 2026 14:41:11 +1000 David Gibson <[email protected]>…
Quoted 92 lines · Herve Codina

Hi David,

Quoted 66 lines · On Wed, 16 Sep 2026 15:21:15 +1000 David Gibson <[email protected]>…
Quoted 34 lines · Herve Codina

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Quoted 6 lines

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

Yeah, those proportions are high enough that I think it's worth it.

Quoted 9 lines

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

Quoted 3 lines

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

Well, I'm convinced we want some sort of compact encoding of the length, but I think we can do better than the current proposal. It seems implausible to me that we'll need 2^29 different metadata tags, so I think we can spend some more of the tag bits on the length. How about:

   0x80000000		structured tag bit
   0x7fff0000		tag type
   0x0000ffff		tag length
Quoted 7 lines

So we have up to 2^15 (32k) different structured tags each with a length of [0..65534] bytes (length==65535 reserved for those that need a full 32-bit length word).

I believe that will avoid the extra length word for everything you have currently drafted.

Yes, this will avoid the extra length field. The drawback is the that the tag value is no more a well fixed value. Each time we have to check the tag value we have to filter out the tag length.

For instance:
- FDT_PROPDATA_PHANDLE
fixed data size 4 bytes for offset
tag value: 0x80010004

- FDT_PROPDATA_PHANDLE_REF
data: 4 bytes for offset + N bytes for a string
tag value 0x8002ssss with ssss for the size

Quoted 7 lines

This will lead to code like this:
tag = fdt_next_tag();
if (tag == FDT_PROPDATA_PHANDLE)

    /* Do something */

if (TAG_GET_ID(tag) == FDT_PROPDATA_PHANDLE_REF)

    /* Do something */    

True. But.. a similar problem kind of exists with the original proposed encoding too: we *expect* a tag with fixed 4-byte contents to use the "1 cell" flags, but we need to consider the case of encoding it as VARLEN with a length field of 4. We could choose to make that forbidden, but we'd still need to consider who's responsible for enforcing that.

Quoted 7 lines
Quoted 3 lines

Similarly, if a variable length metadata tag happens to have length 4 or 8 in a particular place, is it valid to encode it with the 1-cell or 2-cell flag?

My position was: if we expect a tag with "1-cell" flag, using varlen field encoding is considered as an other tag and so either an error or a skippable unknown tag.

So essentially tags of different (fixed) length live in different namespaces. Ok, that makes good sense to me, but wasn't initially obvious to me. So, I think we need to spell this out a bit better.

Quoted 27 lines

The same apply for varlen defined tag. Even if the data is, let's say 8 bytes, the tag cannot be moved to a "2-cells" tag.

The kind of data length encoding (1-cell, 2-cells, varlength) is done when the tag is defined and cannot be changed.

Who is responsible for enforcing that ?
I would say the documentation of the tag should clearly set the data encoding used for the tag and the documentation of the "skippable" format should say that data encoding is fixed for a given tag. It is set when the tag is defined and any changes at runtime should be considered as a different tag.

Of course we can introduce dynamic length encoding to set the data length encoding in the tag according to the exact data length found at runtime.

Quoted 10 lines

As a variant on my proposal, I'd also be fine with dividing the structed tags into several classes with bits indicating which is which. Either:

* "short" vs "long": "short" always has the length within the tag word (and so cannot exceed 64k, or however many bits we set aside) whereas long always has a length word
* "fixed" vs "variable", fixed length tag types always have the same length, so the length can be considered part of the tag. Variable would have a length word.

Quoted 6 lines

Well, only strings, or more generally arrays, need a varlen. For those item, I would use the varlen word and so "long" in your definition.

For all others where the sizeof(data) is well known when the tag is defined, I would use "fixed" and "long" only if sizeof(data) cannot be encoded by "fixed" (lengh > limit of dedicated bits).

Right, now understanding your thoughts on the originally proposed encoding, the "fixed" versus "variable" distinction makes more sense I think. I do see the advantage of never having a variable length encoded within the tag word.

Quoted 6 lines

Without any additional bits for any category, all of these fit with the following length encoding:
000...00: No data
000...01: 1 x 32-bit
111...10: N x 32-bit
111...11: varlen word

Quoted 5 lines

Right, so revising my suggestions in light of a better understanding of what you had in mind originally, it comes down to:

* I think adding more bits to the size field would be worthwhile to allow a wider variety of future fixed length metadata tags.

Right, I have planned to add one more bit compared to the original proposal. This leads to 3 bits and so 0 to 6 32-bit data words (0b111 means varlen word).

Do you think we should add one more bits?

Quoted 7 lines

* Originally I was thinking that having a length in bytes rather than just a length in 32-bit words would be worth it. But thinking further, there's probably no benefit. The length rounded up to 32-bit words is all we need for skipping over it when unknown. Even if we want a fixed length tag with, say, 3 bytes of data, we can pad that out to a 1-word tag with a reserved byte.

The varlen word could be kept in bytes.

Quoted 4 lines

Ok, so more length bits and better documentation of the fixed vs. variable distinction are the only remaming suggestions.

Best regards,
Hervé

Signature · 3 lines
Hervé Codina, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#36 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 178 lines · Herve Codina
Quoted 175 lines · On Sat, 19 Sep 2026 14:22:09 +1000 David Gibson <[email protected]>…
Quoted 113 lines · Herve Codina

Hi David,

Quoted 108 lines · On Fri, 18 Sep 2026 14:41:11 +1000 David Gibson <[email protected]>…
Quoted 92 lines · Herve Codina

Hi David,

Quoted 66 lines · On Wed, 16 Sep 2026 15:21:15 +1000 David Gibson <[email protected]>…
Quoted 34 lines · Herve Codina

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Quoted 6 lines

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

Yeah, those proportions are high enough that I think it's worth it.

Quoted 9 lines

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

Quoted 3 lines

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

Well, I'm convinced we want some sort of compact encoding of the length, but I think we can do better than the current proposal. It seems implausible to me that we'll need 2^29 different metadata tags, so I think we can spend some more of the tag bits on the length. How about:

   0x80000000		structured tag bit
   0x7fff0000		tag type
   0x0000ffff		tag length
Quoted 7 lines

So we have up to 2^15 (32k) different structured tags each with a length of [0..65534] bytes (length==65535 reserved for those that need a full 32-bit length word).

I believe that will avoid the extra length word for everything you have currently drafted.

Yes, this will avoid the extra length field. The drawback is the that the tag value is no more a well fixed value. Each time we have to check the tag value we have to filter out the tag length.

For instance:
- FDT_PROPDATA_PHANDLE
fixed data size 4 bytes for offset
tag value: 0x80010004

- FDT_PROPDATA_PHANDLE_REF
data: 4 bytes for offset + N bytes for a string
tag value 0x8002ssss with ssss for the size

Quoted 7 lines

This will lead to code like this:
tag = fdt_next_tag();
if (tag == FDT_PROPDATA_PHANDLE)

    /* Do something */

if (TAG_GET_ID(tag) == FDT_PROPDATA_PHANDLE_REF)

    /* Do something */    

True. But.. a similar problem kind of exists with the original proposed encoding too: we *expect* a tag with fixed 4-byte contents to use the "1 cell" flags, but we need to consider the case of encoding it as VARLEN with a length field of 4. We could choose to make that forbidden, but we'd still need to consider who's responsible for enforcing that.

Quoted 7 lines
Quoted 3 lines

Similarly, if a variable length metadata tag happens to have length 4 or 8 in a particular place, is it valid to encode it with the 1-cell or 2-cell flag?

My position was: if we expect a tag with "1-cell" flag, using varlen field encoding is considered as an other tag and so either an error or a skippable unknown tag.

So essentially tags of different (fixed) length live in different namespaces. Ok, that makes good sense to me, but wasn't initially obvious to me. So, I think we need to spell this out a bit better.

Quoted 27 lines

The same apply for varlen defined tag. Even if the data is, let's say 8 bytes, the tag cannot be moved to a "2-cells" tag.

The kind of data length encoding (1-cell, 2-cells, varlength) is done when the tag is defined and cannot be changed.

Who is responsible for enforcing that ?
I would say the documentation of the tag should clearly set the data encoding used for the tag and the documentation of the "skippable" format should say that data encoding is fixed for a given tag. It is set when the tag is defined and any changes at runtime should be considered as a different tag.

Of course we can introduce dynamic length encoding to set the data length encoding in the tag according to the exact data length found at runtime.

Quoted 10 lines

As a variant on my proposal, I'd also be fine with dividing the structed tags into several classes with bits indicating which is which. Either:

* "short" vs "long": "short" always has the length within the tag word (and so cannot exceed 64k, or however many bits we set aside) whereas long always has a length word
* "fixed" vs "variable", fixed length tag types always have the same length, so the length can be considered part of the tag. Variable would have a length word.

Quoted 6 lines

Well, only strings, or more generally arrays, need a varlen. For those item, I would use the varlen word and so "long" in your definition.

For all others where the sizeof(data) is well known when the tag is defined, I would use "fixed" and "long" only if sizeof(data) cannot be encoded by "fixed" (lengh > limit of dedicated bits).

Right, now understanding your thoughts on the originally proposed encoding, the "fixed" versus "variable" distinction makes more sense I think. I do see the advantage of never having a variable length encoded within the tag word.

Quoted 6 lines

Without any additional bits for any category, all of these fit with the following length encoding:
000...00: No data
000...01: 1 x 32-bit
111...10: N x 32-bit
111...11: varlen word

Right, so revising my suggestions in light of a better understanding of what you had in mind originally, it comes down to:

Quoted 7 lines
Quoted 2 lines

* I think adding more bits to the size field would be worthwhile to allow a wider variety of future fixed length metadata tags.

Right, I have planned to add one more bit compared to the original proposal. This leads to 3 bits and so 0 to 6 32-bit data words (0b111 means varlen word).

Do you think we should add one more bits?

I don't think we particularly need them for the tag type, so yes, I think that would be worthwhile.

Quoted 8 lines
Quoted 6 lines

* Originally I was thinking that having a length in bytes rather than just a length in 32-bit words would be worth it. But thinking further, there's probably no benefit. The length rounded up to 32-bit words is all we need for skipping over it when unknown. Even if we want a fixed length tag with, say, 3 bytes of data, we can pad that out to a 1-word tag with a reserved byte.

The varlen word could be kept in bytes.

The varlen word _must_ be kept in bytes.

Quoted 2 lines
Quoted 2 lines

Ok, so more length bits and better documentation of the fixed vs. variable distinction are the only remaming suggestions.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#37 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Hi David,

Quoted 197 lines · On Thu, 24 Sep 2026 13:49:55 +1000 David Gibson <[email protected]>…
Quoted 178 lines · Herve Codina
Quoted 175 lines · On Sat, 19 Sep 2026 14:22:09 +1000 David Gibson <[email protected]>…
Quoted 113 lines · Herve Codina

Hi David,

Quoted 108 lines · On Fri, 18 Sep 2026 14:41:11 +1000 David Gibson <[email protected]>…
Quoted 92 lines · Herve Codina

Hi David,

Quoted 66 lines · On Wed, 16 Sep 2026 15:21:15 +1000 David Gibson <[email protected]>…
Quoted 34 lines · Herve Codina

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Quoted 6 lines

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

Yeah, those proportions are high enough that I think it's worth it.

Quoted 9 lines

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

Quoted 3 lines

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

Well, I'm convinced we want some sort of compact encoding of the length, but I think we can do better than the current proposal. It seems implausible to me that we'll need 2^29 different metadata tags, so I think we can spend some more of the tag bits on the length. How about:

   0x80000000		structured tag bit
   0x7fff0000		tag type
   0x0000ffff		tag length
Quoted 7 lines

So we have up to 2^15 (32k) different structured tags each with a length of [0..65534] bytes (length==65535 reserved for those that need a full 32-bit length word).

I believe that will avoid the extra length word for everything you have currently drafted.

Yes, this will avoid the extra length field. The drawback is the that the tag value is no more a well fixed value. Each time we have to check the tag value we have to filter out the tag length.

For instance:
- FDT_PROPDATA_PHANDLE
fixed data size 4 bytes for offset
tag value: 0x80010004

- FDT_PROPDATA_PHANDLE_REF
data: 4 bytes for offset + N bytes for a string
tag value 0x8002ssss with ssss for the size

Quoted 7 lines

This will lead to code like this:
tag = fdt_next_tag();
if (tag == FDT_PROPDATA_PHANDLE)

    /* Do something */

if (TAG_GET_ID(tag) == FDT_PROPDATA_PHANDLE_REF)

    /* Do something */      

True. But.. a similar problem kind of exists with the original proposed encoding too: we *expect* a tag with fixed 4-byte contents to use the "1 cell" flags, but we need to consider the case of encoding it as VARLEN with a length field of 4. We could choose to make that forbidden, but we'd still need to consider who's responsible for enforcing that.

Quoted 7 lines
Quoted 3 lines

Similarly, if a variable length metadata tag happens to have length 4 or 8 in a particular place, is it valid to encode it with the 1-cell or 2-cell flag?

My position was: if we expect a tag with "1-cell" flag, using varlen field encoding is considered as an other tag and so either an error or a skippable unknown tag.

So essentially tags of different (fixed) length live in different namespaces. Ok, that makes good sense to me, but wasn't initially obvious to me. So, I think we need to spell this out a bit better.

Quoted 27 lines

The same apply for varlen defined tag. Even if the data is, let's say 8 bytes, the tag cannot be moved to a "2-cells" tag.

The kind of data length encoding (1-cell, 2-cells, varlength) is done when the tag is defined and cannot be changed.

Who is responsible for enforcing that ?
I would say the documentation of the tag should clearly set the data encoding used for the tag and the documentation of the "skippable" format should say that data encoding is fixed for a given tag. It is set when the tag is defined and any changes at runtime should be considered as a different tag.

Of course we can introduce dynamic length encoding to set the data length encoding in the tag according to the exact data length found at runtime.

Quoted 10 lines

As a variant on my proposal, I'd also be fine with dividing the structed tags into several classes with bits indicating which is which. Either:

* "short" vs "long": "short" always has the length within the tag word (and so cannot exceed 64k, or however many bits we set aside) whereas long always has a length word
* "fixed" vs "variable", fixed length tag types always have the same length, so the length can be considered part of the tag. Variable would have a length word.

Quoted 6 lines

Well, only strings, or more generally arrays, need a varlen. For those item, I would use the varlen word and so "long" in your definition.

For all others where the sizeof(data) is well known when the tag is defined, I would use "fixed" and "long" only if sizeof(data) cannot be encoded by "fixed" (lengh > limit of dedicated bits).

Right, now understanding your thoughts on the originally proposed encoding, the "fixed" versus "variable" distinction makes more sense I think. I do see the advantage of never having a variable length encoded within the tag word.

Quoted 6 lines

Without any additional bits for any category, all of these fit with the following length encoding:
000...00: No data
000...01: 1 x 32-bit
111...10: N x 32-bit
111...11: varlen word

Right, so revising my suggestions in light of a better understanding of what you had in mind originally, it comes down to:

Quoted 7 lines
Quoted 2 lines

* I think adding more bits to the size field would be worthwhile to allow a wider variety of future fixed length metadata tags.

Right, I have planned to add one more bit compared to the original proposal. This leads to 3 bits and so 0 to 6 32-bit data words (0b111 means varlen word).

Do you think we should add one more bits?

I don't think we particularly need them for the tag type, so yes, I think that would be worthwhile.

Quoted 7 lines
Quoted 6 lines

* Originally I was thinking that having a length in bytes rather than just a length in 32-bit words would be worth it. But thinking further, there's probably no benefit. The length rounded up to 32-bit words is all we need for skipping over it when unknown. Even if we want a fixed length tag with, say, 3 bytes of data, we can pad that out to a 1-word tag with a reserved byte.

Quoted 7 lines
Quoted 1 line

The varlen word could be kept in bytes.

The varlen word _must_ be kept in bytes.

Quoted 2 lines
Quoted 2 lines

Ok, so more length bits and better documentation of the fixed vs. variable distinction are the only remaming suggestions.

So the name "structured" tag will be replace my "skippable" tag. I don't want to use "metadata" because we don't know if future tags will be only metadata tags or something else that shouldn't be qualified by "metadata".

Skippable tag format:
- bit 31: set to 1
Indentify a skippable tag.
- bits 30..24: Data length encoding

      Encode the length of data attached to the tag.
      0b0000000: No data
      0b0000001: 1 32-bit word
      0b0000010: 2 x 32-bits words
      0b0000011: 3 x 32-bits words
      ...
      0b1111101: 125 x 32-bits words
      0b1111110: 126 x 32-bits words
      0b1111111: varlen encoding. The length of data is encode by an 32-bit
                 word available right after the tag. This word gives the
                 length of data in bytes.

- bits 23..0: Tag identifier

The full tag value are used to identify a tag. Two skippable tags with the same tag identifier field but with different data lengh encoding should be considered as two different tags.

The exact tag value is completely known when the new tag is defined and its data length encoding must not be determine at runtime when the exact length of data is known.

Any tags where the length of the data is not known when the tag is defined (i.e. sizeof(data) cannot be determined when the tag is defined) must use the varlen encoding value (0b1111111). Tags with strings or arrays where the number of items in the array can vary should use the varlen encoding.

Also for tags where the length of data is greater than 126 x 32-bits words (maximum value without using varlen encoding), the varlen encoding must be used even if the length of data is known when the tag is defined.

Tags reserved for tests purpose:
Any tags with the tag identifier set to 0xffffff are reserved for test purpose. When a parser find this kind of tag, it must ignore the tag (skip it). A generator must never use this kind of tags, except, of course, if the generator is used to generate a dtb for test purpose.

What is you opinion about this description?
Do you agree on the description? If so I will implement it on next iteration.

Best regards,
Hervé

#38 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 256 lines · Herve Codina

Hi David,

Quoted 197 lines · On Thu, 24 Sep 2026 13:49:55 +1000 David Gibson <[email protected]>…
Quoted 178 lines · Herve Codina
Quoted 175 lines · On Sat, 19 Sep 2026 14:22:09 +1000 David Gibson <[email protected]>…
Quoted 113 lines · Herve Codina

Hi David,

Quoted 108 lines · On Fri, 18 Sep 2026 14:41:11 +1000 David Gibson <[email protected]>…
Quoted 92 lines · Herve Codina

Hi David,

Quoted 66 lines · On Wed, 16 Sep 2026 15:21:15 +1000 David Gibson <[email protected]>…
Quoted 34 lines · Herve Codina

Hi David,

On Sat, 12 Sep 2026 12:34:24 +1000
David Gibson <[email protected]> wrote:

...

Quoted 5 lines
Quoted 2 lines

Do you mean that we should avoid the DATA_LEN_ENCODING and always have the 32-bit value right after the tag to give the size for all "skippable" tags?

Yes.

I did a test using a dts file available in kernel sources. I used (arbitrary choice) juno.dts [0].

Without any new tags, the size of the compiled dtb is 27067 bytes.

With new metadata tags identifying phandles in properties (FDT_PROPDATA_PHANDLE), the size of the dtb becomes 29027 bytes and so 29027 - 27067 = 1960 bytes for those FDT_PROPDATA_PHANDLE tags (+7.2%).

The tags used are composed of:
32-bit: FDT_PROPDATA_PHANDLE value encoding 1 x 32-bit for data 32-bit: offset in the property where a phandle is present.

Removing the '1 x 32-bit' information from the tag value and adding a 32-bit 'length' in all cases will lead 3 x 32-bit values for a FDT_PROPDATA_PHANDLE tag (tag + length + offset) instead of the 2 x 32-bit (tag + offset).

Back to juno.dts instead of 1960 bytes, the FDT_PROPDATA_PHANDLE will need 1960 * 3 / 2 = 2640 bytes (+9.7%). This leads to around +2.5% of the whole dtb just to have the 32-bit for length. This +2.5% can be easily avoided.

Quoted 6 lines

Also, I will not be surprised to see more tags in the future adding some more metadata information and so increasing dtb sizes.

Quite often you have mentioned memory constraints system where libfdt should be as small as possible. On those system, the dtb itself is embedded in the binary close to libfdt. The size of dtb should be taken into account.

Yeah, those proportions are high enough that I think it's worth it.

Quoted 9 lines

If the SAFE_SKIP bit is removed, I even plan to use this now free bit in the length encoding part:
0b000: No data
0b001: 1 fdt32
0b010: 2 fdt32
...
0b110: 6 fdt32
0b111: On additional fdt32 to encode the length of data.

Quoted 3 lines

IHMO, length encoding bits in tag value definition should be kept and used for all tags where the length is fixed and can be encoded using these bits.

Well, I'm convinced we want some sort of compact encoding of the length, but I think we can do better than the current proposal. It seems implausible to me that we'll need 2^29 different metadata tags, so I think we can spend some more of the tag bits on the length. How about:

   0x80000000		structured tag bit
   0x7fff0000		tag type
   0x0000ffff		tag length
Quoted 7 lines

So we have up to 2^15 (32k) different structured tags each with a length of [0..65534] bytes (length==65535 reserved for those that need a full 32-bit length word).

I believe that will avoid the extra length word for everything you have currently drafted.

Yes, this will avoid the extra length field. The drawback is the that the tag value is no more a well fixed value. Each time we have to check the tag value we have to filter out the tag length.

For instance:
- FDT_PROPDATA_PHANDLE
fixed data size 4 bytes for offset
tag value: 0x80010004

- FDT_PROPDATA_PHANDLE_REF
data: 4 bytes for offset + N bytes for a string
tag value 0x8002ssss with ssss for the size

Quoted 7 lines

This will lead to code like this:
tag = fdt_next_tag();
if (tag == FDT_PROPDATA_PHANDLE)

    /* Do something */

if (TAG_GET_ID(tag) == FDT_PROPDATA_PHANDLE_REF)

    /* Do something */      

True. But.. a similar problem kind of exists with the original proposed encoding too: we *expect* a tag with fixed 4-byte contents to use the "1 cell" flags, but we need to consider the case of encoding it as VARLEN with a length field of 4. We could choose to make that forbidden, but we'd still need to consider who's responsible for enforcing that.

Quoted 7 lines
Quoted 3 lines

Similarly, if a variable length metadata tag happens to have length 4 or 8 in a particular place, is it valid to encode it with the 1-cell or 2-cell flag?

My position was: if we expect a tag with "1-cell" flag, using varlen field encoding is considered as an other tag and so either an error or a skippable unknown tag.

So essentially tags of different (fixed) length live in different namespaces. Ok, that makes good sense to me, but wasn't initially obvious to me. So, I think we need to spell this out a bit better.

Quoted 27 lines

The same apply for varlen defined tag. Even if the data is, let's say 8 bytes, the tag cannot be moved to a "2-cells" tag.

The kind of data length encoding (1-cell, 2-cells, varlength) is done when the tag is defined and cannot be changed.

Who is responsible for enforcing that ?
I would say the documentation of the tag should clearly set the data encoding used for the tag and the documentation of the "skippable" format should say that data encoding is fixed for a given tag. It is set when the tag is defined and any changes at runtime should be considered as a different tag.

Of course we can introduce dynamic length encoding to set the data length encoding in the tag according to the exact data length found at runtime.

Quoted 10 lines

As a variant on my proposal, I'd also be fine with dividing the structed tags into several classes with bits indicating which is which. Either:

* "short" vs "long": "short" always has the length within the tag word (and so cannot exceed 64k, or however many bits we set aside) whereas long always has a length word
* "fixed" vs "variable", fixed length tag types always have the same length, so the length can be considered part of the tag. Variable would have a length word.

Quoted 6 lines

Well, only strings, or more generally arrays, need a varlen. For those item, I would use the varlen word and so "long" in your definition.

For all others where the sizeof(data) is well known when the tag is defined, I would use "fixed" and "long" only if sizeof(data) cannot be encoded by "fixed" (lengh > limit of dedicated bits).

Right, now understanding your thoughts on the originally proposed encoding, the "fixed" versus "variable" distinction makes more sense I think. I do see the advantage of never having a variable length encoded within the tag word.

Quoted 6 lines

Without any additional bits for any category, all of these fit with the following length encoding:
000...00: No data
000...01: 1 x 32-bit
111...10: N x 32-bit
111...11: varlen word

Right, so revising my suggestions in light of a better understanding of what you had in mind originally, it comes down to:

Quoted 7 lines
Quoted 2 lines

* I think adding more bits to the size field would be worthwhile to allow a wider variety of future fixed length metadata tags.

Right, I have planned to add one more bit compared to the original proposal. This leads to 3 bits and so 0 to 6 32-bit data words (0b111 means varlen word).

Do you think we should add one more bits?

I don't think we particularly need them for the tag type, so yes, I think that would be worthwhile.

Quoted 7 lines
Quoted 6 lines

* Originally I was thinking that having a length in bytes rather than just a length in 32-bit words would be worth it. But thinking further, there's probably no benefit. The length rounded up to 32-bit words is all we need for skipping over it when unknown. Even if we want a fixed length tag with, say, 3 bytes of data, we can pad that out to a 1-word tag with a reserved byte.

Quoted 7 lines
Quoted 1 line

The varlen word could be kept in bytes.

The varlen word _must_ be kept in bytes.

Quoted 2 lines
Quoted 2 lines

Ok, so more length bits and better documentation of the fixed vs. variable distinction are the only remaming suggestions.

So the name "structured" tag will be replace my "skippable" tag. I don't want to use "metadata" because we don't know if future tags will be only metadata tags or something else that shouldn't be qualified by "metadata".

Skippable tag format:
- bit 31: set to 1
Indentify a skippable tag.
- bits 30..24: Data length encoding

      Encode the length of data attached to the tag.
      0b0000000: No data
      0b0000001: 1 32-bit word
      0b0000010: 2 x 32-bits words
      0b0000011: 3 x 32-bits words
      ...
      0b1111101: 125 x 32-bits words
      0b1111110: 126 x 32-bits words
      0b1111111: varlen encoding. The length of data is encode by an 32-bit
                 word available right after the tag. This word gives the
                 length of data in bytes.

- bits 23..0: Tag identifier

The full tag value are used to identify a tag. Two skippable tags with the same tag identifier field but with different data lengh encoding should be considered as two different tags.

The exact tag value is completely known when the new tag is defined and its data length encoding must not be determine at runtime when the exact length of data is known.

Any tags where the length of the data is not known when the tag is defined (i.e. sizeof(data) cannot be determined when the tag is defined) must use the varlen encoding value (0b1111111). Tags with strings or arrays where the number of items in the array can vary should use the varlen encoding.

Also for tags where the length of data is greater than 126 x 32-bits words (maximum value without using varlen encoding), the varlen encoding must be used even if the length of data is known when the tag is defined.

Tags reserved for tests purpose:
Any tags with the tag identifier set to 0xffffff are reserved for test purpose. When a parser find this kind of tag, it must ignore the tag (skip it). A generator must never use this kind of tags, except, of course, if the generator is used to generate a dtb for test purpose.

Quoted 2 lines

What is you opinion about this description?
Do you agree on the description? If so I will implement it on next iteration.

Sounds good, thanks for the revisions.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#39 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

In reply to Herve Codina

On Wed, Aug 26, 2026 at 10:31:37AM +0200, Herve Codina wrote:
[snip]

libfdt/fdt.h struct fdt_property { · line 81

Quoted 9 lines
libfdt/fdt.h +9 -0
+#define FDT_TAG_CAN_SKIP(tag_data, tag_id) \
+		(FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE | tag_data | tag_id)
+
+/* Tests reserved tags */
+#define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
+#define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
+#define FDT_TEST_2CELLS_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_2CELLS, 0)
+#define FDT_TEST_VARLEN_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_VARLEN, 0)
+#define FDT_TEST_NONE_NO_SKIP		FDT_TAG_NO_SKIP(FDT_TAG_DATA_NONE, 0)

Sorry, missed until I saw the later treegen changes that this is defining some specific tag values.

Given that, "Tests reserved tags" needs to be expanded to better explain what these tags are for - what should readers do upon encountering them, when should writers use it ("never, unless you're a test case" is acceptable).

It might be worth reserving a whole range of tag values for tests / documentation / experimentation, rather than just a handful of specific values.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#40 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Hi david,

Quoted 15 lines · On Thu, 10 Sep 2026 15:33:58 +1000 David Gibson <[email protected]>…

On Wed, Aug 26, 2026 at 10:31:37AM +0200, Herve Codina wrote:
[snip]

libfdt/fdt.h struct fdt_property { · line 81

Quoted 9 lines
libfdt/fdt.h +9 -0
+#define FDT_TAG_CAN_SKIP(tag_data, tag_id) \
+		(FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE | tag_data | tag_id)
+
+/* Tests reserved tags */
+#define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
+#define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
+#define FDT_TEST_2CELLS_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_2CELLS, 0)
+#define FDT_TEST_VARLEN_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_VARLEN, 0)
+#define FDT_TEST_NONE_NO_SKIP		FDT_TAG_NO_SKIP(FDT_TAG_DATA_NONE, 0)  

Sorry, missed until I saw the later treegen changes that this is defining some specific tag values.

Quoted 4 lines

Given that, "Tests reserved tags" needs to be expanded to better explain what these tags are for - what should readers do upon encountering them, when should writers use it ("never, unless you're a test case" is acceptable).

I would say, in both cases, consider them as "unknown" tags.
And so:
/*
* Tests reserved tags
*
* When those tags are encountered they should be considered as "unknown"
* tags and rules related to "unknown" tags must be followed.
*
* Readers should skip them or fail depending on the SKIP_SAFE flag. Writers
* should never use those tags. Their usage is only acceptable in test cases. */

Quoted 5 lines

It might be worth reserving a whole range of tag values for tests / documentation / experimentation, rather than just a handful of specific values.

Ok. The range reservation will added be in the comment.

/*
* Tests reserved tags
*
* A TAG_ID range in "structured tags" is reserved to tests tags.
* This tests reserved range is from tag_id 0 to tag_id 0x100.
*
* When those tags are encountered they should be considered as "unknown"
* tags and rules related to "unknown" tags must be followed.
*
* Readers should skip them or fail depending on the SKIP_SAFE flag. Writers
* should never use those tags. Their usage is only acceptable in test cases. */

Is it ok?

Best regards,
Hervé

Signature · 3 lines
Hervé Codina, Bootlin
Embedded Linux and Kernel engineering
https://bootlin.com
#41 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 58 lines · Herve Codina

Hi david,

Quoted 15 lines · On Thu, 10 Sep 2026 15:33:58 +1000 David Gibson <[email protected]>…

On Wed, Aug 26, 2026 at 10:31:37AM +0200, Herve Codina wrote:
[snip]

libfdt/fdt.h struct fdt_property { · line 81

Quoted 9 lines
libfdt/fdt.h +9 -0
+#define FDT_TAG_CAN_SKIP(tag_data, tag_id) \
+		(FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE | tag_data | tag_id)
+
+/* Tests reserved tags */
+#define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
+#define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
+#define FDT_TEST_2CELLS_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_2CELLS, 0)
+#define FDT_TEST_VARLEN_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_VARLEN, 0)
+#define FDT_TEST_NONE_NO_SKIP		FDT_TAG_NO_SKIP(FDT_TAG_DATA_NONE, 0)  

Sorry, missed until I saw the later treegen changes that this is defining some specific tag values.

Quoted 4 lines

Given that, "Tests reserved tags" needs to be expanded to better explain what these tags are for - what should readers do upon encountering them, when should writers use it ("never, unless you're a test case" is acceptable).

I would say, in both cases, consider them as "unknown" tags.
And so:
/*
* Tests reserved tags
*
* When those tags are encountered they should be considered as "unknown"
* tags and rules related to "unknown" tags must be followed.
*
* Readers should skip them or fail depending on the SKIP_SAFE flag. Writers
* should never use those tags. Their usage is only acceptable in test cases. */

Quoted 5 lines

It might be worth reserving a whole range of tag values for tests / documentation / experimentation, rather than just a handful of specific values.

Ok. The range reservation will added be in the comment.

/*
* Tests reserved tags
*
* A TAG_ID range in "structured tags" is reserved to tests tags.
* This tests reserved range is from tag_id 0 to tag_id 0x100.
*
* When those tags are encountered they should be considered as "unknown"
* tags and rules related to "unknown" tags must be followed.
*
* Readers should skip them or fail depending on the SKIP_SAFE flag. Writers
* should never use those tags. Their usage is only acceptable in test cases. */

Quoted 1 line

Is it ok?

I'd probably put the reserved range up high somewhere rather than starting at 0. Otherwise it looks good.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#42 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Hi David,

On Thu, 10 Sep 2026 19:41:42 +1000
David Gibson <[email protected]> wrote:

...

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
libfdt/fdt.h +6 -0
+/* Tests reserved tags */
+#define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
+#define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
+#define FDT_TEST_2CELLS_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_2CELLS, 0)
+#define FDT_TEST_VARLEN_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_VARLEN, 0)
+#define FDT_TEST_NONE_NO_SKIP		FDT_TAG_NO_SKIP(FDT_TAG_DATA_NONE, 0)    

...

Quoted 14 lines
Quoted 14 lines

/*
* Tests reserved tags
*
* A TAG_ID range in "structured tags" is reserved to tests tags.
* This tests reserved range is from tag_id 0 to tag_id 0x100.
*
* When those tags are encountered they should be considered as "unknown"
* tags and rules related to "unknown" tags must be followed.
*
* Readers should skip them or fail depending on the SKIP_SAFE flag. Writers
* should never use those tags. Their usage is only acceptable in test cases. */

Quoted 6 lines
Quoted 1 line

Is it ok?

I'd probably put the reserved range up high somewhere rather than starting at 0. Otherwise it looks good.

Ok I will move the reserved range at an higher area and probable the highest possible area.

Will choose also the highest possible value for FDT_TEST_NONE_NO_SKIP Indeed, this one is a non-skippable tag and so should use "old style" tag.

Best regards.
Hervé

#43 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Quoted 31 lines · Herve Codina

Hi David,

On Thu, 10 Sep 2026 19:41:42 +1000
David Gibson <[email protected]> wrote:

...

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
libfdt/fdt.h +6 -0
+/* Tests reserved tags */
+#define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
+#define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
+#define FDT_TEST_2CELLS_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_2CELLS, 0)
+#define FDT_TEST_VARLEN_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_VARLEN, 0)
+#define FDT_TEST_NONE_NO_SKIP		FDT_TAG_NO_SKIP(FDT_TAG_DATA_NONE, 0)    

...

Quoted 16 lines
Quoted 15 lines

/*
* Tests reserved tags
*
* A TAG_ID range in "structured tags" is reserved to tests tags.
* This tests reserved range is from tag_id 0 to tag_id 0x100.
*
* When those tags are encountered they should be considered as "unknown"
* tags and rules related to "unknown" tags must be followed.
*
* Readers should skip them or fail depending on the SKIP_SAFE flag. Writers
* should never use those tags. Their usage is only acceptable in test cases. */

Is it ok?

Quoted 7 lines
Quoted 4 lines

I'd probably put the reserved range up high somewhere rather than starting at 0. Otherwise it looks good.

Ok I will move the reserved range at an higher area and probable the highest possible area.

Sounds good.

Quoted 3 lines

Will choose also the highest possible value for FDT_TEST_NONE_NO_SKIP Indeed, this one is a non-skippable tag and so should use "old style" tag.

With non-skippable new-style tags no longer being a thing, do you even need this tag and test?

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#44 lore raw

Re: [PATCH v3 06/15] Introduce structured tag value definition

Hi David,

Quoted 40 lines · On Sat, 12 Sep 2026 12:35:10 +1000 David Gibson <[email protected]>…
Quoted 31 lines · Herve Codina

Hi David,

On Thu, 10 Sep 2026 19:41:42 +1000
David Gibson <[email protected]> wrote:

...

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
libfdt/fdt.h +6 -0
+/* Tests reserved tags */
+#define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
+#define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
+#define FDT_TEST_2CELLS_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_2CELLS, 0)
+#define FDT_TEST_VARLEN_CAN_SKIP	FDT_TAG_CAN_SKIP(FDT_TAG_DATA_VARLEN, 0)
+#define FDT_TEST_NONE_NO_SKIP		FDT_TAG_NO_SKIP(FDT_TAG_DATA_NONE, 0)      

...

Quoted 16 lines
Quoted 15 lines

/*
* Tests reserved tags
*
* A TAG_ID range in "structured tags" is reserved to tests tags.
* This tests reserved range is from tag_id 0 to tag_id 0x100.
*
* When those tags are encountered they should be considered as "unknown"
* tags and rules related to "unknown" tags must be followed.
*
* Readers should skip them or fail depending on the SKIP_SAFE flag. Writers
* should never use those tags. Their usage is only acceptable in test cases. */

Is it ok?

Quoted 7 lines
Quoted 4 lines

I'd probably put the reserved range up high somewhere rather than starting at 0. Otherwise it looks good.

Ok I will move the reserved range at an higher area and probable the highest possible area.

Quoted 9 lines

Sounds good.

Quoted 3 lines

Will choose also the highest possible value for FDT_TEST_NONE_NO_SKIP Indeed, this one is a non-skippable tag and so should use "old style" tag.

With non-skippable new-style tags no longer being a thing, do you even need this tag and test?

Yes indeed, the test and the FDT_TEST_NONE_NO_SKIP tag can be just removed. I will remove them in the next iteration.

Best regards,
Herve

#45 lore raw

PATCH v3 7/15 fdtdump: Handle unknown tags

In reply to Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

Add support for those structured tags in fdtdump and introduce a command line option to dump unknown tags that should be ignored.

---
 fdtdump.c                              |  45 ++++++-
 tests/Makefile.tests                   |   3 +-
 tests/meson.build                      |   2 +
 tests/run_tests.sh                     |  41 +++++++
 tests/treegen.c                        | 162 +++++++++++++++++++++++++
 tests/unknown_tags_can_skip.dtb.expect |  29 +++++
 6 files changed, 278 insertions(+), 4 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.dtb.expect
fdtdump.c +42 -3
index 0e7a2659..7a8b2784 100644
@@ -44,7 +44,7 @@ static const char *tagname(uint32_t tag)
 #define dumpf(fmt, args...) \
 	do { if (debug) printf("// " fmt, ## args); } while (0)
 
-static void dump_blob(void *blob, bool debug)
+static void dump_blob(void *blob, bool debug, int dump_unknown)
 {
 	uintptr_t blob_off = (uintptr_t)blob;
 	struct fdt_header *bph = blob;
@@ -146,20 +146,55 @@ static void dump_blob(void *blob, bool debug)
 			continue;
 		}
 
+		if ((tag & FDT_TAG_STRUCTURED) && (tag & FDT_TAG_SKIP_SAFE)) {
+			sz = 0;
+			switch (tag & FDT_TAG_DATA_MASK) {
+			case FDT_TAG_DATA_NONE:
+				break;
+			case FDT_TAG_DATA_1CELL:
+				sz = FDT_CELLSIZE;
+				break;
+			case FDT_TAG_DATA_2CELLS:
+				sz = 2 * FDT_CELLSIZE;
+				break;
+			case FDT_TAG_DATA_VARLEN:
+				/* Get the length */
+				sz = fdt32_to_cpu(GET_CELL(p));
+				break;
+			}
+
+			if (dump_unknown) {
+				printf("%*s// Unknown tag ignored: 0x%08"PRIx32", data len %d",
+				       depth * shift, "", tag, sz);
+				if (dump_unknown > 1 && sz != 0) {
+					printf(" ");
+					for (i = 0; i < sz; i++)
+						printf("%02hhx", *(p + i));
+				}
+				printf("\n");
+			}
+
+			/* Skip the data bytes */
+			p = PALIGN(p + sz, 4);
+			continue;
+		}
+
 		die("** Unknown tag 0x%08"PRIx32"\n", tag);
 	}
 }
 
 /* Usage related data. */
 static const char usage_synopsis[] = "fdtdump [options] <file>";
-static const char usage_short_opts[] = "ds" USAGE_COMMON_SHORT_OPTS;
+static const char usage_short_opts[] = "dus" USAGE_COMMON_SHORT_OPTS;
 static struct option const usage_long_opts[] = {
 	{"debug",            no_argument, NULL, 'd'},
+	{"unknown",          no_argument, NULL, 'u'},
 	{"scan",             no_argument, NULL, 's'},
 	USAGE_COMMON_LONG_OPTS
 };
 static const char * const usage_opts_help[] = {
 	"Dump debug information while decoding the file",
+	"Dump unknown tags information while decoding the file (-uu to dump data)",
 	"Scan for an embedded fdt in file",
 	USAGE_COMMON_OPTS_HELP
 };
@@ -183,6 +218,7 @@ int main(int argc, char *argv[])
 	const char *file;
 	char *buf;
 	bool debug = false;
+	int dump_unknown = 0;
 	bool scan = false;
 	size_t len;
 
@@ -198,6 +234,9 @@ int main(int argc, char *argv[])
 		case 'd':
 			debug = true;
 			break;
+		case 'u':
+			dump_unknown++;
+			break;
 		case 's':
 			scan = true;
 			break;
@@ -242,7 +281,7 @@ int main(int argc, char *argv[])
 	} else if (!valid_header(buf, len))
 		die("%s: header is not valid\n", file);
 
-	dump_blob(buf, debug);
+	dump_blob(buf, debug, dump_unknown);
 
 	return 0;
 }
tests/Makefile.tests +2 -1
index af5d309c..63e201ae 100644
@@ -44,7 +44,8 @@ TESTS = $(LIB_TESTS) $(DL_LIB_TESTS)
 TESTS_TREES_L = test_tree1.dtb bad_node_char.dtb bad_node_format.dtb \
 	bad_prop_char.dtb ovf_size_strings.dtb truncated_property.dtb \
 	truncated_string.dtb truncated_memrsv.dtb unterminated_memrsv.dtb \
-	two_roots.dtb named_root.dtb
+	two_roots.dtb named_root.dtb unknown_tags_can_skip.dtb \
+	unknown_tags_no_skip.dtb
 TESTS_TREES = $(TESTS_TREES_L:%=$(TESTS_PREFIX)%)
 
 TESTS_TARGETS = $(TESTS) $(TESTS_TREES)
tests/meson.build +2 -0
index c6ac2d7f..779e6bc7 100644
@@ -17,6 +17,8 @@ treegen_dtb = custom_target(
     'unterminated_memrsv.dtb',
     'two_roots.dtb',
     'named_root.dtb',
+    'unknown_tags_can_skip.dtb',
+    'unknown_tags_no_skip.dtb',
   ]
 )
 
tests/run_tests.sh +41 -0

53 lines not on this page · raw message

tests/treegen.c +162 -0

174 lines not on this page · raw message

tests/unknown_tags_can_skip.dtb.expect new file +29 -0
new file mode 100644
index 00000000..5ad9964e
@@ -0,0 +1,29 @@
+/dts-v1/;
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
Signature · 1 line
2.55.0
#46 lore raw

Re: [PATCH v3 07/15] fdtdump: Handle unknown tags

Quoted 43 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

Add support for those structured tags in fdtdump and introduce a command line option to dump unknown tags that should be ignored.

---
 fdtdump.c                              |  45 ++++++-
 tests/Makefile.tests                   |   3 +-
 tests/meson.build                      |   2 +
 tests/run_tests.sh                     |  41 +++++++
 tests/treegen.c                        | 162 +++++++++++++++++++++++++
 tests/unknown_tags_can_skip.dtb.expect |  29 +++++
 6 files changed, 278 insertions(+), 4 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.dtb.expect
fdtdump.c +9 -1
index 0e7a2659..7a8b2784 100644
@@ -44,7 +44,7 @@ static const char *tagname(uint32_t tag)
 #define dumpf(fmt, args...) \
 	do { if (debug) printf("// " fmt, ## args); } while (0)
 
-static void dump_blob(void *blob, bool debug)
+static void dump_blob(void *blob, bool debug, int dump_unknown)
 {
 	uintptr_t blob_off = (uintptr_t)blob;
 	struct fdt_header *bph = blob;
@@ -146,20 +146,55 @@ static void dump_blob(void *blob, bool debug)
 			continue;
 		}
 
+		if ((tag & FDT_TAG_STRUCTURED) && (tag & FDT_TAG_SKIP_SAFE)) {
+			sz = 0;
+			switch (tag & FDT_TAG_DATA_MASK) {
+			case FDT_TAG_DATA_NONE:
+				break;
+			case FDT_TAG_DATA_1CELL:
+				sz = FDT_CELLSIZE;
+				break;

fdtdump.c static void dump_blob(void *blob, bool debug) · line 166

Quoted 10 lines
fdtdump.c +10 -0
+			case FDT_TAG_DATA_2CELLS:
+				sz = 2 * FDT_CELLSIZE;
+				break;
+			case FDT_TAG_DATA_VARLEN:
+				/* Get the length */
+				sz = fdt32_to_cpu(GET_CELL(p));
+				break;
+			}
+
+			if (dump_unknown) {

I'd do this unconditionally: fdtdump is specifically for low-level and debug dumping of a tree. If you want pretty printing, dtc -Odts is the thing to use.

fdtdump.c static void dump_blob(void *blob, bool debug) · line 168

Quoted 2 lines
fdtdump.c +2 -0
+				printf("%*s// Unknown tag ignored: 0x%08"PRIx32", data len %d",
+				       depth * shift, "", tag, sz);

"Unknown" seems redundant. "ignored" is not really true - you're dumping its contents, which is all that fdtdump could be asked to do with it. So I'd just say:

	// Tag 0x<tag>: <data>

Or maybe "Metadata tag" / "skippable tag" if we go with one of those terms as I suggested on an earlier patch.

The rest of this LGTM, except for things that will need to change based on suggestions about the earlier patches in the series.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#47 lore raw

Re: [PATCH v3 07/15] fdtdump: Handle unknown tags

Quoted 50 lines · On Thu, 10 Sep 2026 15:25:06 +1000 David Gibson <[email protected]>…
Quoted 49 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

Add support for those structured tags in fdtdump and introduce a command line option to dump unknown tags that should be ignored.

---
 fdtdump.c                              |  45 ++++++-
 tests/Makefile.tests                   |   3 +-
 tests/meson.build                      |   2 +
 tests/run_tests.sh                     |  41 +++++++
 tests/treegen.c                        | 162 +++++++++++++++++++++++++
 tests/unknown_tags_can_skip.dtb.expect |  29 +++++
 6 files changed, 278 insertions(+), 4 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.dtb.expect
fdtdump.c +15 -1
index 0e7a2659..7a8b2784 100644
@@ -44,7 +44,7 @@ static const char *tagname(uint32_t tag)
 #define dumpf(fmt, args...) \
 	do { if (debug) printf("// " fmt, ## args); } while (0)
 
-static void dump_blob(void *blob, bool debug)
+static void dump_blob(void *blob, bool debug, int dump_unknown)
 {
 	uintptr_t blob_off = (uintptr_t)blob;
 	struct fdt_header *bph = blob;
@@ -146,20 +146,55 @@ static void dump_blob(void *blob, bool debug)
 			continue;
 		}
 
+		if ((tag & FDT_TAG_STRUCTURED) && (tag & FDT_TAG_SKIP_SAFE)) {
+			sz = 0;
+			switch (tag & FDT_TAG_DATA_MASK) {
+			case FDT_TAG_DATA_NONE:
+				break;
+			case FDT_TAG_DATA_1CELL:
+				sz = FDT_CELLSIZE;
+				break;
+			case FDT_TAG_DATA_2CELLS:
+				sz = 2 * FDT_CELLSIZE;
+				break;
+			case FDT_TAG_DATA_VARLEN:
+				/* Get the length */
+				sz = fdt32_to_cpu(GET_CELL(p));
Quoted 8 lines

fdtdump.c static void dump_blob(void *blob, bool debug) · line 166

Quoted 4 lines
fdtdump.c +4 -0
+				break;
+			}
+
+			if (dump_unknown) {  

I'd do this unconditionally: fdtdump is specifically for low-level and debug dumping of a tree. If you want pretty printing, dtc -Odts is the thing to use.

Ok, will do it unconditionally.

Quoted 8 lines

fdtdump.c static void dump_blob(void *blob, bool debug) · line 168

Quoted 3 lines
fdtdump.c +2 -0
+				printf("%*s// Unknown tag ignored: 0x%08"PRIx32", data len %d",
+				       depth * shift, "", tag, sz);  

"Unknown" seems redundant. "ignored" is not really true - you're dumping its contents, which is all that fdtdump could be asked to do with it. So I'd just say:

Quoted 4 lines
	// Tag 0x<tag>: <data>

Or maybe "Metadata tag" / "skippable tag" if we go with one of those terms as I suggested on an earlier patch.

I am fine with
// Tag 0x<tag>: <data>

I will use that.

Best regards,
Hervé

#48 lore raw

PATCH v3 8/15 flattree: Handle unknown tags

In reply to Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

Handle those structured tag.

---
 flattree.c                                 | 65 ++++++++++++++++++++--
 tests/run_tests.sh                         |  5 ++
 tests/unknown_tags_can_skip.dtb.dts.expect | 19 +++++++
 3 files changed, 84 insertions(+), 5 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.dtb.dts.expect
flattree.c +60 -5
index f3b698c1..88dbfa7e 100644
@@ -579,7 +579,8 @@ static void flat_read_chunk(struct inbuf *inb, void *p, int len)
 	if ((inb->ptr + len) > inb->limit)
 		die("Premature end of data parsing flat device tree\n");
 
-	memcpy(p, inb->ptr, len);
+	if (p)
+		memcpy(p, inb->ptr, len);
 
 	inb->ptr += len;
 }
@@ -604,6 +605,61 @@ static void flat_realign(struct inbuf *inb, int align)
 		die("Premature end of data parsing flat device tree\n");
 }
 
+static bool flat_skip_unknown_tag(struct inbuf *inb, uint32_t tag)
+{
+	uint32_t lng;
+
+	if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+		return false;
+
+	switch (tag & FDT_TAG_DATA_MASK) {
+	case FDT_TAG_DATA_NONE:
+		break;
+
+	case FDT_TAG_DATA_1CELL:
+		flat_read_word(inb);
+		break;
+
+	case FDT_TAG_DATA_2CELLS:
+		flat_read_word(inb);
+		flat_read_word(inb);
+		break;
+
+	case FDT_TAG_DATA_VARLEN:
+		/* Get the length */
+		lng = flat_read_word(inb);
+
+		/* Skip the following length bytes */
+		flat_read_chunk(inb, NULL, lng);
+
+		flat_realign(inb, sizeof(uint32_t));
+		break;
+	}
+
+	return true;
+}
+
+static uint32_t flat_read_tag(struct inbuf *inb)
+{
+	uint32_t tag;
+
+	do {
+		tag = flat_read_word(inb);
+		switch (tag) {
+		case FDT_BEGIN_NODE:
+		case FDT_END_NODE:
+		case FDT_PROP:
+		case FDT_NOP:
+		case FDT_END:
+			return tag;
+		default:
+			break;
+		}
+	} while (flat_skip_unknown_tag(inb, tag));
+
+	die("Cannot skip unknown tag 0x%08x\n", tag);
+}
+
 static const char *flat_read_string(struct inbuf *inb)
 {
 	int len = 0;
@@ -750,7 +806,7 @@ static struct node *unflatten_tree(struct inbuf *dtbuf,
 		struct property *prop;
 		struct node *child;
 
-		val = flat_read_word(dtbuf);
+		val = flat_read_tag(dtbuf);
 		switch (val) {
 		case FDT_PROP:
 			if (node->children)
@@ -905,14 +961,13 @@ struct dt_info *dt_from_blob(const char *fname)
 
 	reservelist = flat_read_mem_reserve(&memresvbuf);
 
-	val = flat_read_word(&dtbuf);
-
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_BEGIN_NODE)
 		die("Device tree blob doesn't begin with FDT_BEGIN_NODE (begins with 0x%08x)\n", val);
 
 	tree = unflatten_tree(&dtbuf, &strbuf, "", flags);
 
-	val = flat_read_word(&dtbuf);
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_END)
 		die("Device tree blob doesn't end with FDT_END\n");
 
tests/run_tests.sh +5 -0
index f3647e63..8fc23cb7 100755
@@ -882,6 +882,11 @@ dtc_tests () {
 
     # Tests for overlay/plugin generation
     dtc_overlay_tests
+
+    # Tests with "unknown tags"
+    run_dtc_test -I dtb -O dts -o unknown_tags_can_skip.dtb.dts unknown_tags_can_skip.dtb
+    base_run_test check_diff unknown_tags_can_skip.dtb.dts "$SRCDIR/unknown_tags_can_skip.dtb.dts.expect"
+    run_wrap_error_test $DTC -I dtb -O dts -o unknown_tags_no_skip.dtb.dts unknown_tags_no_skip.dtb
 }
 
 cmp_tests () {
tests/unknown_tags_can_skip.dtb.dts.expect new file +19 -0
new file mode 100644
index 00000000..2194025b
@@ -0,0 +1,19 @@
+/dts-v1/;
+
+/ {
+	prop-int = <0x3201>;
+	prop-str = "abcd";
+
+	subnode1 {
+		prop-int = <0x6401 0x6402>;
+	};
+
+	subnode2 {
+		prop-int1 = <0x64020 0x64021>;
+		prop-int2 = <0x32022>;
+
+		subsubnode {
+			prop-bool;
+		};
+	};
+};
Signature · 1 line
2.55.0
#49 lore raw

Re: [PATCH v3 08/15] flattree: Handle unknown tags

Quoted 46 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

Handle those structured tag.

---
 flattree.c                                 | 65 ++++++++++++++++++++--
 tests/run_tests.sh                         |  5 ++
 tests/unknown_tags_can_skip.dtb.dts.expect | 19 +++++++
 3 files changed, 84 insertions(+), 5 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.dtb.dts.expect
flattree.c +15 -1
index f3b698c1..88dbfa7e 100644
@@ -579,7 +579,8 @@ static void flat_read_chunk(struct inbuf *inb, void *p, int len)
 	if ((inb->ptr + len) > inb->limit)
 		die("Premature end of data parsing flat device tree\n");
 
-	memcpy(p, inb->ptr, len);
+	if (p)
+		memcpy(p, inb->ptr, len);
 
 	inb->ptr += len;
 }
@@ -604,6 +605,61 @@ static void flat_realign(struct inbuf *inb, int align)
 		die("Premature end of data parsing flat device tree\n");
 }
 
+static bool flat_skip_unknown_tag(struct inbuf *inb, uint32_t tag)
+{
+	uint32_t lng;
+
+	if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+		return false;
+
+	switch (tag & FDT_TAG_DATA_MASK) {
+	case FDT_TAG_DATA_NONE:
+		break;
+
+	case FDT_TAG_DATA_1CELL:
+		flat_read_word(inb);

flattree.c static void flat_realign(struct inbuf *inb, int align) · line 630

Quoted 10 lines
flattree.c +10 -0
+		break;
+
+	case FDT_TAG_DATA_2CELLS:
+		flat_read_word(inb);
+		flat_read_word(inb);
+		break;
+
+	case FDT_TAG_DATA_VARLEN:
+		/* Get the length */
+		lng = flat_read_word(inb);

I think it would be more natural to get the length as a single value, then have a common flat_read_chunk() and flat_realign() to consume it. That's for two reasons:
* Assuming we keep this length encoding, getting the final tag size seems like it would make a useful helper function anyway.
* Using flat_read_word() is misleading - it implies it's integer data where endianness matters. In this case it's not - it's just some bytes we're skipping over, we don't know the internal structure.

Quoted 18 lines
flattree.c +18 -0
+
+		/* Skip the following length bytes */
+		flat_read_chunk(inb, NULL, lng);
+
+		flat_realign(inb, sizeof(uint32_t));
+		break;
+	}
+
+	return true;
+}
+
+static uint32_t flat_read_tag(struct inbuf *inb)
+{
+	uint32_t tag;
+
+	do {
+		tag = flat_read_word(inb);
+		switch (tag) {

flattree.c static void flat_realign(struct inbuf *inb, int align) · line 658

Quoted 10 lines
flattree.c +10 -0
+		case FDT_BEGIN_NODE:
+		case FDT_END_NODE:
+		case FDT_PROP:
+		case FDT_NOP:
+		case FDT_END:
+			return tag;
+		default:
+			break;
+		}
+	} while (flat_skip_unknown_tag(inb, tag));

Having this as a separate function seems odd to me...

flattree.c static struct node *unflatten_tree(struct inbuf *dtbuf, · line 810

Quoted 13 lines
flattree.c +4 -1
+	die("Cannot skip unknown tag 0x%08x\n", tag);
+}
+
 static const char *flat_read_string(struct inbuf *inb)
 {
 	int len = 0;
@@ -750,7 +806,7 @@ static struct node *unflatten_tree(struct inbuf *dtbuf,
 		struct property *prop;
 		struct node *child;
 
-		val = flat_read_word(dtbuf);
+		val = flat_read_tag(dtbuf);
 		switch (val) {

.. rather than having handling unknown tags as part of the default:
case here.

flattree.c struct dt_info *dt_from_blob(const char *fname) · line 966

Quoted 11 lines
flattree.c +1 -2
 		case FDT_PROP:
 			if (node->children)
@@ -905,14 +961,13 @@ struct dt_info *dt_from_blob(const char *fname)
 
 	reservelist = flat_read_mem_reserve(&memresvbuf);
 
-	val = flat_read_word(&dtbuf);
-
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_BEGIN_NODE)
 		die("Device tree blob doesn't begin with FDT_BEGIN_NODE (begins with 0x%08x)\n", val);

Hmm.. doesn't this already need to be fixed to handle NOP tags before the root node? Logically that change would go before this one.

flattree.c struct dt_info *dt_from_blob(const char *fname) · line 972

Quoted 7 lines
flattree.c +1 -1
 	tree = unflatten_tree(&dtbuf, &strbuf, "", flags);
 
-	val = flat_read_word(&dtbuf);
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_END)
 		die("Device tree blob doesn't end with FDT_END\n");

Likewise here for that matter, a NOP should be valid between the last FDT_END_NODE and the FDT_END.

tests/run_tests.sh dtc_tests () { · line 888

Quoted 12 lines
tests/run_tests.sh +4 -0
index f3647e63..8fc23cb7 100755
@@ -882,6 +882,11 @@ dtc_tests () {
 
     # Tests for overlay/plugin generation
     dtc_overlay_tests
+
+    # Tests with "unknown tags"
+    run_dtc_test -I dtb -O dts -o unknown_tags_can_skip.dtb.dts unknown_tags_can_skip.dtb
+    base_run_test check_diff unknown_tags_can_skip.dtb.dts "$SRCDIR/unknown_tags_can_skip.dtb.dts.expect"

It's best to avoid tests based on -O dts output unless we're explicitly checking -O dts behaviour: because there are multiple ways to format property values, the exact output isn't really guaranteed.

What I'd suggest instead is to adjust treegen to generate two dtbs that are identical _except_ for the skippable tag. Then you can use dtc -I dtb -O dtb, and compare the dtc output (which should strip the tag) against the dtb which was constructed without it in the first place.

Or, rather than explicitly creating two new trees, you could make your skippable tag example identical to test_tree1, except for the additional tag, and re-use one of the other instances of test_tree1 as the "tagless" version.

Quoted 33 lines
tests/run_tests.sh +1 -0
+    run_wrap_error_test $DTC -I dtb -O dts -o unknown_tags_no_skip.dtb.dts unknown_tags_no_skip.dtb
 }
 
 cmp_tests () {
tests/unknown_tags_can_skip.dtb.dts.expect new file +19 -0
new file mode 100644
index 00000000..2194025b
@@ -0,0 +1,19 @@
+/dts-v1/;
+
+/ {
+	prop-int = <0x3201>;
+	prop-str = "abcd";
+
+	subnode1 {
+		prop-int = <0x6401 0x6402>;
+	};
+
+	subnode2 {
+		prop-int1 = <0x64020 0x64021>;
+		prop-int2 = <0x32022>;
+
+		subsubnode {
+			prop-bool;
+		};
+	};
+};
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#50 lore raw

Re: [PATCH v3 08/15] flattree: Handle unknown tags

Hi David,

Quoted 58 lines · On Mon, 14 Sep 2026 18:23:49 +1000 David Gibson <[email protected]>…
Quoted 46 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

Handle those structured tag.

---
 flattree.c                                 | 65 ++++++++++++++++++++--
 tests/run_tests.sh                         |  5 ++
 tests/unknown_tags_can_skip.dtb.dts.expect | 19 +++++++
 3 files changed, 84 insertions(+), 5 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.dtb.dts.expect
flattree.c +15 -1
index f3b698c1..88dbfa7e 100644
@@ -579,7 +579,8 @@ static void flat_read_chunk(struct inbuf *inb, void *p, int len)
 	if ((inb->ptr + len) > inb->limit)
 		die("Premature end of data parsing flat device tree\n");
 
-	memcpy(p, inb->ptr, len);
+	if (p)
+		memcpy(p, inb->ptr, len);
 
 	inb->ptr += len;
 }
@@ -604,6 +605,61 @@ static void flat_realign(struct inbuf *inb, int align)
 		die("Premature end of data parsing flat device tree\n");
 }
 
+static bool flat_skip_unknown_tag(struct inbuf *inb, uint32_t tag)
+{
+	uint32_t lng;
+
+	if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+		return false;
+
+	switch (tag & FDT_TAG_DATA_MASK) {
+	case FDT_TAG_DATA_NONE:
+		break;
+
+	case FDT_TAG_DATA_1CELL:
+		flat_read_word(inb);

flattree.c static void flat_realign(struct inbuf *inb, int align) · line 630

Quoted 10 lines
flattree.c +10 -0
+		break;
+
+	case FDT_TAG_DATA_2CELLS:
+		flat_read_word(inb);
+		flat_read_word(inb);
+		break;
+
+	case FDT_TAG_DATA_VARLEN:
+		/* Get the length */
+		lng = flat_read_word(inb);  
Quoted 8 lines

I think it would be more natural to get the length as a single value, then have a common flat_read_chunk() and flat_realign() to consume it. That's for two reasons:
* Assuming we keep this length encoding, getting the final tag size seems like it would make a useful helper function anyway.
* Using flat_read_word() is misleading - it implies it's integer data where endianness matters. In this case it's not - it's just some bytes we're skipping over, we don't know the internal structure.

Well, without the length for all tags (I mean keeping some size encoding in the tag value), we can avoid the flat_read_word().
--- 8< ---

	switch (tag & FDT_TAG_DATA_MASK) {
	case FDT_TAG_DATA_NONE:
		lng = 0;
		break;

	case FDT_TAG_DATA_1CELL:
		lng = sizeof(uint32_t);
		break;

	case FDT_TAG_DATA_2CELLS:
		lng = 2 * sizeof(uint32_t);
		break;

	case FDT_TAG_DATA_VARLEN:
		/* Get the length */
		lng = flat_read_word(inb)
		break;
        }

        if (lng) {
		flat_read_chunk(inb, NULL, lng);
		flat_realign(inb, sizeof(uint32_t));
        }

---- 8< ----

Related to a helper, I have introduced one in the addon series where new tags are present and these new tags are no more "unknown" tags and flat_read_subbuf() has been introduced to parse them. You can see that in the patch 11/74 [0] or directly in the final code [1]

[0] https://lore.kernel.org/devicetree-compiler/[email protected]/
[1] https://github.com/bootlin/dtc/blob/c68038e0ff4cde5de37a21419df8a082032ef994/flattree.c#L1169

I can see to avoid some more code duplication between functions skipping "unknown" tags and function parsing new "known" tags.

Quoted 23 lines
Quoted 23 lines
flattree.c +22 -0
+
+		/* Skip the following length bytes */
+		flat_read_chunk(inb, NULL, lng);
+
+		flat_realign(inb, sizeof(uint32_t));
+		break;
+	}
+
+	return true;
+}
+
+static uint32_t flat_read_tag(struct inbuf *inb)
+{
+	uint32_t tag;
+
+	do {
+		tag = flat_read_word(inb);
+		switch (tag) {
+		case FDT_BEGIN_NODE:
+		case FDT_END_NODE:
+		case FDT_PROP:
+		case FDT_NOP:
Quoted 8 lines

flattree.c static void flat_realign(struct inbuf *inb, int align) · line 658

Quoted 6 lines
flattree.c +6 -0
+		case FDT_END:
+			return tag;
+		default:
+			break;
+		}
+	} while (flat_skip_unknown_tag(inb, tag));  

Having this as a separate function seems odd to me...

Well, this clearly decouples "known" tags from "unknown" tags and keeps the function small.

Quoted 11 lines
Quoted 11 lines
flattree.c +3 -0
+	die("Cannot skip unknown tag 0x%08x\n", tag);
+}
+
 static const char *flat_read_string(struct inbuf *inb)
 {
 	int len = 0;
@@ -750,7 +806,7 @@ static struct node *unflatten_tree(struct inbuf *dtbuf,
 		struct property *prop;
 		struct node *child;
 
Quoted 7 lines

flattree.c static struct node *unflatten_tree(struct inbuf *dtbuf, · line 810

Quoted 3 lines
flattree.c +1 -1
-		val = flat_read_word(dtbuf);
+		val = flat_read_tag(dtbuf);
 		switch (val) {  

.. rather than having handling unknown tags as part of the default:
case here.

Here and probably on some other part if we go in that direction.

Here you have already parsed a FDT_BEGIN_NODE to call unflatten_tree().

Unknown tags should be handle and skipped if possible at lower level to handle them everywhere and without code duplication.

flat_read_tag() is this lower level.

Quoted 7 lines
Quoted 7 lines
flattree.c +0 -0
 		case FDT_PROP:
 			if (node->children)
@@ -905,14 +961,13 @@ struct dt_info *dt_from_blob(const char *fname)
 
 	reservelist = flat_read_mem_reserve(&memresvbuf);
 
Quoted 8 lines

flattree.c struct dt_info *dt_from_blob(const char *fname) · line 966

Quoted 5 lines
flattree.c +1 -2
-	val = flat_read_word(&dtbuf);
-
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_BEGIN_NODE)
 		die("Device tree blob doesn't begin with FDT_BEGIN_NODE (begins with 0x%08x)\n", val);  

Hmm.. doesn't this already need to be fixed to handle NOP tags before the root node? Logically that change would go before this one.

Oh yes, good catch. I missed that one.

Will be update in next iteration (in offset 0 vs real root node offset part) with 2 points:
- handle the case here with something like

    --- 8< ---
       /* Skip possible FDT_NOP available before the root node */
       do {
	  val = flat_read_tag(&dtbuf);
       } while (tag == FDT_NOP);

       if (val != FDT_BEGIN_NODE)
	  die("Device tree blob doesn't begin with FDT_BEGIN_NODE (begins with 0x%08x)\n", val);
       ...
    --- 8< ---

- Add a test calling dtc with a "nopulated" dtb
This test is really missing. Only functions from libfdt are tested with a nopulated dtb. DTC has to be tested too.

Quoted 11 lines

flattree.c struct dt_info *dt_from_blob(const char *fname) · line 972

Quoted 8 lines
flattree.c +1 -1
 	tree = unflatten_tree(&dtbuf, &strbuf, "", flags);
 
-	val = flat_read_word(&dtbuf);
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_END)
 		die("Device tree blob doesn't end with FDT_END\n");  

Likewise here for that matter, a NOP should be valid between the last FDT_END_NODE and the FDT_END.

Yes, exactly and this will be taken into account in the next iteration.

Quoted 7 lines
Quoted 7 lines
tests/run_tests.sh +0 -0
index f3647e63..8fc23cb7 100755
@@ -882,6 +882,11 @@ dtc_tests () {
 
Quoted 10 lines

tests/run_tests.sh dtc_tests () { · line 888

Quoted 6 lines
tests/run_tests.sh +4 -0
     # Tests for overlay/plugin generation
     dtc_overlay_tests
+
+    # Tests with "unknown tags"
+    run_dtc_test -I dtb -O dts -o unknown_tags_can_skip.dtb.dts unknown_tags_can_skip.dtb
+    base_run_test check_diff unknown_tags_can_skip.dtb.dts "$SRCDIR/unknown_tags_can_skip.dtb.dts.expect"  

It's best to avoid tests based on -O dts output unless we're explicitly checking -O dts behaviour: because there are multiple ways to format property values, the exact output isn't really guaranteed.

But at a give version dtc and a given dtb file, there is only one way to generate a dts.

If it change because of some modification in dtc, having some changes in tests expected value should not be a big deal.

Quoted 11 lines

What I'd suggest instead is to adjust treegen to generate two dtbs that are identical _except_ for the skippable tag. Then you can use dtc -I dtb -O dtb, and compare the dtc output (which should strip the tag) against the dtb which was constructed without it in the first place.

Or, rather than explicitly creating two new trees, you could make your skippable tag example identical to test_tree1, except for the additional tag, and re-use one of the other instances of test_tree1 as the "tagless" version.

Why not just one dtb generated to treegen with unknown tags (already available unknown_tags_can_skip.dtb)

dtc -I dtb -O dtb -o unknown_tags_can_skip.dtb.dtb unknown_tags_can_skip.dtb

And then
base_run_test wrap_fdtdump unknown_tags_can_skip.dtb.dtb unknown_tags_can_skip.dtb.dtb.out # Remove unneeded comments
sed -i '/^\/\/ [^U]/d' unknown_tags_can_skip.dtb.out
base_run_test check_diff unknown_tags_can_skip.dtb.dtb.out "$SRCDIR/unknown_tags_can_skip.dtb.expect"

This avoid the need for 2 dtbs generated by treegen and also avoid to compare binary files which are difficult to analyze when the comparison detects a problem due to something broken by some modifications.

Quoted 27 lines
Quoted 27 lines
tests/run_tests.sh +1 -0
+    run_wrap_error_test $DTC -I dtb -O dts -o unknown_tags_no_skip.dtb.dts unknown_tags_no_skip.dtb
 }
 
 cmp_tests () {
tests/unknown_tags_can_skip.dtb.dts.expect new file +15 -0
new file mode 100644
index 00000000..2194025b
@@ -0,0 +1,19 @@
+/dts-v1/;
+
+/ {
+	prop-int = <0x3201>;
+	prop-str = "abcd";
+
+	subnode1 {
+		prop-int = <0x6401 0x6402>;
+	};
+
+	subnode2 {
+		prop-int1 = <0x64020 0x64021>;
+		prop-int2 = <0x32022>;
+
+		subsubnode {
Quoted 9 lines
Quoted 8 lines
tests/unknown_tags_can_skip.dtb.dts.expect new file +4 -0
+			prop-bool;
+		};
+	};
+};
Signature · 1 line
2.55.0

Best regards,
Hervé

#51 lore raw

Re: [PATCH v3 08/15] flattree: Handle unknown tags

Quoted 98 lines · Herve Codina

Hi David,

Quoted 58 lines · On Mon, 14 Sep 2026 18:23:49 +1000 David Gibson <[email protected]>…
Quoted 46 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

Handle those structured tag.

---
 flattree.c                                 | 65 ++++++++++++++++++++--
 tests/run_tests.sh                         |  5 ++
 tests/unknown_tags_can_skip.dtb.dts.expect | 19 +++++++
 3 files changed, 84 insertions(+), 5 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.dtb.dts.expect
flattree.c +15 -1
index f3b698c1..88dbfa7e 100644
@@ -579,7 +579,8 @@ static void flat_read_chunk(struct inbuf *inb, void *p, int len)
 	if ((inb->ptr + len) > inb->limit)
 		die("Premature end of data parsing flat device tree\n");
 
-	memcpy(p, inb->ptr, len);
+	if (p)
+		memcpy(p, inb->ptr, len);
 
 	inb->ptr += len;
 }
@@ -604,6 +605,61 @@ static void flat_realign(struct inbuf *inb, int align)
 		die("Premature end of data parsing flat device tree\n");
 }
 
+static bool flat_skip_unknown_tag(struct inbuf *inb, uint32_t tag)
+{
+	uint32_t lng;
+
+	if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+		return false;
+
+	switch (tag & FDT_TAG_DATA_MASK) {
+	case FDT_TAG_DATA_NONE:
+		break;
+
+	case FDT_TAG_DATA_1CELL:
+		flat_read_word(inb);

flattree.c static void flat_realign(struct inbuf *inb, int align) · line 630

Quoted 10 lines
flattree.c +10 -0
+		break;
+
+	case FDT_TAG_DATA_2CELLS:
+		flat_read_word(inb);
+		flat_read_word(inb);
+		break;
+
+	case FDT_TAG_DATA_VARLEN:
+		/* Get the length */
+		lng = flat_read_word(inb);  
Quoted 8 lines

I think it would be more natural to get the length as a single value, then have a common flat_read_chunk() and flat_realign() to consume it. That's for two reasons:
* Assuming we keep this length encoding, getting the final tag size seems like it would make a useful helper function anyway.
* Using flat_read_word() is misleading - it implies it's integer data where endianness matters. In this case it's not - it's just some bytes we're skipping over, we don't know the internal structure.

Well, without the length for all tags (I mean keeping some size encoding in the tag value), we can avoid the flat_read_word().
--- 8< ---

	switch (tag & FDT_TAG_DATA_MASK) {
	case FDT_TAG_DATA_NONE:
		lng = 0;
		break;

	case FDT_TAG_DATA_1CELL:
		lng = sizeof(uint32_t);
		break;

	case FDT_TAG_DATA_2CELLS:
		lng = 2 * sizeof(uint32_t);
		break;

	case FDT_TAG_DATA_VARLEN:
		/* Get the length */
		lng = flat_read_word(inb)
		break;
        }

        if (lng) {
		flat_read_chunk(inb, NULL, lng);
		flat_realign(inb, sizeof(uint32_t));
        }
Quoted 1 line

---- 8< ----

Right, that's exactly what I'm suggesting.

Quoted 10 lines

Related to a helper, I have introduced one in the addon series where new tags are present and these new tags are no more "unknown" tags and flat_read_subbuf() has been introduced to parse them. You can see that in the patch 11/74 [0] or directly in the final code [1]

[0] https://lore.kernel.org/devicetree-compiler/[email protected]/
[1] https://github.com/bootlin/dtc/blob/c68038e0ff4cde5de37a21419df8a082032ef994/flattree.c#L1169

I can see to avoid some more code duplication between functions skipping "unknown" tags and function parsing new "known" tags.

Uh.. I don't quite see the relevance of that here. I'm just suggesting the length calculation alone be a helper function.

Quoted 94 lines
Quoted 22 lines
Quoted 22 lines
flattree.c +22 -0
+
+		/* Skip the following length bytes */
+		flat_read_chunk(inb, NULL, lng);
+
+		flat_realign(inb, sizeof(uint32_t));
+		break;
+	}
+
+	return true;
+}
+
+static uint32_t flat_read_tag(struct inbuf *inb)
+{
+	uint32_t tag;
+
+	do {
+		tag = flat_read_word(inb);
+		switch (tag) {
+		case FDT_BEGIN_NODE:
+		case FDT_END_NODE:
+		case FDT_PROP:
+		case FDT_NOP:
Quoted 8 lines

flattree.c static void flat_realign(struct inbuf *inb, int align) · line 658

Quoted 6 lines
flattree.c +6 -0
+		case FDT_END:
+			return tag;
+		default:
+			break;
+		}
+	} while (flat_skip_unknown_tag(inb, tag));  

Having this as a separate function seems odd to me...

Well, this clearly decouples "known" tags from "unknown" tags and keeps the function small.

Quoted 11 lines
Quoted 11 lines
flattree.c +3 -0
+	die("Cannot skip unknown tag 0x%08x\n", tag);
+}
+
 static const char *flat_read_string(struct inbuf *inb)
 {
 	int len = 0;
@@ -750,7 +806,7 @@ static struct node *unflatten_tree(struct inbuf *dtbuf,
 		struct property *prop;
 		struct node *child;
 
Quoted 7 lines

flattree.c static struct node *unflatten_tree(struct inbuf *dtbuf, · line 810

Quoted 3 lines
flattree.c +1 -1
-		val = flat_read_word(dtbuf);
+		val = flat_read_tag(dtbuf);
 		switch (val) {  

.. rather than having handling unknown tags as part of the default:
case here.

Here and probably on some other part if we go in that direction.

Here you have already parsed a FDT_BEGIN_NODE to call unflatten_tree().

Unknown tags should be handle and skipped if possible at lower level to handle them everywhere and without code duplication.

flat_read_tag() is this lower level.

Quoted 7 lines
Quoted 7 lines
flattree.c +0 -0
 		case FDT_PROP:
 			if (node->children)
@@ -905,14 +961,13 @@ struct dt_info *dt_from_blob(const char *fname)
 
 	reservelist = flat_read_mem_reserve(&memresvbuf);
 
Quoted 8 lines

flattree.c struct dt_info *dt_from_blob(const char *fname) · line 966

Quoted 5 lines
flattree.c +1 -2
-	val = flat_read_word(&dtbuf);
-
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_BEGIN_NODE)
 		die("Device tree blob doesn't begin with FDT_BEGIN_NODE (begins with 0x%08x)\n", val);  

Hmm.. doesn't this already need to be fixed to handle NOP tags before the root node? Logically that change would go before this one.

Oh yes, good catch. I missed that one.

Will be update in next iteration (in offset 0 vs real root node offset part) with 2 points:
- handle the case here with something like

    --- 8< ---
       /* Skip possible FDT_NOP available before the root node */
       do {
	  val = flat_read_tag(&dtbuf);
       } while (tag == FDT_NOP);

       if (val != FDT_BEGIN_NODE)
	  die("Device tree blob doesn't begin with FDT_BEGIN_NODE (begins with 0x%08x)\n", val);
       ...
    --- 8< ---
Quoted 3 lines

- Add a test calling dtc with a "nopulated" dtb
This test is really missing. Only functions from libfdt are tested with a nopulated dtb. DTC has to be tested too.

Sounds good.

Quoted 12 lines
Quoted 11 lines

flattree.c struct dt_info *dt_from_blob(const char *fname) · line 972

Quoted 8 lines
flattree.c +1 -1
 	tree = unflatten_tree(&dtbuf, &strbuf, "", flags);
 
-	val = flat_read_word(&dtbuf);
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_END)
 		die("Device tree blob doesn't end with FDT_END\n");  

Likewise here for that matter, a NOP should be valid between the last FDT_END_NODE and the FDT_END.

Quoted 1 line

Yes, exactly and this will be taken into account in the next iteration.

Great.

Quoted 17 lines
Quoted 6 lines
Quoted 6 lines
tests/run_tests.sh +0 -0
index f3647e63..8fc23cb7 100755
@@ -882,6 +882,11 @@ dtc_tests () {
 
Quoted 10 lines

tests/run_tests.sh dtc_tests () { · line 888

Quoted 6 lines
tests/run_tests.sh +4 -0
     # Tests for overlay/plugin generation
     dtc_overlay_tests
+
+    # Tests with "unknown tags"
+    run_dtc_test -I dtb -O dts -o unknown_tags_can_skip.dtb.dts unknown_tags_can_skip.dtb
+    base_run_test check_diff unknown_tags_can_skip.dtb.dts "$SRCDIR/unknown_tags_can_skip.dtb.dts.expect"  

It's best to avoid tests based on -O dts output unless we're explicitly checking -O dts behaviour: because there are multiple ways to format property values, the exact output isn't really guaranteed.

Quoted 2 lines

But at a give version dtc and a given dtb file, there is only one way to generate a dts.

Yes, but if we tweak our -Odts formatting decisions, we don't want to have to churn tests that aren't specifically related to -Odts.

Quoted 2 lines

If it change because of some modification in dtc, having some changes in tests expected value should not be a big deal.

It's not a huge deal, but it's still preferable to avoid.

Quoted 14 lines
Quoted 10 lines

What I'd suggest instead is to adjust treegen to generate two dtbs that are identical _except_ for the skippable tag. Then you can use dtc -I dtb -O dtb, and compare the dtc output (which should strip the tag) against the dtb which was constructed without it in the first place.

Or, rather than explicitly creating two new trees, you could make your skippable tag example identical to test_tree1, except for the additional tag, and re-use one of the other instances of test_tree1 as the "tagless" version.

Why not just one dtb generated to treegen with unknown tags (already available unknown_tags_can_skip.dtb)

Quoted 7 lines

dtc -I dtb -O dtb -o unknown_tags_can_skip.dtb.dtb unknown_tags_can_skip.dtb

And then
base_run_test wrap_fdtdump unknown_tags_can_skip.dtb.dtb unknown_tags_can_skip.dtb.dtb.out # Remove unneeded comments
sed -i '/^\/\/ [^U]/d' unknown_tags_can_skip.dtb.out
base_run_test check_diff unknown_tags_can_skip.dtb.dtb.out "$SRCDIR/unknown_tags_can_skip.dtb.expect"

I don't like it - the output formatting of fdtdump is even less guaranteed than -Odts.

Quoted 3 lines

This avoid the need for 2 dtbs generated by treegen and also avoid to compare binary files which are difficult to analyze when the comparison detects a problem due to something broken by some modifications.

We _want_ to understand and test things at the binary byte level. Debugging differences is a little trickier, but it's really not that bad - -Odts or fdtdump or dtdiff can be used if/when there's a test failure. I really think doing the comparison in binary is preferable
- that's the level at which the behaviour is specified and should be tested.

Quoted 38 lines
Quoted 25 lines
Quoted 25 lines
tests/run_tests.sh +1 -0
+    run_wrap_error_test $DTC -I dtb -O dts -o unknown_tags_no_skip.dtb.dts unknown_tags_no_skip.dtb
 }
 
 cmp_tests () {
tests/unknown_tags_can_skip.dtb.dts.expect new file +15 -0
new file mode 100644
index 00000000..2194025b
@@ -0,0 +1,19 @@
+/dts-v1/;
+
+/ {
+	prop-int = <0x3201>;
+	prop-str = "abcd";
+
+	subnode1 {
+		prop-int = <0x6401 0x6402>;
+	};
+
+	subnode2 {
+		prop-int1 = <0x64020 0x64021>;
+		prop-int2 = <0x32022>;
+
+		subsubnode {
Quoted 9 lines
Quoted 8 lines
tests/unknown_tags_can_skip.dtb.dts.expect new file +4 -0
+			prop-bool;
+		};
+	};
+};
Signature · 1 line
2.55.0

Best regards,
Hervé

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#52 lore raw

Re: [PATCH v3 08/15] flattree: Handle unknown tags

Hi David,

Quoted 108 lines · On Tue, 15 Sep 2026 21:52:24 +1000 David Gibson <[email protected]>…
Quoted 98 lines · Herve Codina

Hi David,

Quoted 58 lines · On Mon, 14 Sep 2026 18:23:49 +1000 David Gibson <[email protected]>…
Quoted 46 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

Handle those structured tag.

---
 flattree.c                                 | 65 ++++++++++++++++++++--
 tests/run_tests.sh                         |  5 ++
 tests/unknown_tags_can_skip.dtb.dts.expect | 19 +++++++
 3 files changed, 84 insertions(+), 5 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.dtb.dts.expect
flattree.c +15 -1
index f3b698c1..88dbfa7e 100644
@@ -579,7 +579,8 @@ static void flat_read_chunk(struct inbuf *inb, void *p, int len)
 	if ((inb->ptr + len) > inb->limit)
 		die("Premature end of data parsing flat device tree\n");
 
-	memcpy(p, inb->ptr, len);
+	if (p)
+		memcpy(p, inb->ptr, len);
 
 	inb->ptr += len;
 }
@@ -604,6 +605,61 @@ static void flat_realign(struct inbuf *inb, int align)
 		die("Premature end of data parsing flat device tree\n");
 }
 
+static bool flat_skip_unknown_tag(struct inbuf *inb, uint32_t tag)
+{
+	uint32_t lng;
+
+	if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+		return false;
+
+	switch (tag & FDT_TAG_DATA_MASK) {
+	case FDT_TAG_DATA_NONE:
+		break;
+
+	case FDT_TAG_DATA_1CELL:
+		flat_read_word(inb);

flattree.c static void flat_realign(struct inbuf *inb, int align) · line 630

Quoted 10 lines
flattree.c +10 -0
+		break;
+
+	case FDT_TAG_DATA_2CELLS:
+		flat_read_word(inb);
+		flat_read_word(inb);
+		break;
+
+	case FDT_TAG_DATA_VARLEN:
+		/* Get the length */
+		lng = flat_read_word(inb);    
Quoted 8 lines

I think it would be more natural to get the length as a single value, then have a common flat_read_chunk() and flat_realign() to consume it. That's for two reasons:
* Assuming we keep this length encoding, getting the final tag size seems like it would make a useful helper function anyway.
* Using flat_read_word() is misleading - it implies it's integer data where endianness matters. In this case it's not - it's just some bytes we're skipping over, we don't know the internal structure.

Well, without the length for all tags (I mean keeping some size encoding in the tag value), we can avoid the flat_read_word().
--- 8< ---

	switch (tag & FDT_TAG_DATA_MASK) {
	case FDT_TAG_DATA_NONE:
		lng = 0;
		break;

	case FDT_TAG_DATA_1CELL:
		lng = sizeof(uint32_t);
		break;

	case FDT_TAG_DATA_2CELLS:
		lng = 2 * sizeof(uint32_t);
		break;

	case FDT_TAG_DATA_VARLEN:
		/* Get the length */
		lng = flat_read_word(inb)
		break;
        }

        if (lng) {
		flat_read_chunk(inb, NULL, lng);
		flat_realign(inb, sizeof(uint32_t));
        }
Quoted 1 line

---- 8< ----

Right, that's exactly what I'm suggesting.

Quoted 5 lines

Related to a helper, I have introduced one in the addon series where new tags are present and these new tags are no more "unknown" tags and flat_read_subbuf() has been introduced to parse them. You can see that in the patch 11/74 [0] or directly in the final code [1]

Quoted 9 lines
Quoted 5 lines

[0] https://lore.kernel.org/devicetree-compiler/[email protected]/
[1] https://github.com/bootlin/dtc/blob/c68038e0ff4cde5de37a21419df8a082032ef994/flattree.c#L1169

I can see to avoid some more code duplication between functions skipping "unknown" tags and function parsing new "known" tags.

Uh.. I don't quite see the relevance of that here. I'm just suggesting the length calculation alone be a helper function.

Ah, okay, I'll introduce and use this small length calculation helper.

Quoted 95 lines
Quoted 95 lines
Quoted 23 lines
Quoted 23 lines
flattree.c +22 -0
+
+		/* Skip the following length bytes */
+		flat_read_chunk(inb, NULL, lng);
+
+		flat_realign(inb, sizeof(uint32_t));
+		break;
+	}
+
+	return true;
+}
+
+static uint32_t flat_read_tag(struct inbuf *inb)
+{
+	uint32_t tag;
+
+	do {
+		tag = flat_read_word(inb);
+		switch (tag) {
+		case FDT_BEGIN_NODE:
+		case FDT_END_NODE:
+		case FDT_PROP:
+		case FDT_NOP:
Quoted 8 lines

flattree.c static void flat_realign(struct inbuf *inb, int align) · line 658

Quoted 6 lines
flattree.c +6 -0
+		case FDT_END:
+			return tag;
+		default:
+			break;
+		}
+	} while (flat_skip_unknown_tag(inb, tag));    

Having this as a separate function seems odd to me...

Well, this clearly decouples "known" tags from "unknown" tags and keeps the function small.

Quoted 11 lines
Quoted 11 lines
flattree.c +3 -0
+	die("Cannot skip unknown tag 0x%08x\n", tag);
+}
+
 static const char *flat_read_string(struct inbuf *inb)
 {
 	int len = 0;
@@ -750,7 +806,7 @@ static struct node *unflatten_tree(struct inbuf *dtbuf,
 		struct property *prop;
 		struct node *child;
 
Quoted 7 lines

flattree.c static struct node *unflatten_tree(struct inbuf *dtbuf, · line 810

Quoted 3 lines
flattree.c +1 -1
-		val = flat_read_word(dtbuf);
+		val = flat_read_tag(dtbuf);
 		switch (val) {    

.. rather than having handling unknown tags as part of the default:
case here.

Here and probably on some other part if we go in that direction.

Here you have already parsed a FDT_BEGIN_NODE to call unflatten_tree().

Unknown tags should be handle and skipped if possible at lower level to handle them everywhere and without code duplication.

flat_read_tag() is this lower level.

Quoted 7 lines
Quoted 7 lines
flattree.c +0 -0
 		case FDT_PROP:
 			if (node->children)
@@ -905,14 +961,13 @@ struct dt_info *dt_from_blob(const char *fname)
 
 	reservelist = flat_read_mem_reserve(&memresvbuf);
 
Quoted 8 lines

flattree.c struct dt_info *dt_from_blob(const char *fname) · line 966

Quoted 5 lines
flattree.c +1 -2
-	val = flat_read_word(&dtbuf);
-
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_BEGIN_NODE)
 		die("Device tree blob doesn't begin with FDT_BEGIN_NODE (begins with 0x%08x)\n", val);    

Hmm.. doesn't this already need to be fixed to handle NOP tags before the root node? Logically that change would go before this one.

Oh yes, good catch. I missed that one.

Will be update in next iteration (in offset 0 vs real root node offset part) with 2 points:
- handle the case here with something like

    --- 8< ---
       /* Skip possible FDT_NOP available before the root node */
       do {
	  val = flat_read_tag(&dtbuf);
       } while (tag == FDT_NOP);

       if (val != FDT_BEGIN_NODE)
	  die("Device tree blob doesn't begin with FDT_BEGIN_NODE (begins with 0x%08x)\n", val);
       ...
    --- 8< ---
Quoted 5 lines
Quoted 3 lines

- Add a test calling dtc with a "nopulated" dtb
This test is really missing. Only functions from libfdt are tested with a nopulated dtb. DTC has to be tested too.

Sounds good.

Perfect.

Quoted 74 lines
Quoted 13 lines
Quoted 5 lines
Quoted 5 lines
flattree.c +0 -0
 	tree = unflatten_tree(&dtbuf, &strbuf, "", flags);
 
Quoted 7 lines

flattree.c struct dt_info *dt_from_blob(const char *fname) · line 972

Quoted 4 lines
flattree.c +1 -1
-	val = flat_read_word(&dtbuf);
+	val = flat_read_tag(&dtbuf);
 	if (val != FDT_END)
 		die("Device tree blob doesn't end with FDT_END\n");    

Likewise here for that matter, a NOP should be valid between the last FDT_END_NODE and the FDT_END.

Quoted 1 line

Yes, exactly and this will be taken into account in the next iteration.

Great.

Quoted 17 lines
Quoted 6 lines
Quoted 6 lines
tests/run_tests.sh +0 -0
index f3647e63..8fc23cb7 100755
@@ -882,6 +882,11 @@ dtc_tests () {
 
Quoted 10 lines

tests/run_tests.sh dtc_tests () { · line 888

Quoted 6 lines
tests/run_tests.sh +4 -0
     # Tests for overlay/plugin generation
     dtc_overlay_tests
+
+    # Tests with "unknown tags"
+    run_dtc_test -I dtb -O dts -o unknown_tags_can_skip.dtb.dts unknown_tags_can_skip.dtb
+    base_run_test check_diff unknown_tags_can_skip.dtb.dts "$SRCDIR/unknown_tags_can_skip.dtb.dts.expect"    

It's best to avoid tests based on -O dts output unless we're explicitly checking -O dts behaviour: because there are multiple ways to format property values, the exact output isn't really guaranteed.

Quoted 2 lines

But at a give version dtc and a given dtb file, there is only one way to generate a dts.

Yes, but if we tweak our -Odts formatting decisions, we don't want to have to churn tests that aren't specifically related to -Odts.

Quoted 2 lines

If it change because of some modification in dtc, having some changes in tests expected value should not be a big deal.

It's not a huge deal, but it's still preferable to avoid.

Quoted 14 lines
Quoted 10 lines

What I'd suggest instead is to adjust treegen to generate two dtbs that are identical _except_ for the skippable tag. Then you can use dtc -I dtb -O dtb, and compare the dtc output (which should strip the tag) against the dtb which was constructed without it in the first place.

Or, rather than explicitly creating two new trees, you could make your skippable tag example identical to test_tree1, except for the additional tag, and re-use one of the other instances of test_tree1 as the "tagless" version.

Why not just one dtb generated to treegen with unknown tags (already available unknown_tags_can_skip.dtb)

Quoted 7 lines

dtc -I dtb -O dtb -o unknown_tags_can_skip.dtb.dtb unknown_tags_can_skip.dtb

And then
base_run_test wrap_fdtdump unknown_tags_can_skip.dtb.dtb unknown_tags_can_skip.dtb.dtb.out # Remove unneeded comments
sed -i '/^\/\/ [^U]/d' unknown_tags_can_skip.dtb.out
base_run_test check_diff unknown_tags_can_skip.dtb.dtb.out "$SRCDIR/unknown_tags_can_skip.dtb.expect"

I don't like it - the output formatting of fdtdump is even less guaranteed than -Odts.

Quoted 3 lines

This avoid the need for 2 dtbs generated by treegen and also avoid to compare binary files which are difficult to analyze when the comparison detects a problem due to something broken by some modifications.

Quoted 6 lines

We _want_ to understand and test things at the binary byte level. Debugging differences is a little trickier, but it's really not that bad - -Odts or fdtdump or dtdiff can be used if/when there's a test failure. I really think doing the comparison in binary is preferable
- that's the level at which the behaviour is specified and should be tested.

Right, will see what I can do. Probably generating using two specific dtbs as suggested in your first proposal.

Worth noting that each time a dtb will change due to, for instance, a new dtb version (or any other header field update), this test will need to be updated. DTC will generate the dtb with new headers value.

Best regards,
Hervé

#53 lore raw

Re: [PATCH v3 08/15] flattree: Handle unknown tags

Quoted 4 lines · Herve Codina

Hi David,

On Tue, 15 Sep 2026 21:52:24 +1000
David Gibson <[email protected]> wrote:

[snip]

Quoted 11 lines
Quoted 10 lines
Quoted 3 lines

This avoid the need for 2 dtbs generated by treegen and also avoid to compare binary files which are difficult to analyze when the comparison detects a problem due to something broken by some modifications.

We _want_ to understand and test things at the binary byte level. Debugging differences is a little trickier, but it's really not that bad - -Odts or fdtdump or dtdiff can be used if/when there's a test failure. I really think doing the comparison in binary is preferable
- that's the level at which the behaviour is specified and should be tested.

Quoted 6 lines

Right, will see what I can do. Probably generating using two specific dtbs as suggested in your first proposal.

Worth noting that each time a dtb will change due to, for instance, a new dtb version (or any other header field update), this test will need to be updated. DTC will generate the dtb with new headers value.

If you use the default call for the header in treegen, which always uses the latest version, then it should be fine.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#54 lore raw

Re: [PATCH v3 08/15] flattree: Handle unknown tags

Quoted 20 lines · On Wed, 16 Sep 2026 18:27:53 +1000 David Gibson <[email protected]>…
Quoted 4 lines · Herve Codina

Hi David,

On Tue, 15 Sep 2026 21:52:24 +1000
David Gibson <[email protected]> wrote:

[snip]

Quoted 14 lines
Quoted 10 lines
Quoted 3 lines

This avoid the need for 2 dtbs generated by treegen and also avoid to compare binary files which are difficult to analyze when the comparison detects a problem due to something broken by some modifications.

We _want_ to understand and test things at the binary byte level. Debugging differences is a little trickier, but it's really not that bad - -Odts or fdtdump or dtdiff can be used if/when there's a test failure. I really think doing the comparison in binary is preferable
- that's the level at which the behaviour is specified and should be tested.

Right, will see what I can do. Probably generating using two specific dtbs as suggested in your first proposal.

Quoted 7 lines
Quoted 3 lines

Worth noting that each time a dtb will change due to, for instance, a new dtb version (or any other header field update), this test will need to be updated. DTC will generate the dtb with new headers value.

If you use the default call for the header in treegen, which always uses the latest version, then it should be fine.

Yes indeed. Will give a try.

Best regards,
Hervé

#55 lore raw

PATCH v3 9/15 libfdt: Handle unknown tags in fdt_next_tag()

In reply to Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

libfdt uses fdt_next_tag() to get a tag.

Filtering out tags that should be ignored in fdt_next_tag() allows to have the filtering done globally and allows, in future releases, to have a central place to add new known tags that should not be filtered out.

An already known tag exists with the meaning of "just ignore". This tag is FDT_NOP. fdt_next_tag() callers already handle the FDT_NOP tag.

Avoid unneeded modification at callers side and use a fake FDT_NOP tag when an unknown tag that should be ignored is encountered.

Add also fdt_next_tag_() internal function for callers who need to know if the FDT_NOP tag returned is a real FDT_NOP or a fake FDT_NOP due to an unknown tag.

---
 libfdt/fdt.c             | 75 ++++++++++++++++++++++++++++++++++++++--
 libfdt/libfdt_internal.h |  3 ++
 tests/run_tests.sh       |  9 +++--
 3 files changed, 83 insertions(+), 4 deletions(-)
libfdt/fdt.c +73 -2
index eb803e8a..506e0dd3 100644
@@ -167,7 +167,7 @@ const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int len)
 	return fdt_offset_ptr_(fdt, offset);
 }
 
-uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
+static uint32_t fdt_next_tag_all(const void *fdt, int startoffset, int *nextoffset)
 {
 	const fdt32_t *tagp, *lenp;
 	uint32_t tag, len, sum;
@@ -218,7 +218,37 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 		break;
 
 	default:
-		return FDT_END;
+		if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+			return FDT_END;
+
+		switch (tag & FDT_TAG_DATA_MASK) {
+		case FDT_TAG_DATA_NONE:
+			break;
+		case FDT_TAG_DATA_1CELL:
+			offset += FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_2CELLS:
+			offset += 2 * FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_VARLEN:
+			/* Get the length */
+			lenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp));
+			if (!can_assume(VALID_DTB) && !lenp)
+				return FDT_END; /* premature end */
+			len = fdt32_to_cpu(*lenp);
+			/*
+			 * Skip the cell encoding the length and the
+			 * following length bytes
+			 */
+			len += sizeof(*lenp);
+			sum = len + offset;
+			if (!can_assume(VALID_DTB) &&
+			    (sum >= INT_MAX || sum < (uint32_t) offset))
+				return FDT_END; /* premature end */
+
+			offset += len;
+			break;
+		}
 	}
 
 	if (!fdt_offset_ptr(fdt, startoffset, offset - startoffset))
@@ -228,6 +258,47 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 	return tag;
 }
 
+static bool fdt_tag_is_unknown(uint32_t tag)
+{
+	switch (tag) {
+	case FDT_BEGIN_NODE:
+	case FDT_END_NODE:
+	case FDT_PROP:
+	case FDT_NOP:
+	case FDT_END:
+		return false;
+	default:
+		break;
+	}
+	return true;
+}
+
+uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset, bool *is_unknown)
+{
+	uint32_t tag;
+	bool unknown = false;
+
+	/* Retrieve next tag */
+	tag = fdt_next_tag_all(fdt, startoffset, nextoffset);
+	if (tag == FDT_END)
+		goto end;
+
+	if (fdt_tag_is_unknown(tag)) {
+		unknown = true;
+		/* Use a known tag that should be skipped by the caller */
+		tag = FDT_NOP;
+	}
+end:
+	if (is_unknown)
+		*is_unknown = unknown;
+	return tag;
+}
+
+uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
+{
+	return fdt_next_tag_(fdt, startoffset, nextoffset, NULL);
+}
+
 int fdt_check_node_offset_(const void *fdt, int offset)
 {
 	if (!can_assume(VALID_INPUT)
libfdt/libfdt_internal.h +3 -0
index 0e103caf..f2e30ce8 100644
@@ -20,6 +20,9 @@ int32_t fdt_ro_probe_(const void *fdt);
 		}							\
 	}
 
+uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset,
+		       bool *is_unknown);
+
 int fdt_check_node_offset_(const void *fdt, int offset);
 int fdt_check_prop_offset_(const void *fdt, int offset);
 
tests/run_tests.sh +7 -2
index 8fc23cb7..225c22f8 100755
@@ -577,11 +577,12 @@ libfdt_tests () {
     run_test dtbs_equal_ordered cell-overflow.test.dtb cell-overflow-results.test.dtb
 
     # check full tests
-    for good in test_tree1.dtb; do
+    for good in test_tree1.dtb unknown_tags_can_skip.dtb; do
 	run_test check_full $good
     done
     for bad in truncated_property.dtb truncated_string.dtb \
-		truncated_memrsv.dtb two_roots.dtb named_root.dtb; do
+		truncated_memrsv.dtb two_roots.dtb named_root.dtb \
+		unknown_tags_no_skip.dtb; do
 	run_test check_full -n $bad
     done
 }
@@ -962,6 +963,10 @@ fdtget_tests () {
     run_fdtget_test "<the dead silence>" -tx \
 	-d "<the dead silence>" $dtb /randomnode doctor-who
     run_fdtget_test "<blink>" -tx -d "<blink>" $dtb /memory doctor-who
+
+    # test with unknown tags involved
+    run_fdtget_test "25601 25602" unknown_tags_can_skip.dtb /subnode1 prop-int
+    run_wrap_error_test $DTGET unknown_tags_no_skip.dtb /subnode1 prop-int
 }
 
 fdtput_tests () {
Signature · 1 line
2.55.0
#56 lore raw

Re: [PATCH v3 09/15] libfdt: Handle unknown tags in fdt_next_tag()

Quoted 12 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

libfdt uses fdt_next_tag() to get a tag.

Filtering out tags that should be ignored in fdt_next_tag() allows to have the filtering done globally and allows, in future releases, to have a central place to add new known tags that should not be filtered out.

An already known tag exists with the meaning of "just ignore". This tag is FDT_NOP. fdt_next_tag() callers already handle the FDT_NOP tag.

Quoted 6 lines

Avoid unneeded modification at callers side and use a fake FDT_NOP tag when an unknown tag that should be ignored is encountered.

Add also fdt_next_tag_() internal function for callers who need to know if the FDT_NOP tag returned is a real FDT_NOP or a fake FDT_NOP due to an unknown tag.

I'm a bit unsure about this one. If we were designing the libfdt interface from scratch, I'd definitely say that fdt_next_tag() - as a low level function - should return every tag, and it's up to the caller to skip unknown ones. fdt_next_tag() already provides nextoffset making it fairly easy to do so.

But, of course, we're not building from scratch so we do need to consider backwards compatibility. Supplying a skipping and non-skipping version as you have here is the obvious approach.

But I'm not entirely convinced it's the only or best approach. A user which calls fdt_next_tag() is, in a sense, already opting in to low-level handling of the dtb. They could well already be broken by new tags (depending on how they handle the default case). Arguably it's reasonable to require them to be updated (once only) for this new family of tags.

Another potential approach would be to actually use the symbol versioning we have, but have som far only minimally exploited. The LIBFDT_1.2 version of fdt_next_tag() would skip tags that postdate it, but we'd introduce a new version tag and the new default version of fdt_next_tag() would return all tags. That would of course require figuring out how to do that with the verison script.

Quoted 62 lines
---
 libfdt/fdt.c             | 75 ++++++++++++++++++++++++++++++++++++++--
 libfdt/libfdt_internal.h |  3 ++
 tests/run_tests.sh       |  9 +++--
 3 files changed, 83 insertions(+), 4 deletions(-)
libfdt/fdt.c +32 -2
index eb803e8a..506e0dd3 100644
@@ -167,7 +167,7 @@ const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int len)
 	return fdt_offset_ptr_(fdt, offset);
 }
 
-uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
+static uint32_t fdt_next_tag_all(const void *fdt, int startoffset, int *nextoffset)
 {
 	const fdt32_t *tagp, *lenp;
 	uint32_t tag, len, sum;
@@ -218,7 +218,37 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 		break;
 
 	default:
-		return FDT_END;
+		if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+			return FDT_END;
+
+		switch (tag & FDT_TAG_DATA_MASK) {
+		case FDT_TAG_DATA_NONE:
+			break;
+		case FDT_TAG_DATA_1CELL:
+			offset += FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_2CELLS:
+			offset += 2 * FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_VARLEN:
+			/* Get the length */
+			lenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp));
+			if (!can_assume(VALID_DTB) && !lenp)
+				return FDT_END; /* premature end */
+			len = fdt32_to_cpu(*lenp);
+			/*
+			 * Skip the cell encoding the length and the
+			 * following length bytes
+			 */
+			len += sizeof(*lenp);
+			sum = len + offset;
+			if (!can_assume(VALID_DTB) &&
+			    (sum >= INT_MAX || sum < (uint32_t) offset))
+				return FDT_END; /* premature end */
+
+			offset += len;
+			break;
+		}
 	}
 
 	if (!fdt_offset_ptr(fdt, startoffset, offset - startoffset))

libfdt/fdt.c uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset) · line 261

Quoted 4 lines
libfdt/fdt.c +1 -0
@@ -228,6 +258,47 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 	return tag;
 }
 
+static bool fdt_tag_is_unknown(uint32_t tag)

Regardless of what approach we decide to take, "unknown" is a misleading term here. As we add support for new metadata tags to libfdt, they will no longer be unknown to libfdt. But what matters for the interface compatibility is whether they're unknown to the caller, which we can't know. So really this is checking for structured tags specifically.

Quoted 5 lines
libfdt/fdt.c +5 -0
+{
+	switch (tag) {
+	case FDT_BEGIN_NODE:
+	case FDT_END_NODE:
+	case FDT_PROP:

libfdt/fdt.c uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset) · line 276

Quoted 10 lines
libfdt/fdt.c +10 -0
+	case FDT_NOP:
+	case FDT_END:
+		return false;
+	default:
+		break;
+	}
+	return true;
+}
+
+uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset, bool *is_unknown)

Nothing in this patch uses the is_unknown parameter. Presumably something later does, but it's not clear to me what it's useful for.

Quoted 79 lines
libfdt/fdt.c +25 -0
+{
+	uint32_t tag;
+	bool unknown = false;
+
+	/* Retrieve next tag */
+	tag = fdt_next_tag_all(fdt, startoffset, nextoffset);
+	if (tag == FDT_END)
+		goto end;
+
+	if (fdt_tag_is_unknown(tag)) {
+		unknown = true;
+		/* Use a known tag that should be skipped by the caller */
+		tag = FDT_NOP;
+	}
+end:
+	if (is_unknown)
+		*is_unknown = unknown;
+	return tag;
+}
+
+uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
+{
+	return fdt_next_tag_(fdt, startoffset, nextoffset, NULL);
+}
+
 int fdt_check_node_offset_(const void *fdt, int offset)
 {
 	if (!can_assume(VALID_INPUT)
libfdt/libfdt_internal.h +3 -0
index 0e103caf..f2e30ce8 100644
@@ -20,6 +20,9 @@ int32_t fdt_ro_probe_(const void *fdt);
 		}							\
 	}
 
+uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset,
+		       bool *is_unknown);
 
 
 
+

int fdt_check_node_offset_(const void *fdt, int offset); int fdt_check_prop_offset_(const void *fdt, int offset);

tests/run_tests.sh +7 -2
index 8fc23cb7..225c22f8 100755
@@ -577,11 +577,12 @@ libfdt_tests () {
     run_test dtbs_equal_ordered cell-overflow.test.dtb cell-overflow-results.test.dtb
 
     # check full tests
-    for good in test_tree1.dtb; do
+    for good in test_tree1.dtb unknown_tags_can_skip.dtb; do
 	run_test check_full $good
     done
     for bad in truncated_property.dtb truncated_string.dtb \
-		truncated_memrsv.dtb two_roots.dtb named_root.dtb; do
+		truncated_memrsv.dtb two_roots.dtb named_root.dtb \
+		unknown_tags_no_skip.dtb; do
 	run_test check_full -n $bad
     done
 }
@@ -962,6 +963,10 @@ fdtget_tests () {
     run_fdtget_test "<the dead silence>" -tx \
 	-d "<the dead silence>" $dtb /randomnode doctor-who
     run_fdtget_test "<blink>" -tx -d "<blink>" $dtb /memory doctor-who
+
+    # test with unknown tags involved
+    run_fdtget_test "25601 25602" unknown_tags_can_skip.dtb /subnode1 prop-int
+    run_wrap_error_test $DTGET unknown_tags_no_skip.dtb /subnode1 prop-int
 }
 
 fdtput_tests () {
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#57 lore raw

Re: [PATCH v3 09/15] libfdt: Handle unknown tags in fdt_next_tag()

Hi David,

Quoted 30 lines · On Wed, 16 Sep 2026 19:10:27 +1000 David Gibson <[email protected]>…
Quoted 12 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

libfdt uses fdt_next_tag() to get a tag.

Filtering out tags that should be ignored in fdt_next_tag() allows to have the filtering done globally and allows, in future releases, to have a central place to add new known tags that should not be filtered out.

An already known tag exists with the meaning of "just ignore". This tag is FDT_NOP. fdt_next_tag() callers already handle the FDT_NOP tag.

Quoted 6 lines

Avoid unneeded modification at callers side and use a fake FDT_NOP tag when an unknown tag that should be ignored is encountered.

Add also fdt_next_tag_() internal function for callers who need to know if the FDT_NOP tag returned is a real FDT_NOP or a fake FDT_NOP due to an unknown tag.

I'm a bit unsure about this one. If we were designing the libfdt interface from scratch, I'd definitely say that fdt_next_tag() - as a low level function - should return every tag, and it's up to the caller to skip unknown ones. fdt_next_tag() already provides nextoffset making it fairly easy to do so.

But, of course, we're not building from scratch so we do need to consider backwards compatibility. Supplying a skipping and non-skipping version as you have here is the obvious approach.

Quoted 6 lines

But I'm not entirely convinced it's the only or best approach. A user which calls fdt_next_tag() is, in a sense, already opting in to low-level handling of the dtb. They could well already be broken by new tags (depending on how they handle the default case). Arguably it's reasonable to require them to be updated (once only) for this new family of tags.

I can go in that way. We will have same kind of sequence in almost all callers.

   do {
      tag = fdt_next_tag()
   } while (!fdt_tag_is_unknown(tag));

We have to care about those "unknown_and_skippable" tags only when we modify a dtb. This is handled by a few functions.

The vast majority of callers of fdt_next_tag() just want to skip unknown tags.

Quoted 7 lines

Another potential approach would be to actually use the symbol versioning we have, but have som far only minimally exploited. The LIBFDT_1.2 version of fdt_next_tag() would skip tags that postdate it, but we'd introduce a new version tag and the new default version of fdt_next_tag() would return all tags. That would of course require figuring out how to do that with the verison script.

Hum, I really don't want to have versioning in loop for fdt_next_tag().

Also, this could work in the dynamic lib (.so) case but not for static link and even less for libfdt code copy compiled in bootloaders or Linux kernel code.

fdt_next_tag() is a low level function accessible out of libfdt (API). If it doesn't skip unknown tags even for other libfdt internal function it will be a too lower function. Ok, we can have a wrapper on top of fdt_next_tag() to skip unknown tags.

fdt_next_tag() is a low level function but the rule related to skipping unknown tags is also a low level rule.

We have to choose:
a) fdt_next_tag() as I proposed
Of course ok for me

b) fdt_next_tag() returns all tags -> Full handling at caller side Ok, we can go in that direction but it will bring quite a lot of code duplication. I am not fully convinced by this option.

c) lib version
I disagree on my side

d) Other idea
Of course, I am still open.

Quoted 67 lines
Quoted 67 lines
---
 libfdt/fdt.c             | 75 ++++++++++++++++++++++++++++++++++++++--
 libfdt/libfdt_internal.h |  3 ++
 tests/run_tests.sh       |  9 +++--
 3 files changed, 83 insertions(+), 4 deletions(-)
libfdt/fdt.c +32 -2
index eb803e8a..506e0dd3 100644
@@ -167,7 +167,7 @@ const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int len)
 	return fdt_offset_ptr_(fdt, offset);
 }
 
-uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
+static uint32_t fdt_next_tag_all(const void *fdt, int startoffset, int *nextoffset)
 {
 	const fdt32_t *tagp, *lenp;
 	uint32_t tag, len, sum;
@@ -218,7 +218,37 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 		break;
 
 	default:
-		return FDT_END;
+		if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+			return FDT_END;
+
+		switch (tag & FDT_TAG_DATA_MASK) {
+		case FDT_TAG_DATA_NONE:
+			break;
+		case FDT_TAG_DATA_1CELL:
+			offset += FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_2CELLS:
+			offset += 2 * FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_VARLEN:
+			/* Get the length */
+			lenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp));
+			if (!can_assume(VALID_DTB) && !lenp)
+				return FDT_END; /* premature end */
+			len = fdt32_to_cpu(*lenp);
+			/*
+			 * Skip the cell encoding the length and the
+			 * following length bytes
+			 */
+			len += sizeof(*lenp);
+			sum = len + offset;
+			if (!can_assume(VALID_DTB) &&
+			    (sum >= INT_MAX || sum < (uint32_t) offset))
+				return FDT_END; /* premature end */
+
+			offset += len;
+			break;
+		}
 	}
 
 	if (!fdt_offset_ptr(fdt, startoffset, offset - startoffset))
@@ -228,6 +258,47 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 	return tag;
 }
 
Quoted 5 lines

libfdt/fdt.c uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset) · line 261

Quoted 1 line
libfdt/fdt.c +1 -0
+static bool fdt_tag_is_unknown(uint32_t tag)  

Regardless of what approach we decide to take, "unknown" is a misleading term here. As we add support for new metadata tags to libfdt, they will no longer be unknown to libfdt. But what matters

Yes, metadata tags once supported in libfdt will not be considered as "unknown" tags.

An unknow tag is a tag libfdt don't know about except:
- weither it can be skip or not,
- the data length related to this tag.
- Is relation ship with other objects:
- Global to the whole dtb if found out of any nodes
- Related to a node if found right after FDT_BEGIN_NODE
- Related to a poperty if found right after FDT_PROP

Quoted 2 lines

for the interface compatibility is whether they're unknown to the caller, which we can't know. So really this is checking for

If a caller need to handle this unknown tag, it has to use a libfdt which support this tag.

Quoted 9 lines

structured tags specifically.

libfdt/fdt.c uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset) · line 268

Quoted 7 lines
libfdt/fdt.c +7 -0
+{
+	switch (tag) {
+	case FDT_BEGIN_NODE:
+	case FDT_END_NODE:
+	case FDT_PROP:
+	case FDT_NOP:
+	case FDT_END:

This list will grow as soon as new tags are defined and supported in libfdt.

See all tags added by the addon series:
https://github.com/bootlin/dtc/blob/c68038e0ff4cde5de37a21419df8a082032ef994/libfdt/fdt.c#L435

Quoted 4 lines
Quoted 4 lines
libfdt/fdt.c +4 -0
+		return false;
+	default:
+		break;
+	}
Quoted 8 lines

libfdt/fdt.c uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset) · line 276

Quoted 4 lines
libfdt/fdt.c +4 -0
+	return true;
+}
+
+uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset, bool *is_unknown)  

Nothing in this patch uses the is_unknown parameter. Presumably something later does, but it's not clear to me what it's useful for.

Yes later in [PATCH v3 14/15] libfdt: Handle unknown tags on dtb modifications In this patch, libfdt/fdt_rw.c, fdt_prop_remove_unknown_tags(). Code also in git repo [0].

[0] https://github.com/bootlin/dtc/blob/2653bb9cd4414780c863051467b5e77eea6e5bdd/libfdt/fdt_rw.c#L211

Best regards,
Hervé

#58 lore raw

Re: [PATCH v3 09/15] libfdt: Handle unknown tags in fdt_next_tag()

Quoted 42 lines · Herve Codina

Hi David,

Quoted 30 lines · On Wed, 16 Sep 2026 19:10:27 +1000 David Gibson <[email protected]>…
Quoted 12 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

libfdt uses fdt_next_tag() to get a tag.

Filtering out tags that should be ignored in fdt_next_tag() allows to have the filtering done globally and allows, in future releases, to have a central place to add new known tags that should not be filtered out.

An already known tag exists with the meaning of "just ignore". This tag is FDT_NOP. fdt_next_tag() callers already handle the FDT_NOP tag.

Quoted 6 lines

Avoid unneeded modification at callers side and use a fake FDT_NOP tag when an unknown tag that should be ignored is encountered.

Add also fdt_next_tag_() internal function for callers who need to know if the FDT_NOP tag returned is a real FDT_NOP or a fake FDT_NOP due to an unknown tag.

I'm a bit unsure about this one. If we were designing the libfdt interface from scratch, I'd definitely say that fdt_next_tag() - as a low level function - should return every tag, and it's up to the caller to skip unknown ones. fdt_next_tag() already provides nextoffset making it fairly easy to do so.

But, of course, we're not building from scratch so we do need to consider backwards compatibility. Supplying a skipping and non-skipping version as you have here is the obvious approach.

Quoted 6 lines

But I'm not entirely convinced it's the only or best approach. A user which calls fdt_next_tag() is, in a sense, already opting in to low-level handling of the dtb. They could well already be broken by new tags (depending on how they handle the default case). Arguably it's reasonable to require them to be updated (once only) for this new family of tags.

Quoted 6 lines

I can go in that way. We will have same kind of sequence in almost all callers.

   do {
      tag = fdt_next_tag()
   } while (!fdt_tag_is_unknown(tag));

Not really - users of fdt_next_tag() will typically already have a switch on the tag type, so the unknown tag handling would be an addition to the 'default' case, not requiring an extra loop.

Quoted 5 lines

We have to care about those "unknown_and_skippable" tags only when we modify a dtb. This is handled by a few functions.

The vast majority of callers of fdt_next_tag() just want to skip unknown tags.

I'm not sure that's true of the (few) callers outside libfdt itself.

Quoted 8 lines
Quoted 6 lines

Another potential approach would be to actually use the symbol versioning we have, but have som far only minimally exploited. The LIBFDT_1.2 version of fdt_next_tag() would skip tags that postdate it, but we'd introduce a new version tag and the new default version of fdt_next_tag() would return all tags. That would of course require figuring out how to do that with the verison script.

Hum, I really don't want to have versioning in loop for fdt_next_tag().

I'm not sure what you mean by "in loop" here.

Quoted 3 lines

Also, this could work in the dynamic lib (.so) case but not for static link and even less for libfdt code copy compiled in bootloaders or Linux kernel code.

Are symbol versions entirely unsupported with static libraries? Obviously they'd have to be resolved at (static) link time, not runtime, but I don't see that it's impossible.

Quoted 3 lines

fdt_next_tag() is a low level function accessible out of libfdt (API). If it doesn't skip unknown tags even for other libfdt internal function it will be a too lower function.

I don't really follow what you're saying here.

Quoted 6 lines

Ok, we can have a wrapper on top of
fdt_next_tag() to skip unknown tags.

fdt_next_tag() is a low level function but the rule related to skipping unknown tags is also a low level rule.

Quoted 7 lines

We have to choose:
a) fdt_next_tag() as I proposed
Of course ok for me

b) fdt_next_tag() returns all tags -> Full handling at caller side Ok, we can go in that direction but it will bring quite a lot of code duplication.

I'm not sure it's that bad, since fdt_next_tag() loops will typically already have a 'default' case for irrelevant tags, which will generally be handled the same as unknown tags.

Quoted 4 lines

I am not fully convinced by this option.

c) lib version
I disagree on my side

Yeah, I'm not really convinced by this one either.

Quoted 2 lines

d) Other idea
Of course, I am still open.

I haven't thought of any more ideas yet.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#59 lore raw

Re: [PATCH v3 09/15] libfdt: Handle unknown tags in fdt_next_tag()

Hi David,

Quoted 46 lines · On Thu, 17 Sep 2026 19:36:06 +1000 David Gibson <[email protected]>…
Quoted 45 lines · Herve Codina

Hi David,

Quoted 30 lines · On Wed, 16 Sep 2026 19:10:27 +1000 David Gibson <[email protected]>…
Quoted 12 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

libfdt uses fdt_next_tag() to get a tag.

Filtering out tags that should be ignored in fdt_next_tag() allows to have the filtering done globally and allows, in future releases, to have a central place to add new known tags that should not be filtered out.

An already known tag exists with the meaning of "just ignore". This tag is FDT_NOP. fdt_next_tag() callers already handle the FDT_NOP tag.

Quoted 6 lines

Avoid unneeded modification at callers side and use a fake FDT_NOP tag when an unknown tag that should be ignored is encountered.

Add also fdt_next_tag_() internal function for callers who need to know if the FDT_NOP tag returned is a real FDT_NOP or a fake FDT_NOP due to an unknown tag.

I'm a bit unsure about this one. If we were designing the libfdt interface from scratch, I'd definitely say that fdt_next_tag() - as a low level function - should return every tag, and it's up to the caller to skip unknown ones. fdt_next_tag() already provides nextoffset making it fairly easy to do so.

But, of course, we're not building from scratch so we do need to consider backwards compatibility. Supplying a skipping and non-skipping version as you have here is the obvious approach.

Quoted 6 lines

But I'm not entirely convinced it's the only or best approach. A user which calls fdt_next_tag() is, in a sense, already opting in to low-level handling of the dtb. They could well already be broken by new tags (depending on how they handle the default case). Arguably it's reasonable to require them to be updated (once only) for this new family of tags.

I can go in that way. We will have same kind of sequence in almost all callers.

Quoted 7 lines
Quoted 3 lines
   do {
      tag = fdt_next_tag()
   } while (!fdt_tag_is_unknown(tag));  

Not really - users of fdt_next_tag() will typically already have a switch on the tag type, so the unknown tag handling would be an addition to the 'default' case, not requiring an extra loop.

Ok, those are to be update to use a switch on tag but that's not big deal
- fdt_check_node_offset_()
- fdt_check_prop_offset_()
- fdt_add_subnode_namelen()
- fdt_finish()

Some others like nextprop_() or fdt_next_node() mix a while loop and a switch/case. Some rework to be planned.

Quoted 8 lines
Quoted 6 lines

We have to care about those "unknown_and_skippable" tags only when we modify a dtb. This is handled by a few functions.

The vast majority of callers of fdt_next_tag() just want to skip unknown tags.

I'm not sure that's true of the (few) callers outside libfdt itself.

Well, today there is no "unknown" tags and existing callers works correctly.

Unknown tags are reported as FDT_NOP. It should be ok with existing callers. They should handle FDT_NOP.

Quoted 11 lines
Quoted 9 lines
Quoted 7 lines

Another potential approach would be to actually use the symbol versioning we have, but have som far only minimally exploited. The LIBFDT_1.2 version of fdt_next_tag() would skip tags that postdate it, but we'd introduce a new version tag and the new default version of fdt_next_tag() would return all tags. That would of course require figuring out how to do that with the verison script.

Hum, I really don't want to have versioning in loop for fdt_next_tag().

I'm not sure what you mean by "in loop" here.

I don't want to add the versioning extra complexity in this context. I am sure we can find a solution for this "all tags vs only known tags" topic without versioning involved.

Quoted 6 lines
Quoted 4 lines

Also, this could work in the dynamic lib (.so) case but not for static link and even less for libfdt code copy compiled in bootloaders or Linux kernel code.

Are symbol versions entirely unsupported with static libraries?

I would say yes but maybe I am wrong.

https://sourceware.org/binutils/docs/ld/VERSION.html
https://sourceware.org/binutils/docs/ld.html#index-_002d_002dversion_002dscript_003dversion_002dscriptfile

Quoted 8 lines

Obviously they'd have to be resolved at (static) link time, not runtime, but I don't see that it's impossible.

Quoted 3 lines

fdt_next_tag() is a low level function accessible out of libfdt (API). If it doesn't skip unknown tags even for other libfdt internal function it will be a too lower function.

I don't really follow what you're saying here.

Skipping unknown tag is a low level feature.
I think fdt_next_tag() can handle this low level feature.

Upper layer using fdt_next_tag() should not handle this tag skipping the general case and let fdt_next_tag() do this job.

Got the feeling that we are going to add complexity at upper layer to handle a feature that should be handled at low level.

Quoted 11 lines
Quoted 11 lines

Ok, we can have a wrapper on top of
fdt_next_tag() to skip unknown tags.

fdt_next_tag() is a low level function but the rule related to skipping unknown tags is also a low level rule.

We have to choose:
a) fdt_next_tag() as I proposed
Of course ok for me

Quoted 7 lines
Quoted 3 lines

b) fdt_next_tag() returns all tags -> Full handling at caller side Ok, we can go in that direction but it will bring quite a lot of code duplication.

I'm not sure it's that bad, since fdt_next_tag() loops will typically already have a 'default' case for irrelevant tags, which will generally be handled the same as unknown tags.

Well as we did for "offset 0 vs real root node offset", I think the best way to known if it's bad or not is to try.

I will not have time this week to propose something and I have a training next week.

If you're ok for a try, I will do it but not as quickly as I did for the "offset 0 vs real root node offset" topic.

Quoted 7 lines
Quoted 5 lines

I am not fully convinced by this option.

c) lib version
I disagree on my side

Yeah, I'm not really convinced by this one either.

We are on the same page.

Quoted 6 lines
Quoted 3 lines

d) Other idea
Of course, I am still open.

I haven't thought of any more ideas yet.

Best regards,
Hervé

#60 lore raw

Re: [PATCH v3 09/15] libfdt: Handle unknown tags in fdt_next_tag()

Quoted 55 lines · Herve Codina

Hi David,

Quoted 50 lines · On Thu, 17 Sep 2026 19:36:06 +1000 David Gibson <[email protected]>…
Quoted 48 lines · Herve Codina

Hi David,

Quoted 30 lines · On Wed, 16 Sep 2026 19:10:27 +1000 David Gibson <[email protected]>…
Quoted 12 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error when they are read.

libfdt uses fdt_next_tag() to get a tag.

Filtering out tags that should be ignored in fdt_next_tag() allows to have the filtering done globally and allows, in future releases, to have a central place to add new known tags that should not be filtered out.

An already known tag exists with the meaning of "just ignore". This tag is FDT_NOP. fdt_next_tag() callers already handle the FDT_NOP tag.

Quoted 6 lines

Avoid unneeded modification at callers side and use a fake FDT_NOP tag when an unknown tag that should be ignored is encountered.

Add also fdt_next_tag_() internal function for callers who need to know if the FDT_NOP tag returned is a real FDT_NOP or a fake FDT_NOP due to an unknown tag.

I'm a bit unsure about this one. If we were designing the libfdt interface from scratch, I'd definitely say that fdt_next_tag() - as a low level function - should return every tag, and it's up to the caller to skip unknown ones. fdt_next_tag() already provides nextoffset making it fairly easy to do so.

But, of course, we're not building from scratch so we do need to consider backwards compatibility. Supplying a skipping and non-skipping version as you have here is the obvious approach.

Quoted 6 lines

But I'm not entirely convinced it's the only or best approach. A user which calls fdt_next_tag() is, in a sense, already opting in to low-level handling of the dtb. They could well already be broken by new tags (depending on how they handle the default case). Arguably it's reasonable to require them to be updated (once only) for this new family of tags.

I can go in that way. We will have same kind of sequence in almost all callers.

   do {
      tag = fdt_next_tag()
   } while (!fdt_tag_is_unknown(tag));  
Quoted 7 lines
Quoted 3 lines

Not really - users of fdt_next_tag() will typically already have a switch on the tag type, so the unknown tag handling would be an addition to the 'default' case, not requiring an extra loop.

Ok, those are to be update to use a switch on tag but that's not big deal
- fdt_check_node_offset_()
- fdt_check_prop_offset_()

These don't have a switch because they're asserting we're already on a specific tag type. They should still do that with structured tags:
these functions should be checking that we're exactly on an FDT_BEGIN_NODE or FDT_PROP, not on a skippable tag that sits before one of those.

Or to put it another way, if we did have fdt_next_tag() vs. fdt_next_tag_all() these functions should be using fdt_next_tag_all().

Quoted 1 line

- fdt_add_subnode_namelen()

The logic here is placing the subnode after the parent's properties, by moving past any FDT_PROP or FDT_NOP tags. With skippable tags we do need to skip those too. Which we can express instead as skipping until we find either an FDT_BEGIN_NODE (indicating the first child) or an FDT_END_NODE (indicating the end of a currently childless parent). So, no need for a new switch here.

Quoted 1 line

- fdt_finish()

No need for changes here either - this already skips everything that's not FDT_PROP, so it will do the right think for skippable tags.

Quoted 2 lines

Some others like nextprop_() or fdt_next_node() mix a while loop and a switch/case. Some rework to be planned.

nextprop_() will need some rework, yes.

fdt_next_node() only barely: it already ignores FDT_PROP and FDT_NOP; change that to 'default' and it will skip those and future structured tags as well.

Quoted 10 lines
Quoted 7 lines
Quoted 5 lines

We have to care about those "unknown_and_skippable" tags only when we modify a dtb. This is handled by a few functions.

The vast majority of callers of fdt_next_tag() just want to skip unknown tags.

I'm not sure that's true of the (few) callers outside libfdt itself.

Well, today there is no "unknown" tags and existing callers works correctly.

Rather, any tags unknown by the caller are assumed fatal.

Quoted 11 lines

Unknown tags are reported as FDT_NOP. It should be ok with existing callers. They should handle FDT_NOP.

Quoted 8 lines
Quoted 8 lines
Quoted 7 lines

Another potential approach would be to actually use the symbol versioning we have, but have som far only minimally exploited. The LIBFDT_1.2 version of fdt_next_tag() would skip tags that postdate it, but we'd introduce a new version tag and the new default version of fdt_next_tag() would return all tags. That would of course require figuring out how to do that with the verison script.

Quoted 7 lines
Quoted 3 lines
Quoted 1 line

Hum, I really don't want to have versioning in loop for fdt_next_tag().

I'm not sure what you mean by "in loop" here.

I don't want to add the versioning extra complexity in this context. I am sure we can find a solution for this "all tags vs only known tags" topic without versioning involved.

"known tags" is meaningless here - what matters is whether the tags are known by the *caller*, which we don't know.

Quoted 10 lines
Quoted 5 lines
Quoted 3 lines

Also, this could work in the dynamic lib (.so) case but not for static link and even less for libfdt code copy compiled in bootloaders or Linux kernel code.

Are symbol versions entirely unsupported with static libraries?

I would say yes but maybe I am wrong.

https://sourceware.org/binutils/docs/ld/VERSION.html
https://sourceware.org/binutils/docs/ld.html#index-_002d_002dversion_002dscript_003dversion_002dscriptfile

Ah, yes, I think you're right. Ok, that's not going to work.

Quoted 4 lines
Quoted 4 lines

Obviously they'd have to be resolved at (static) link time, not runtime, but I don't see that it's impossible.

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

fdt_next_tag() is a low level function accessible out of libfdt (API). If it doesn't skip unknown tags even for other libfdt internal function it will be a too lower function.

I don't really follow what you're saying here.

Skipping unknown tag is a low level feature.
I think fdt_next_tag() can handle this low level feature.

It really can't, because it doesn't know what tags the caller is aware of. It can only make a distinction between "older tags than <arbitrary cutoff>" and "newer tags than <arbitrary cutoff>".

Quoted 21 lines

Upper layer using fdt_next_tag() should not handle this tag skipping the general case and let fdt_next_tag() do this job.

Got the feeling that we are going to add complexity at upper layer to handle a feature that should be handled at low level.

Quoted 15 lines
Quoted 14 lines

Ok, we can have a wrapper on top of
fdt_next_tag() to skip unknown tags.

fdt_next_tag() is a low level function but the rule related to skipping unknown tags is also a low level rule.

We have to choose:
a) fdt_next_tag() as I proposed
Of course ok for me

b) fdt_next_tag() returns all tags -> Full handling at caller side Ok, we can go in that direction but it will bring quite a lot of code duplication.

Quoted 6 lines
Quoted 3 lines

I'm not sure it's that bad, since fdt_next_tag() loops will typically already have a 'default' case for irrelevant tags, which will generally be handled the same as unknown tags.

Well as we did for "offset 0 vs real root node offset", I think the best way to known if it's bad or not is to try.

Agreed.

Quoted 26 lines

I will not have time this week to propose something and I have a training next week.

If you're ok for a try, I will do it but not as quickly as I did for the "offset 0 vs real root node offset" topic.

Quoted 7 lines
Quoted 5 lines

I am not fully convinced by this option.

c) lib version
I disagree on my side

Yeah, I'm not really convinced by this one either.

We are on the same page.

Quoted 6 lines
Quoted 3 lines

d) Other idea
Of course, I am still open.

I haven't thought of any more ideas yet.

Best regards,
Hervé

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#61 lore raw

Re: [PATCH v3 09/15] libfdt: Handle unknown tags in fdt_next_tag()

Hi David,

On Sat, 19 Sep 2026 14:46:05 +1000
David Gibson <[email protected]> wrote:

...

Quoted 22 lines
Quoted 22 lines

Upper layer using fdt_next_tag() should not handle this tag skipping the general case and let fdt_next_tag() do this job.

Got the feeling that we are going to add complexity at upper layer to handle a feature that should be handled at low level.

Quoted 15 lines
Quoted 14 lines

Ok, we can have a wrapper on top of
fdt_next_tag() to skip unknown tags.

fdt_next_tag() is a low level function but the rule related to skipping unknown tags is also a low level rule.

We have to choose:
a) fdt_next_tag() as I proposed
Of course ok for me

b) fdt_next_tag() returns all tags -> Full handling at caller side Ok, we can go in that direction but it will bring quite a lot of code duplication.

Quoted 15 lines
Quoted 6 lines
Quoted 3 lines

I'm not sure it's that bad, since fdt_next_tag() loops will typically already have a 'default' case for irrelevant tags, which will generally be handled the same as unknown tags.

Well as we did for "offset 0 vs real root node offset", I think the best way to known if it's bad or not is to try.

Agreed.

Quoted 6 lines

I will not have time this week to propose something and I have a training next week.

If you're ok for a try, I will do it but not as quickly as I did for the "offset 0 vs real root node offset" topic.

I did my homework and I think I was wrong. fdt_next_tag() can return all tags without adding too much complexity in current code.

Here is the diff to consider that fully replaces this current patch.

You can note that I've added the FDT_TAG_IS_SKIPPABLE() macro. This macro should be added in a previous commit introducing structured tag (or skippable if renamed). According to discussion we've already had related to "structure" tag format, the FDT_TAG_IS_SKIPPABLE() macro content will not be that one but you've got the idea of its usage in the diff.

--- 8< ---

libfdt/fdt.c +32 -1
index eb803e8a..e426414b 100644
@@ -218,7 +218,37 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 		break;
 
 	default:
-		return FDT_END;
+		if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+			return FDT_END;
+
+		switch (tag & FDT_TAG_DATA_MASK) {
+		case FDT_TAG_DATA_NONE:
+			break;
+		case FDT_TAG_DATA_1CELL:
+			offset += FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_2CELLS:
+			offset += 2 * FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_VARLEN:
+			/* Get the length */
+			lenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp));
+			if (!can_assume(VALID_DTB) && !lenp)
+				return FDT_END; /* premature end */
+			len = fdt32_to_cpu(*lenp);
+			/*
+			 * Skip the cell encoding the length and the
+			 * following length bytes
+			 */
+			len += sizeof(*lenp);
+			sum = len + offset;
+			if (!can_assume(VALID_DTB) &&
+			    (sum >= INT_MAX || sum < (uint32_t) offset))
+				return FDT_END; /* premature end */
+
+			offset += len;
+			break;
+		}
 	}
 
 	if (!fdt_offset_ptr(fdt, startoffset, offset - startoffset))
@@ -303,6 +333,7 @@ int fdt_next_node(const void *fdt, int offset, int *depth)
 		switch (tag) {
 		case FDT_PROP:
 		case FDT_NOP:
+		default: /* All Skippable tags */
 			break;
 
 		case FDT_BEGIN_NODE:
libfdt/fdt.h +2 -0
index f41a355f..55138261 100644
@@ -73,6 +73,8 @@ struct fdt_property {
 #define FDT_TAG_CAN_SKIP(tag_data, tag_id) \
 		(FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE | tag_data | tag_id)
 
+#define FDT_TAG_IS_SKIPPABLE(_tag) (((_tag) & (FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE)) == (FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE))
+
 /* Tests reserved tags */
 #define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
 #define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
libfdt/fdt_check.c +4 -2
index 2fd5b61d..8bd9b252 100644
@@ -45,7 +45,8 @@ int fdt_check_full(const void *fdt, size_t bufsize)
 			return nextoffset;
 
 		/* If we see two root nodes, something is wrong */
-		if (expect_end && tag != FDT_END && tag != FDT_NOP)
+		if (expect_end && tag != FDT_END && tag != FDT_NOP &&
+			!FDT_TAG_IS_SKIPPABLE(tag))
 			return -FDT_ERR_BADSTRUCTURE;
 
 		switch (tag) {
@@ -92,7 +93,8 @@ int fdt_check_full(const void *fdt, size_t bufsize)
 			break;
 
 		default:
-			return -FDT_ERR_INTERNAL;
+			/* Skippable tags -> Skip them */
+			break;
 		}
 	}
 }
libfdt/fdt_ro.c +1 -1
index 856c62f1..3cc0435c 100644
@@ -219,7 +219,7 @@ static int nextprop_(const void *fdt, int offset)
 			return offset;
 		}
 		offset = nextoffset;
-	} while (tag == FDT_NOP);
+	} while (tag == FDT_NOP || FDT_TAG_IS_SKIPPABLE(tag));
 
 	return -FDT_ERR_NOTFOUND;
 }
tests/run_tests.sh +7 -2
index 8fc23cb7..225c22f8 100755
@@ -577,11 +577,12 @@ libfdt_tests () {
     run_test dtbs_equal_ordered cell-overflow.test.dtb cell-overflow-results.test.dtb
 
     # check full tests
-    for good in test_tree1.dtb; do
+    for good in test_tree1.dtb unknown_tags_can_skip.dtb; do
 	run_test check_full $good
     done
     for bad in truncated_property.dtb truncated_string.dtb \
-		truncated_memrsv.dtb two_roots.dtb named_root.dtb; do
+		truncated_memrsv.dtb two_roots.dtb named_root.dtb \
+		unknown_tags_no_skip.dtb; do
 	run_test check_full -n $bad
     done
 }
@@ -962,6 +963,10 @@ fdtget_tests () {
     run_fdtget_test "<the dead silence>" -tx \
 	-d "<the dead silence>" $dtb /randomnode doctor-who
     run_fdtget_test "<blink>" -tx -d "<blink>" $dtb /memory doctor-who
+
+    # test with unknown tags involved
+    run_fdtget_test "25601 25602" unknown_tags_can_skip.dtb /subnode1 prop-int
+    run_wrap_error_test $DTGET unknown_tags_no_skip.dtb /subnode1 prop-int
 }
 
 fdtput_tests () {

--- 8< ---

Also I've modified tests/dtbs_equal_ordered.c but I am not sure that the modification I did is a modification you will accept.

We could just ignore skippable tags but I choose to test data when such an skippable tag is encoutered.

This leads to the following modification:
--- 8< ---

tests/dtbs_equal_ordered.c +34 -0
@@ -71,6 +71,7 @@ static void compare_structure(const void *fdt1, const void *fdt2)
 	int err;
 	const struct fdt_property *prop1, *prop2;
 	int len1, len2;
+	const void *raw1, *raw2;
 
 	while (1) {
 		do {
@@ -102,6 +103,9 @@ static void compare_structure(const void *fdt1, const void *fdt2)
 				     name1, name2, offset1, offset2);
 			break;
 
+		case FDT_END_NODE:
+			break;
+
 		case FDT_PROP:
 			prop1 = fdt_offset_ptr(fdt1, offset1, sizeof(*prop1));
 			if (!prop1)
@@ -128,6 +132,36 @@ static void compare_structure(const void *fdt1, const void *fdt2)
 
 		case FDT_END:
 			return;
+
+		default:
+			if (!FDT_TAG_IS_SKIPPABLE(tag1))
+				FAIL("Cannot check tag data at (%d, %d)",
+					offset1, offset2);
+
+			/*
+			 * Even if we don't known the meaning of data,
+			 * we can check that raw data are the same.
+			 */
+			len1 = nextoffset1 - offset1;
+			len2 = nextoffset2 - offset2;
+
+			if (len1 != len2) {
+				MISMATCH("tag data length mismatch at (%d, %d)",
+					offset1, offset2);
+			}
+
+			raw1 = fdt_offset_ptr(fdt1, offset1, len1);
+			if (!raw1)
+				FAIL("Could get fdt1 raw buffer at %d", offset1);
+
+			raw2 = fdt_offset_ptr(fdt2, offset2, len2);
+			if (!raw1)
+				FAIL("Could get fdt1 raw buffer at %d", offset2);
+
+			if (memcmp(raw1, raw2, len1) != 0)
+				MISMATCH("Tag data value mismatch at (%d, %d)",
+					 offset1, offset2);
+			break;
 		}
 	}
 }

--- 8< ---

With that done, my conclusion is: Yes we can return all tags in fdt_next_tag(). I think you will agree this conclusion.

For dtbs_equal_ordered.c, should we compare skippable tags and related data as I did (diff above) or should we just skip them? what is your opinion?

For the next patch ("libfdt: Handle unknown tags on dtb modifications") returning all tags from fdt_next_tag() has also some impacts but nothing more complex than modification provided here. I can provide the full diff if you want. Let me know.

Best regards,
Hervé

#62 lore raw

Re: [PATCH v3 09/15] libfdt: Handle unknown tags in fdt_next_tag()

Quoted 41 lines · Herve Codina

Hi David,

On Sat, 19 Sep 2026 14:46:05 +1000
David Gibson <[email protected]> wrote:

...

Quoted 34 lines
Quoted 22 lines

Upper layer using fdt_next_tag() should not handle this tag skipping the general case and let fdt_next_tag() do this job.

Got the feeling that we are going to add complexity at upper layer to handle a feature that should be handled at low level.

Quoted 15 lines
Quoted 14 lines

Ok, we can have a wrapper on top of
fdt_next_tag() to skip unknown tags.

fdt_next_tag() is a low level function but the rule related to skipping unknown tags is also a low level rule.

We have to choose:
a) fdt_next_tag() as I proposed
Of course ok for me

b) fdt_next_tag() returns all tags -> Full handling at caller side Ok, we can go in that direction but it will bring quite a lot of code duplication.

Quoted 6 lines
Quoted 3 lines

I'm not sure it's that bad, since fdt_next_tag() loops will typically already have a 'default' case for irrelevant tags, which will generally be handled the same as unknown tags.

Well as we did for "offset 0 vs real root node offset", I think the best way to known if it's bad or not is to try.

Agreed.

Quoted 3 lines

I will not have time this week to propose something and I have a training next week.

Quoted 6 lines
Quoted 3 lines
Quoted 3 lines

If you're ok for a try, I will do it but not as quickly as I did for the "offset 0 vs real root node offset" topic.

I did my homework and I think I was wrong. fdt_next_tag() can return all tags without adding too much complexity in current code.

Right, I suspected that would be the case.

Quoted 7 lines

Here is the diff to consider that fully replaces this current patch.

You can note that I've added the FDT_TAG_IS_SKIPPABLE() macro. This macro should be added in a previous commit introducing structured tag (or skippable if renamed). According to discussion we've already had related to "structure" tag format, the FDT_TAG_IS_SKIPPABLE() macro content will not be that one but you've got the idea of its usage in the diff.

Ok. I'm having second thoughts about the "skippable" terminology based on the complications for read-write access, but I'll discuss that in full elsewhere.

Whatever we call it, the idea of an is_new_style(tag) macro makes sense.

Quoted 123 lines

--- 8< ---

libfdt/fdt.c +32 -1
index eb803e8a..e426414b 100644
@@ -218,7 +218,37 @@ uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
 		break;
 
 	default:
-		return FDT_END;
+		if (!(tag & FDT_TAG_STRUCTURED) || !(tag & FDT_TAG_SKIP_SAFE))
+			return FDT_END;
+
+		switch (tag & FDT_TAG_DATA_MASK) {
+		case FDT_TAG_DATA_NONE:
+			break;
+		case FDT_TAG_DATA_1CELL:
+			offset += FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_2CELLS:
+			offset += 2 * FDT_CELLSIZE;
+			break;
+		case FDT_TAG_DATA_VARLEN:
+			/* Get the length */
+			lenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp));
+			if (!can_assume(VALID_DTB) && !lenp)
+				return FDT_END; /* premature end */
+			len = fdt32_to_cpu(*lenp);
+			/*
+			 * Skip the cell encoding the length and the
+			 * following length bytes
+			 */
+			len += sizeof(*lenp);
+			sum = len + offset;
+			if (!can_assume(VALID_DTB) &&
+			    (sum >= INT_MAX || sum < (uint32_t) offset))
+				return FDT_END; /* premature end */
+
+			offset += len;
+			break;
+		}
 	}
 
 	if (!fdt_offset_ptr(fdt, startoffset, offset - startoffset))
@@ -303,6 +333,7 @@ int fdt_next_node(const void *fdt, int offset, int *depth)
 		switch (tag) {
 		case FDT_PROP:
 		case FDT_NOP:
+		default: /* All Skippable tags */
 			break;
 
 		case FDT_BEGIN_NODE:
libfdt/fdt.h +2 -0
index f41a355f..55138261 100644
@@ -73,6 +73,8 @@ struct fdt_property {
 #define FDT_TAG_CAN_SKIP(tag_data, tag_id) \
 		(FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE | tag_data | tag_id)
 
+#define FDT_TAG_IS_SKIPPABLE(_tag) (((_tag) & (FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE)) == (FDT_TAG_STRUCTURED | FDT_TAG_SKIP_SAFE))
+
 /* Tests reserved tags */
 #define FDT_TEST_NONE_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_NONE, 0)
 #define FDT_TEST_1CELL_CAN_SKIP		FDT_TAG_CAN_SKIP(FDT_TAG_DATA_1CELL, 0)
libfdt/fdt_check.c +4 -2
index 2fd5b61d..8bd9b252 100644
@@ -45,7 +45,8 @@ int fdt_check_full(const void *fdt, size_t bufsize)
 			return nextoffset;
 
 		/* If we see two root nodes, something is wrong */
-		if (expect_end && tag != FDT_END && tag != FDT_NOP)
+		if (expect_end && tag != FDT_END && tag != FDT_NOP &&
+			!FDT_TAG_IS_SKIPPABLE(tag))
 			return -FDT_ERR_BADSTRUCTURE;
 
 		switch (tag) {
@@ -92,7 +93,8 @@ int fdt_check_full(const void *fdt, size_t bufsize)
 			break;
 
 		default:
-			return -FDT_ERR_INTERNAL;
+			/* Skippable tags -> Skip them */
+			break;
 		}
 	}
 }
libfdt/fdt_ro.c +1 -1
index 856c62f1..3cc0435c 100644
@@ -219,7 +219,7 @@ static int nextprop_(const void *fdt, int offset)
 			return offset;
 		}
 		offset = nextoffset;
-	} while (tag == FDT_NOP);
+	} while (tag == FDT_NOP || FDT_TAG_IS_SKIPPABLE(tag));
 
 	return -FDT_ERR_NOTFOUND;
 }
tests/run_tests.sh +3 -2
index 8fc23cb7..225c22f8 100755
@@ -577,11 +577,12 @@ libfdt_tests () {
     run_test dtbs_equal_ordered cell-overflow.test.dtb cell-overflow-results.test.dtb
 
     # check full tests
-    for good in test_tree1.dtb; do
+    for good in test_tree1.dtb unknown_tags_can_skip.dtb; do
 	run_test check_full $good
     done
     for bad in truncated_property.dtb truncated_string.dtb \
-		truncated_memrsv.dtb two_roots.dtb named_root.dtb; do
+		truncated_memrsv.dtb two_roots.dtb named_root.dtb \
+		unknown_tags_no_skip.dtb; do
 	run_test check_full -n $bad
     done
 }
@@ -962,6 +963,10 @@ fdtget_tests () {
     run_fdtget_test "<the dead silence>" -tx \

tests/run_tests.sh fdtget_tests () {

Quoted 10 lines
tests/run_tests.sh +4 -1
 	-d "<the dead silence>" $dtb /randomnode doctor-who
     run_fdtget_test "<blink>" -tx -d "<blink>" $dtb /memory doctor-who
+
+    # test with unknown tags involved
+    run_fdtget_test "25601 25602" unknown_tags_can_skip.dtb /subnode1 prop-int
+    run_wrap_error_test $DTGET unknown_tags_no_skip.dtb /subnode1 prop-int
 }
 
 fdtput_tests () {
--- 8< ---

That looks fine, except insofar as other changes we've already discussed will require updates here too.

Quoted 56 lines

Also I've modified tests/dtbs_equal_ordered.c but I am not sure that the modification I did is a modification you will accept.

We could just ignore skippable tags but I choose to test data when such an skippable tag is encoutered.

This leads to the following modification:
--- 8< ---

tests/dtbs_equal_ordered.c +28 -0
@@ -71,6 +71,7 @@ static void compare_structure(const void *fdt1, const void *fdt2)
 	int err;
 	const struct fdt_property *prop1, *prop2;
 	int len1, len2;
+	const void *raw1, *raw2;
 
 	while (1) {
 		do {
@@ -102,6 +103,9 @@ static void compare_structure(const void *fdt1, const void *fdt2)
 				     name1, name2, offset1, offset2);
 			break;
 
+		case FDT_END_NODE:
+			break;
+
 		case FDT_PROP:
 			prop1 = fdt_offset_ptr(fdt1, offset1, sizeof(*prop1));
 			if (!prop1)
@@ -128,6 +132,36 @@ static void compare_structure(const void *fdt1, const void *fdt2)
 
 		case FDT_END:
 			return;
+
+		default:
+			if (!FDT_TAG_IS_SKIPPABLE(tag1))
+				FAIL("Cannot check tag data at (%d, %d)",
+					offset1, offset2);
+
+			/*
+			 * Even if we don't known the meaning of data,
+			 * we can check that raw data are the same.
+			 */
+			len1 = nextoffset1 - offset1;
+			len2 = nextoffset2 - offset2;
+
+			if (len1 != len2) {
+				MISMATCH("tag data length mismatch at (%d, %d)",
+					offset1, offset2);
+			}
+
+			raw1 = fdt_offset_ptr(fdt1, offset1, len1);
+			if (!raw1)
+				FAIL("Could get fdt1 raw buffer at %d", offset1);
+
+			raw2 = fdt_offset_ptr(fdt2, offset2, len2);
+			if (!raw1)

tests/dtbs_equal_ordered.c static void compare_structure(const void *fdt1, const void *fdt2)

Quoted 10 lines
tests/dtbs_equal_ordered.c +6 -1
+				FAIL("Could get fdt1 raw buffer at %d", offset2);
+
+			if (memcmp(raw1, raw2, len1) != 0)
+				MISMATCH("Tag data value mismatch at (%d, %d)",
+					 offset1, offset2);
+			break;
 		}
 	}
 }
--- 8< ---

So, as I mentioned elswhere a version of dtbs_equal_ordered that also checks tag data sounds like a very useful tool. But, I can also see the use of comparisons that ignore metadata tags. So, I think we want both variants. That could be either separate test binaries, or an option to dtbs_equal_ordered and/or dtbs_equal_unordered, whicever turns out easier.

Quoted 2 lines

With that done, my conclusion is: Yes we can return all tags in fdt_next_tag(). I think you will agree this conclusion.

Excellent.

Quoted 3 lines

For dtbs_equal_ordered.c, should we compare skippable tags and related data as I did (diff above) or should we just skip them? what is your opinion?

As above, I think we want both options.

Quoted 4 lines

For the next patch ("libfdt: Handle unknown tags on dtb modifications") returning all tags from fdt_next_tag() has also some impacts but nothing more complex than modification provided here. I can provide the full diff if you want. Let me know.

Not for now, leave it until you post the next revision of the series.

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#63 lore raw

PATCH v3 10/15 libfdt: Introduce fdt_ptr_offset_()

In reply to Herve Codina

libfdt provides internal helpers to convert an offset to a pointer but nothing to do the reverse operation.

Introduce the fdt_ptr_offset_() internal helper to convert a pointer to an offset.

---
 libfdt/libfdt_internal.h | 5 +++++
 1 file changed, 5 insertions(+)
libfdt/libfdt_internal.h +5 -0
index f2e30ce8..3c83d9a7 100644
@@ -46,6 +46,11 @@ static inline void *fdt_offset_ptr_w_(void *fdt, int offset)
 	return (void *)(uintptr_t)fdt_offset_ptr_(fdt, offset);
 }
 
+static inline int fdt_ptr_offset_(const void *fdt, const void *ptr)
+{
+	return (const char *)ptr - (const char *)fdt_offset_ptr_(fdt, 0);
+}
+
 static inline const struct fdt_reserve_entry *fdt_mem_rsv_(const void *fdt, int n)
 {
 	const struct fdt_reserve_entry *rsv_table =
Signature · 1 line
2.55.0
#64 lore raw

PATCH v3 11/15 libfdt: Introduce fdt_getprop_by_offset_w()

In reply to Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to modify properties retrieved by their offset.

fdt_getprop_by_offset() already exists to get a preperty by its offset but the property returned is read-only. A writable returned property is needed.

Fill the lack and introduce fdt_getprop_by_offset_w(), the write enabled variant of fdt_getprop_by_offset().

Add also its related test.

---
 libfdt/libfdt.h           |  6 +++
 tests/.gitignore          |  1 +
 tests/Makefile.tests      |  2 +-
 tests/get_prop_offset_w.c | 84 +++++++++++++++++++++++++++++++++++++++
 tests/meson.build         |  1 +
 tests/run_tests.sh        |  1 +
 tests/tests.h             |  1 +
 tests/testutils.c         | 18 +++++++++
 8 files changed, 113 insertions(+), 1 deletion(-)
 create mode 100644 tests/get_prop_offset_w.c
libfdt/libfdt.h +6 -0
index 7a1915a5..82965e32 100644
@@ -856,6 +856,12 @@ static inline struct fdt_property *fdt_get_property_w(void *fdt, int nodeoffset,
 #ifndef SWIG /* This function is not useful in Python */
 const void *fdt_getprop_by_offset(const void *fdt, int offset,
 				  const char **namep, int *lenp);
+static inline void *fdt_getprop_by_offset_w(const void *fdt, int offset,
+					    const char **namep, int *lenp)
+{
+	return (void *)(uintptr_t)fdt_getprop_by_offset(fdt, offset, namep,
+							lenp);
+}
 #endif
 
 /**
tests/.gitignore +1 -0
index 69693129..1091174a 100644
@@ -30,6 +30,7 @@ tmp.*
 /get_phandle
 /getprop
 /get_prop_offset
+/get_prop_offset_w
 /incbin
 /integer-expressions
 /fs_tree1
tests/Makefile.tests +1 -1
index 63e201ae..0d4d399f 100644
@@ -16,7 +16,7 @@ LIB_TESTS_L = get_mem_rsv \
 	sw_tree1 sw_states \
 	move_and_save mangle-layout nopulate \
 	open_pack rw_tree1 rw_oom set_name setprop del_property del_node \
-	appendprop1 appendprop2 propname_escapes \
+	appendprop1 appendprop2 propname_escapes get_prop_offset_w \
 	string_escapes references path-references phandle_format \
 	boot-cpuid incbin relref_merge \
 	extra-terminating-null \
tests/get_prop_offset_w.c new file +84 -0

84 lines not on this page · raw message

tests/meson.build +1 -0
index 779e6bc7..dae6a941 100644
@@ -50,6 +50,7 @@ tests = [
   'get_path',
   'get_phandle',
   'get_prop_offset',
+  'get_prop_offset_w',
   'get_next_tag_invalid_prop_len',
   'getprop',
   'incbin',
tests/run_tests.sh +1 -0
index 225c22f8..419a24d8 100755
@@ -419,6 +419,7 @@ tree1_tests_rw () {
     run_test setprop $TREE
     run_test del_property $TREE
     run_test del_node $TREE
+    run_test get_prop_offset_w $TREE
 }
 
 check_tests () {
tests/tests.h +1 -0
index 578d8c1a..37ed3394 100644
@@ -109,6 +109,7 @@ const void *check_get_prop_offset(void *fdt, int poffset, const char *in_name,
 const void *check_getprop_addrrange(void *fdt, int parent, int nodeoffset,
 				    const char *name, int num);
 
+int get_poffset(void *fdt, int nodeoffset, const char *propname);
 int nodename_eq(const char *s1, const char *s2);
 void vg_prepare_blob(void *fdt, size_t bufsize);
 void *load_blob(const char *filename);
tests/testutils.c +18 -0
index 6d69e872..d35a1978 100644
@@ -230,6 +230,24 @@ const void *check_getprop_addrrange(void *fdt, int parent, int nodeoffset,
 	return propval;
 }
 
+int get_poffset(void *fdt, int nodeoffset, const char *propname)
+{
+	const char *name;
+	int poffset;
+
+	fdt_for_each_property_offset(poffset, fdt, nodeoffset) {
+		if (fdt_getprop_by_offset(fdt, poffset, &name, NULL)) {
+			if (!strcmp(name, propname))
+				return poffset;
+		}
+	}
+
+	if (poffset < 0)
+		return poffset;
+
+	return -FDT_ERR_NOTFOUND;
+}
+
 int nodename_eq(const char *s1, const char *s2)
 {
 	int len = strlen(s2);
Signature · 1 line
2.55.0
#65 lore raw

Re: [PATCH v3 11/15] libfdt: Introduce fdt_getprop_by_offset_w()

Quoted 6 lines · Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to modify properties retrieved by their offset.

fdt_getprop_by_offset() already exists to get a preperty by its offset but the property returned is read-only. A writable returned property is needed.

Since we already have fdt_get_property_by_offset_w() this is an obvious gap and I'd be happy in principle to apply this independent of the rest of the series.

Quoted 94 lines

Fill the lack and introduce fdt_getprop_by_offset_w(), the write enabled variant of fdt_getprop_by_offset().

Add also its related test.

---
 libfdt/libfdt.h           |  6 +++
 tests/.gitignore          |  1 +
 tests/Makefile.tests      |  2 +-
 tests/get_prop_offset_w.c | 84 +++++++++++++++++++++++++++++++++++++++
 tests/meson.build         |  1 +
 tests/run_tests.sh        |  1 +
 tests/tests.h             |  1 +
 tests/testutils.c         | 18 +++++++++
 8 files changed, 113 insertions(+), 1 deletion(-)
 create mode 100644 tests/get_prop_offset_w.c
libfdt/libfdt.h +6 -0
index 7a1915a5..82965e32 100644
@@ -856,6 +856,12 @@ static inline struct fdt_property *fdt_get_property_w(void *fdt, int nodeoffset,
 #ifndef SWIG /* This function is not useful in Python */
 const void *fdt_getprop_by_offset(const void *fdt, int offset,
 				  const char **namep, int *lenp);
+static inline void *fdt_getprop_by_offset_w(const void *fdt, int offset,
+					    const char **namep, int *lenp)
+{
+	return (void *)(uintptr_t)fdt_getprop_by_offset(fdt, offset, namep,
+							lenp);
+}
 #endif
 
 /**
tests/.gitignore +1 -0
index 69693129..1091174a 100644
@@ -30,6 +30,7 @@ tmp.*
 /get_phandle
 /getprop
 /get_prop_offset
+/get_prop_offset_w
 /incbin
 /integer-expressions
 /fs_tree1
tests/Makefile.tests +1 -1
index 63e201ae..0d4d399f 100644
@@ -16,7 +16,7 @@ LIB_TESTS_L = get_mem_rsv \
 	sw_tree1 sw_states \
 	move_and_save mangle-layout nopulate \
 	open_pack rw_tree1 rw_oom set_name setprop del_property del_node \
-	appendprop1 appendprop2 propname_escapes \
+	appendprop1 appendprop2 propname_escapes get_prop_offset_w \
 	string_escapes references path-references phandle_format \
 	boot-cpuid incbin relref_merge \
 	extra-terminating-null \
tests/get_prop_offset_w.c new file +28 -0
new file mode 100644
index 00000000..dbfa5dd7
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: LGPL-2.1-or-later
+/*
+ * libfdt - Flat Device Tree manipulation
+ *	Testcase for fdt_getprop_by_offset_w()
+ * Copyright (C) 2026 Bootlin.
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdint.h>
+
+#include <libfdt.h>
+
+#include "tests.h"
+#include "testdata.h"
+
+#define SPACE		65536
+
+int main(int argc, char *argv[])
+{
+	const void *exp_val;
+	const char *name;
+	char *modif_val;
+	void *propval;
+	int proplen;
+	int exp_len;
+	int poffset;

tests/get_prop_offset_w.c line 38

Quoted 10 lines
tests/get_prop_offset_w.c new file +10 -0
+	void *fdt;
+	void *buf;
+	int err;
+
+	test_init(argc, argv);
+	fdt = load_blob_arg(argc, argv);
+
+	buf = xmalloc(SPACE);
+
+	err = fdt_open_into(fdt, buf, SPACE);

You shouldn't need an fdt_open_into(). You're modifying the contents of a single property, but not moving tags about or (specifically) expanding the tree as a whole. This is a "write in place" operation rather than a "read/write" operation in libfdt terms.

tests/get_prop_offset_w.c

Quoted 10 lines
tests/get_prop_offset_w.c new file +10 -0
+	if (err)
+		FAIL("fdt_open_into(): %s", fdt_strerror(err));
+
+	free(fdt);
+	fdt = buf;
+
+	/* Retrieve the offset of the 'prop-str' property */
+	poffset = get_poffset(fdt, 0, "prop-str");
+	if (poffset < 0)
+		FAIL("Property 'prop-str' not found")

Introducing get_poffset() seems a bit awkward compared to using an fdt_for_each_property_offset() like get_prop_offset.c does.

Quoted 10 lines
tests/get_prop_offset_w.c new file +10 -0
+
+	/* Get the property value for modification */
+	propval = fdt_getprop_by_offset_w(fdt, poffset, &name, &proplen);
+	if (!propval)
+		FAIL("fdt_getprop_by_offset_w(%d): %s", poffset,
+		     fdt_strerror(proplen));
+
+	/* Check original values */
+	if (strcmp(name, "prop-str"))
+		FAIL("Name mismatch : %s instead of prop-str", name);

tests/get_prop_offset_w.c line 68

Quoted 10 lines
tests/get_prop_offset_w.c new file +10 -0
+
+	exp_len = strlen(TEST_STRING_1) + 1;
+	if (proplen != exp_len)
+		FAIL("Original size mismatch on property \"%s\": %d instead of %d",
+		     name, proplen, exp_len);
+
+	exp_val = TEST_STRING_1;
+	if (memcmp(exp_val, propval, exp_len))
+		FAIL("Original data mismatch on property \"%s\"", name);
+

You could re-use check_get_prop_offset() from testutils.c to perform these tests before invoking fdt_getprop_by_offset_w().

tests/get_prop_offset_w.c line 74

Quoted 6 lines
tests/get_prop_offset_w.c new file +6 -0
+	if (exp_len < 4)
+		CONFIG("Property \"%s\" should be at least 4 bytes", name);
+
+	/* Modify the property value */
+	modif_val = xmalloc(proplen);
+	memcpy(modif_val, propval, proplen);

Why malloc() and memcpy()? The whole point of fdt_getprop_by_offset_w() is that you get a writable pointer into the fdt which you can modify in place.

Quoted 27 lines
tests/get_prop_offset_w.c new file +10 -0
+	modif_val[1] = (modif_val[1] != 'A') ? 'A' : 'a';
+	modif_val[3] = (modif_val[3] != 'B') ? 'B' : 'b';
+	memcpy(propval, modif_val, exp_len);
+
+	/* Check that the modified value is taken into account */
+	if (!check_get_prop_offset(fdt, poffset, "prop-str", exp_len, modif_val))
+		FAIL("Modified property 'prop-str' not found");
+
+	PASS();
+}
tests/meson.build +1 -0
index 779e6bc7..dae6a941 100644
@@ -50,6 +50,7 @@ tests = [
   'get_path',
   'get_phandle',
   'get_prop_offset',
+  'get_prop_offset_w',
   'get_next_tag_invalid_prop_len',
   'getprop',
   'incbin',
tests/run_tests.sh +0 -0
index 225c22f8..419a24d8 100755

tests/run_tests.sh tree1_tests_rw () { · line 422

Quoted 4 lines
tests/run_tests.sh +1 -0
@@ -419,6 +419,7 @@ tree1_tests_rw () {
     run_test setprop $TREE
     run_test del_property $TREE
     run_test del_node $TREE
+    run_test get_prop_offset_w $TREE

This belongs with the other write-in-place tests in tree1_tests(), not as an rw test.

Quoted 48 lines
tests/run_tests.sh +0 -0
 }
 
 check_tests () {
tests/tests.h +1 -0
index 578d8c1a..37ed3394 100644
@@ -109,6 +109,7 @@ const void *check_get_prop_offset(void *fdt, int poffset, const char *in_name,
 const void *check_getprop_addrrange(void *fdt, int parent, int nodeoffset,
 				    const char *name, int num);
 
+int get_poffset(void *fdt, int nodeoffset, const char *propname);
 int nodename_eq(const char *s1, const char *s2);
 void vg_prepare_blob(void *fdt, size_t bufsize);
 void *load_blob(const char *filename);
tests/testutils.c +18 -0
index 6d69e872..d35a1978 100644
@@ -230,6 +230,24 @@ const void *check_getprop_addrrange(void *fdt, int parent, int nodeoffset,
 	return propval;
 }
 
+int get_poffset(void *fdt, int nodeoffset, const char *propname)
+{
+	const char *name;
+	int poffset;
+
+	fdt_for_each_property_offset(poffset, fdt, nodeoffset) {
+		if (fdt_getprop_by_offset(fdt, poffset, &name, NULL)) {
+			if (!strcmp(name, propname))
+				return poffset;
+		}
+	}
+
+	if (poffset < 0)
+		return poffset;
+
+	return -FDT_ERR_NOTFOUND;
+}
+
 int nodename_eq(const char *s1, const char *s2)
 {
 	int len = strlen(s2);
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#66 lore raw

Re: [PATCH v3 11/15] libfdt: Introduce fdt_getprop_by_offset_w()

Hi David,

Quoted 11 lines · On Wed, 16 Sep 2026 19:56:46 +1000 David Gibson <[email protected]>…
Quoted 6 lines · Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to modify properties retrieved by their offset.

fdt_getprop_by_offset() already exists to get a preperty by its offset but the property returned is read-only. A writable returned property is needed.

Since we already have fdt_get_property_by_offset_w() this is an obvious gap and I'd be happy in principle to apply this independent of the rest of the series.

Nice :)

Quoted 102 lines
Quoted 102 lines

Fill the lack and introduce fdt_getprop_by_offset_w(), the write enabled variant of fdt_getprop_by_offset().

Add also its related test.

---
 libfdt/libfdt.h           |  6 +++
 tests/.gitignore          |  1 +
 tests/Makefile.tests      |  2 +-
 tests/get_prop_offset_w.c | 84 +++++++++++++++++++++++++++++++++++++++
 tests/meson.build         |  1 +
 tests/run_tests.sh        |  1 +
 tests/tests.h             |  1 +
 tests/testutils.c         | 18 +++++++++
 8 files changed, 113 insertions(+), 1 deletion(-)
 create mode 100644 tests/get_prop_offset_w.c
libfdt/libfdt.h +6 -0
index 7a1915a5..82965e32 100644
@@ -856,6 +856,12 @@ static inline struct fdt_property *fdt_get_property_w(void *fdt, int nodeoffset,
 #ifndef SWIG /* This function is not useful in Python */
 const void *fdt_getprop_by_offset(const void *fdt, int offset,
 				  const char **namep, int *lenp);
+static inline void *fdt_getprop_by_offset_w(const void *fdt, int offset,
+					    const char **namep, int *lenp)
+{
+	return (void *)(uintptr_t)fdt_getprop_by_offset(fdt, offset, namep,
+							lenp);
+}
 #endif
 
 /**
tests/.gitignore +1 -0
index 69693129..1091174a 100644
@@ -30,6 +30,7 @@ tmp.*
 /get_phandle
 /getprop
 /get_prop_offset
+/get_prop_offset_w
 /incbin
 /integer-expressions
 /fs_tree1
tests/Makefile.tests +1 -1
index 63e201ae..0d4d399f 100644
@@ -16,7 +16,7 @@ LIB_TESTS_L = get_mem_rsv \
 	sw_tree1 sw_states \
 	move_and_save mangle-layout nopulate \
 	open_pack rw_tree1 rw_oom set_name setprop del_property del_node \
-	appendprop1 appendprop2 propname_escapes \
+	appendprop1 appendprop2 propname_escapes get_prop_offset_w \
 	string_escapes references path-references phandle_format \
 	boot-cpuid incbin relref_merge \
 	extra-terminating-null \
tests/get_prop_offset_w.c new file +35 -0
new file mode 100644
index 00000000..dbfa5dd7
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: LGPL-2.1-or-later
+/*
+ * libfdt - Flat Device Tree manipulation
+ *	Testcase for fdt_getprop_by_offset_w()
+ * Copyright (C) 2026 Bootlin.
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdint.h>
+
+#include <libfdt.h>
+
+#include "tests.h"
+#include "testdata.h"
+
+#define SPACE		65536
+
+int main(int argc, char *argv[])
+{
+	const void *exp_val;
+	const char *name;
+	char *modif_val;
+	void *propval;
+	int proplen;
+	int exp_len;
+	int poffset;
+	void *fdt;
+	void *buf;
+	int err;
+
+	test_init(argc, argv);
+	fdt = load_blob_arg(argc, argv);
+
Quoted 8 lines

tests/get_prop_offset_w.c line 38

Quoted 3 lines
tests/get_prop_offset_w.c new file +3 -0
+	buf = xmalloc(SPACE);
+
+	err = fdt_open_into(fdt, buf, SPACE);  

You shouldn't need an fdt_open_into(). You're modifying the contents of a single property, but not moving tags about or (specifically) expanding the tree as a whole. This is a "write in place" operation rather than a "read/write" operation in libfdt terms.

Ok, I will update in the next iteration.

Quoted 14 lines

tests/get_prop_offset_w.c

Quoted 11 lines
tests/get_prop_offset_w.c new file +10 -0
+	if (err)
+		FAIL("fdt_open_into(): %s", fdt_strerror(err));
+
+	free(fdt);
+	fdt = buf;
+
+	/* Retrieve the offset of the 'prop-str' property */
+	poffset = get_poffset(fdt, 0, "prop-str");
+	if (poffset < 0)
+		FAIL("Property 'prop-str' not found")  

Introducing get_poffset() seems a bit awkward compared to using an fdt_for_each_property_offset() like get_prop_offset.c does.

Ok, will use fdt_for_each_property_offset() directly here and remove get_poffset() in the next iteration.

Quoted 16 lines
Quoted 16 lines
tests/get_prop_offset_w.c new file +15 -0
+
+	/* Get the property value for modification */
+	propval = fdt_getprop_by_offset_w(fdt, poffset, &name, &proplen);
+	if (!propval)
+		FAIL("fdt_getprop_by_offset_w(%d): %s", poffset,
+		     fdt_strerror(proplen));
+
+	/* Check original values */
+	if (strcmp(name, "prop-str"))
+		FAIL("Name mismatch : %s instead of prop-str", name);
+
+	exp_len = strlen(TEST_STRING_1) + 1;
+	if (proplen != exp_len)
+		FAIL("Original size mismatch on property \"%s\": %d instead of %d",
+		     name, proplen, exp_len);
Quoted 8 lines

tests/get_prop_offset_w.c line 68

Quoted 5 lines
tests/get_prop_offset_w.c new file +5 -0
+
+	exp_val = TEST_STRING_1;
+	if (memcmp(exp_val, propval, exp_len))
+		FAIL("Original data mismatch on property \"%s\"", name);
+  

You could re-use check_get_prop_offset() from testutils.c to perform these tests before invoking fdt_getprop_by_offset_w().

I wanted to test that the value returned by fdt_getprop_by_offset_w() is the correct one. check_get_prop_offset() calls fdt_getprop_by_offset() and not fdt_getprop_by_offset_w(). I know it doesn't matter with current implementation of fdt_getprop_by_offset_w() but I am not supposed to know about this implementation here in the test. Also, this implementation could change in the future (not planned on my side).

Quoted 11 lines

tests/get_prop_offset_w.c line 74

Quoted 7 lines
tests/get_prop_offset_w.c new file +6 -0
+	if (exp_len < 4)
+		CONFIG("Property \"%s\" should be at least 4 bytes", name);
+
+	/* Modify the property value */
+	modif_val = xmalloc(proplen);
+	memcpy(modif_val, propval, proplen);  

Why malloc() and memcpy()? The whole point of fdt_getprop_by_offset_w() is that you get a writable pointer into the fdt which you can modify in place.

I want to keep the modified value for later comparison.

- modif_val : Current property val + modification.
- Update propval: Current property val.
- Check reading the property with check_get_prop_offset() that the property has been really updated.

If instead I use only propval, I use only one buffer and so
- propval = modified value
- check that get check_get_prop_offset() which will also return the propval buffer matches the propval buffer.

In check_get_prop_offset();
--- 8< ---
const void *check_get_prop_offset(void *fdt, int poffset, const char *exp_name,
int exp_len, const void *exp_val)

{
	const void *propval;
	...
	propval = fdt_getprop_by_offset(fdt, poffset, &name, &proplen);
	...
 	if (exp_len && memcmp(exp_val, propval, exp_len))
             FAIL("Data mismatch on property \"%s\"", name);
        ...
}

Using a pointer returned by fdt_getprop_by_offset_w() as exp_val parameter leads to something like:
memcmp(propval, propval, exp_len)

This is always successful even if the propval buffer doesn't contain the data expected by the test. If for whatever reason the propval buffer is wrongly modified by some internal libfdt function called by check_get_prop_offset(), we cannot see it.

With the additional buffer (modif_val) which is never passed to libfdt, and contains expected data, we can see any wrong proval modification.

Quoted 27 lines
Quoted 27 lines
tests/get_prop_offset_w.c new file +10 -0
+	modif_val[1] = (modif_val[1] != 'A') ? 'A' : 'a';
+	modif_val[3] = (modif_val[3] != 'B') ? 'B' : 'b';
+	memcpy(propval, modif_val, exp_len);
+
+	/* Check that the modified value is taken into account */
+	if (!check_get_prop_offset(fdt, poffset, "prop-str", exp_len, modif_val))
+		FAIL("Modified property 'prop-str' not found");
+
+	PASS();
+}
tests/meson.build +1 -0
index 779e6bc7..dae6a941 100644
@@ -50,6 +50,7 @@ tests = [
   'get_path',
   'get_phandle',
   'get_prop_offset',
+  'get_prop_offset_w',
   'get_next_tag_invalid_prop_len',
   'getprop',
   'incbin',
tests/run_tests.sh +0 -0
index 225c22f8..419a24d8 100755
Quoted 8 lines

tests/run_tests.sh tree1_tests_rw () { · line 422

Quoted 5 lines
tests/run_tests.sh +1 -0
@@ -419,6 +419,7 @@ tree1_tests_rw () {
     run_test setprop $TREE
     run_test del_property $TREE
     run_test del_node $TREE
+    run_test get_prop_offset_w $TREE  

This belongs with the other write-in-place tests in tree1_tests(), not as an rw test.

Ok, I will move it.

Best regards,
Hervé

#67 lore raw

Re: [PATCH v3 11/15] libfdt: Introduce fdt_getprop_by_offset_w()

Quoted 174 lines · Herve Codina

Hi David,

Quoted 11 lines · On Wed, 16 Sep 2026 19:56:46 +1000 David Gibson <[email protected]>…
Quoted 6 lines · Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to modify properties retrieved by their offset.

fdt_getprop_by_offset() already exists to get a preperty by its offset but the property returned is read-only. A writable returned property is needed.

Since we already have fdt_get_property_by_offset_w() this is an obvious gap and I'd be happy in principle to apply this independent of the rest of the series.

Nice :)

Quoted 102 lines
Quoted 102 lines

Fill the lack and introduce fdt_getprop_by_offset_w(), the write enabled variant of fdt_getprop_by_offset().

Add also its related test.

---
 libfdt/libfdt.h           |  6 +++
 tests/.gitignore          |  1 +
 tests/Makefile.tests      |  2 +-
 tests/get_prop_offset_w.c | 84 +++++++++++++++++++++++++++++++++++++++
 tests/meson.build         |  1 +
 tests/run_tests.sh        |  1 +
 tests/tests.h             |  1 +
 tests/testutils.c         | 18 +++++++++
 8 files changed, 113 insertions(+), 1 deletion(-)
 create mode 100644 tests/get_prop_offset_w.c
libfdt/libfdt.h +6 -0
index 7a1915a5..82965e32 100644
@@ -856,6 +856,12 @@ static inline struct fdt_property *fdt_get_property_w(void *fdt, int nodeoffset,
 #ifndef SWIG /* This function is not useful in Python */
 const void *fdt_getprop_by_offset(const void *fdt, int offset,
 				  const char **namep, int *lenp);
+static inline void *fdt_getprop_by_offset_w(const void *fdt, int offset,
+					    const char **namep, int *lenp)
+{
+	return (void *)(uintptr_t)fdt_getprop_by_offset(fdt, offset, namep,
+							lenp);
+}
 #endif
 
 /**
tests/.gitignore +1 -0
index 69693129..1091174a 100644
@@ -30,6 +30,7 @@ tmp.*
 /get_phandle
 /getprop
 /get_prop_offset
+/get_prop_offset_w
 /incbin
 /integer-expressions
 /fs_tree1
tests/Makefile.tests +1 -1
index 63e201ae..0d4d399f 100644
@@ -16,7 +16,7 @@ LIB_TESTS_L = get_mem_rsv \
 	sw_tree1 sw_states \
 	move_and_save mangle-layout nopulate \
 	open_pack rw_tree1 rw_oom set_name setprop del_property del_node \
-	appendprop1 appendprop2 propname_escapes \
+	appendprop1 appendprop2 propname_escapes get_prop_offset_w \
 	string_escapes references path-references phandle_format \
 	boot-cpuid incbin relref_merge \
 	extra-terminating-null \
tests/get_prop_offset_w.c new file +35 -0
new file mode 100644
index 00000000..dbfa5dd7
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: LGPL-2.1-or-later
+/*
+ * libfdt - Flat Device Tree manipulation
+ *	Testcase for fdt_getprop_by_offset_w()
+ * Copyright (C) 2026 Bootlin.
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdint.h>
+
+#include <libfdt.h>
+
+#include "tests.h"
+#include "testdata.h"
+
+#define SPACE		65536
+
+int main(int argc, char *argv[])
+{
+	const void *exp_val;
+	const char *name;
+	char *modif_val;
+	void *propval;
+	int proplen;
+	int exp_len;
+	int poffset;
+	void *fdt;
+	void *buf;
+	int err;
+
+	test_init(argc, argv);
+	fdt = load_blob_arg(argc, argv);
+
Quoted 8 lines

tests/get_prop_offset_w.c line 38

Quoted 3 lines
tests/get_prop_offset_w.c new file +3 -0
+	buf = xmalloc(SPACE);
+
+	err = fdt_open_into(fdt, buf, SPACE);  

You shouldn't need an fdt_open_into(). You're modifying the contents of a single property, but not moving tags about or (specifically) expanding the tree as a whole. This is a "write in place" operation rather than a "read/write" operation in libfdt terms.

Ok, I will update in the next iteration.

Quoted 14 lines

tests/get_prop_offset_w.c

Quoted 11 lines
tests/get_prop_offset_w.c new file +10 -0
+	if (err)
+		FAIL("fdt_open_into(): %s", fdt_strerror(err));
+
+	free(fdt);
+	fdt = buf;
+
+	/* Retrieve the offset of the 'prop-str' property */
+	poffset = get_poffset(fdt, 0, "prop-str");
+	if (poffset < 0)
+		FAIL("Property 'prop-str' not found")  

Introducing get_poffset() seems a bit awkward compared to using an fdt_for_each_property_offset() like get_prop_offset.c does.

Ok, will use fdt_for_each_property_offset() directly here and remove get_poffset() in the next iteration.

Quoted 15 lines
Quoted 15 lines
tests/get_prop_offset_w.c new file +15 -0
+
+	/* Get the property value for modification */
+	propval = fdt_getprop_by_offset_w(fdt, poffset, &name, &proplen);
+	if (!propval)
+		FAIL("fdt_getprop_by_offset_w(%d): %s", poffset,
+		     fdt_strerror(proplen));
+
+	/* Check original values */
+	if (strcmp(name, "prop-str"))
+		FAIL("Name mismatch : %s instead of prop-str", name);
+
+	exp_len = strlen(TEST_STRING_1) + 1;
+	if (proplen != exp_len)
+		FAIL("Original size mismatch on property \"%s\": %d instead of %d",
+		     name, proplen, exp_len);
Quoted 8 lines

tests/get_prop_offset_w.c line 68

Quoted 5 lines
tests/get_prop_offset_w.c new file +5 -0
+
+	exp_val = TEST_STRING_1;
+	if (memcmp(exp_val, propval, exp_len))
+		FAIL("Original data mismatch on property \"%s\"", name);
+  

You could re-use check_get_prop_offset() from testutils.c to perform these tests before invoking fdt_getprop_by_offset_w().

Quoted 3 lines

I wanted to test that the value returned by fdt_getprop_by_offset_w() is the correct one. check_get_prop_offset() calls fdt_getprop_by_offset() and not fdt_getprop_by_offset_w().

Ah, fair point.

But.. rather than checking the retreived values the same as get_prop_offset.c, it would be both simpler and more complete to explicitly check that fdt_getprop_by_offset_w() returns the same pointer as fdt_getprop_by_offset().

Quoted 24 lines

I know it doesn't matter with current implementation
of fdt_getprop_by_offset_w() but I am not supposed to know about this implementation here in the test. Also, this implementation could change in the future (not planned on my side).

Quoted 11 lines

tests/get_prop_offset_w.c line 74

Quoted 7 lines
tests/get_prop_offset_w.c new file +6 -0
+	if (exp_len < 4)
+		CONFIG("Property \"%s\" should be at least 4 bytes", name);
+
+	/* Modify the property value */
+	modif_val = xmalloc(proplen);
+	memcpy(modif_val, propval, proplen);  

Why malloc() and memcpy()? The whole point of fdt_getprop_by_offset_w() is that you get a writable pointer into the fdt which you can modify in place.

I want to keep the modified value for later comparison.

- modif_val : Current property val + modification.
- Update propval: Current property val.
- Check reading the property with check_get_prop_offset() that the property has been really updated.

Quoted 4 lines

If instead I use only propval, I use only one buffer and so
- propval = modified value
- check that get check_get_prop_offset() which will also return the propval buffer matches the propval buffer.

Ah, missed that, that makes sense. Personally I'd probably go with a static buffer with the value to write in (and then compare), but either way is fine.

Quoted 67 lines

In check_get_prop_offset();
--- 8< ---
const void *check_get_prop_offset(void *fdt, int poffset, const char *exp_name,
int exp_len, const void *exp_val)

{
	const void *propval;
	...
	propval = fdt_getprop_by_offset(fdt, poffset, &name, &proplen);
	...
 	if (exp_len && memcmp(exp_val, propval, exp_len))
             FAIL("Data mismatch on property \"%s\"", name);
        ...
}

Using a pointer returned by fdt_getprop_by_offset_w() as exp_val parameter leads to something like:
memcmp(propval, propval, exp_len)

This is always successful even if the propval buffer doesn't contain the data expected by the test. If for whatever reason the propval buffer is wrongly modified by some internal libfdt function called by check_get_prop_offset(), we cannot see it.

With the additional buffer (modif_val) which is never passed to libfdt, and contains expected data, we can see any wrong proval modification.

Quoted 27 lines
Quoted 27 lines
tests/get_prop_offset_w.c new file +10 -0
+	modif_val[1] = (modif_val[1] != 'A') ? 'A' : 'a';
+	modif_val[3] = (modif_val[3] != 'B') ? 'B' : 'b';
+	memcpy(propval, modif_val, exp_len);
+
+	/* Check that the modified value is taken into account */
+	if (!check_get_prop_offset(fdt, poffset, "prop-str", exp_len, modif_val))
+		FAIL("Modified property 'prop-str' not found");
+
+	PASS();
+}
tests/meson.build +1 -0
index 779e6bc7..dae6a941 100644
@@ -50,6 +50,7 @@ tests = [
   'get_path',
   'get_phandle',
   'get_prop_offset',
+  'get_prop_offset_w',
   'get_next_tag_invalid_prop_len',
   'getprop',
   'incbin',
tests/run_tests.sh +0 -0
index 225c22f8..419a24d8 100755
Quoted 8 lines

tests/run_tests.sh tree1_tests_rw () { · line 422

Quoted 5 lines
tests/run_tests.sh +1 -0
@@ -419,6 +419,7 @@ tree1_tests_rw () {
     run_test setprop $TREE
     run_test del_property $TREE
     run_test del_node $TREE
+    run_test get_prop_offset_w $TREE  

This belongs with the other write-in-place tests in tree1_tests(), not as an rw test.

Ok, I will move it.

Best regards,
Hervé

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#68 lore raw

Re: [PATCH v3 11/15] libfdt: Introduce fdt_getprop_by_offset_w()

Quoted 179 lines · On Thu, 17 Sep 2026 14:52:28 +1000 David Gibson <[email protected]>…
Quoted 174 lines · Herve Codina

Hi David,

Quoted 11 lines · On Wed, 16 Sep 2026 19:56:46 +1000 David Gibson <[email protected]>…
Quoted 6 lines · Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to modify properties retrieved by their offset.

fdt_getprop_by_offset() already exists to get a preperty by its offset but the property returned is read-only. A writable returned property is needed.

Since we already have fdt_get_property_by_offset_w() this is an obvious gap and I'd be happy in principle to apply this independent of the rest of the series.

Nice :)

Quoted 102 lines
Quoted 102 lines

Fill the lack and introduce fdt_getprop_by_offset_w(), the write enabled variant of fdt_getprop_by_offset().

Add also its related test.

---
 libfdt/libfdt.h           |  6 +++
 tests/.gitignore          |  1 +
 tests/Makefile.tests      |  2 +-
 tests/get_prop_offset_w.c | 84 +++++++++++++++++++++++++++++++++++++++
 tests/meson.build         |  1 +
 tests/run_tests.sh        |  1 +
 tests/tests.h             |  1 +
 tests/testutils.c         | 18 +++++++++
 8 files changed, 113 insertions(+), 1 deletion(-)
 create mode 100644 tests/get_prop_offset_w.c
libfdt/libfdt.h +6 -0
index 7a1915a5..82965e32 100644
@@ -856,6 +856,12 @@ static inline struct fdt_property *fdt_get_property_w(void *fdt, int nodeoffset,
 #ifndef SWIG /* This function is not useful in Python */
 const void *fdt_getprop_by_offset(const void *fdt, int offset,
 				  const char **namep, int *lenp);
+static inline void *fdt_getprop_by_offset_w(const void *fdt, int offset,
+					    const char **namep, int *lenp)
+{
+	return (void *)(uintptr_t)fdt_getprop_by_offset(fdt, offset, namep,
+							lenp);
+}
 #endif
 
 /**
tests/.gitignore +1 -0
index 69693129..1091174a 100644
@@ -30,6 +30,7 @@ tmp.*
 /get_phandle
 /getprop
 /get_prop_offset
+/get_prop_offset_w
 /incbin
 /integer-expressions
 /fs_tree1
tests/Makefile.tests +1 -1
index 63e201ae..0d4d399f 100644
@@ -16,7 +16,7 @@ LIB_TESTS_L = get_mem_rsv \
 	sw_tree1 sw_states \
 	move_and_save mangle-layout nopulate \
 	open_pack rw_tree1 rw_oom set_name setprop del_property del_node \
-	appendprop1 appendprop2 propname_escapes \
+	appendprop1 appendprop2 propname_escapes get_prop_offset_w \
 	string_escapes references path-references phandle_format \
 	boot-cpuid incbin relref_merge \
 	extra-terminating-null \
tests/get_prop_offset_w.c new file +35 -0
new file mode 100644
index 00000000..dbfa5dd7
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: LGPL-2.1-or-later
+/*
+ * libfdt - Flat Device Tree manipulation
+ *	Testcase for fdt_getprop_by_offset_w()
+ * Copyright (C) 2026 Bootlin.
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdint.h>
+
+#include <libfdt.h>
+
+#include "tests.h"
+#include "testdata.h"
+
+#define SPACE		65536
+
+int main(int argc, char *argv[])
+{
+	const void *exp_val;
+	const char *name;
+	char *modif_val;
+	void *propval;
+	int proplen;
+	int exp_len;
+	int poffset;
+	void *fdt;
+	void *buf;
+	int err;
+
+	test_init(argc, argv);
+	fdt = load_blob_arg(argc, argv);
+
Quoted 8 lines

tests/get_prop_offset_w.c line 38

Quoted 3 lines
tests/get_prop_offset_w.c new file +3 -0
+	buf = xmalloc(SPACE);
+
+	err = fdt_open_into(fdt, buf, SPACE);    

You shouldn't need an fdt_open_into(). You're modifying the contents of a single property, but not moving tags about or (specifically) expanding the tree as a whole. This is a "write in place" operation rather than a "read/write" operation in libfdt terms.

Ok, I will update in the next iteration.

Quoted 14 lines

tests/get_prop_offset_w.c

Quoted 11 lines
tests/get_prop_offset_w.c new file +10 -0
+	if (err)
+		FAIL("fdt_open_into(): %s", fdt_strerror(err));
+
+	free(fdt);
+	fdt = buf;
+
+	/* Retrieve the offset of the 'prop-str' property */
+	poffset = get_poffset(fdt, 0, "prop-str");
+	if (poffset < 0)
+		FAIL("Property 'prop-str' not found")    

Introducing get_poffset() seems a bit awkward compared to using an fdt_for_each_property_offset() like get_prop_offset.c does.

Ok, will use fdt_for_each_property_offset() directly here and remove get_poffset() in the next iteration.

Quoted 15 lines
Quoted 15 lines
tests/get_prop_offset_w.c new file +15 -0
+
+	/* Get the property value for modification */
+	propval = fdt_getprop_by_offset_w(fdt, poffset, &name, &proplen);
+	if (!propval)
+		FAIL("fdt_getprop_by_offset_w(%d): %s", poffset,
+		     fdt_strerror(proplen));
+
+	/* Check original values */
+	if (strcmp(name, "prop-str"))
+		FAIL("Name mismatch : %s instead of prop-str", name);
+
+	exp_len = strlen(TEST_STRING_1) + 1;
+	if (proplen != exp_len)
+		FAIL("Original size mismatch on property \"%s\": %d instead of %d",
+		     name, proplen, exp_len);
Quoted 8 lines

tests/get_prop_offset_w.c line 68

Quoted 5 lines
tests/get_prop_offset_w.c new file +5 -0
+
+	exp_val = TEST_STRING_1;
+	if (memcmp(exp_val, propval, exp_len))
+		FAIL("Original data mismatch on property \"%s\"", name);
+    

You could re-use check_get_prop_offset() from testutils.c to perform these tests before invoking fdt_getprop_by_offset_w().

Quoted 3 lines

I wanted to test that the value returned by fdt_getprop_by_offset_w() is the correct one. check_get_prop_offset() calls fdt_getprop_by_offset() and not fdt_getprop_by_offset_w().

Quoted 6 lines

Ah, fair point.

But.. rather than checking the retreived values the same as get_prop_offset.c, it would be both simpler and more complete to explicitly check that fdt_getprop_by_offset_w() returns the same pointer as fdt_getprop_by_offset().

Ok, I will do that.

Quoted 25 lines
Quoted 25 lines

I know it doesn't matter with current implementation
of fdt_getprop_by_offset_w() but I am not supposed to know about this implementation here in the test. Also, this implementation could change in the future (not planned on my side).

Quoted 11 lines

tests/get_prop_offset_w.c line 74

Quoted 7 lines
tests/get_prop_offset_w.c new file +6 -0
+	if (exp_len < 4)
+		CONFIG("Property \"%s\" should be at least 4 bytes", name);
+
+	/* Modify the property value */
+	modif_val = xmalloc(proplen);
+	memcpy(modif_val, propval, proplen);    

Why malloc() and memcpy()? The whole point of fdt_getprop_by_offset_w() is that you get a writable pointer into the fdt which you can modify in place.

I want to keep the modified value for later comparison.

- modif_val : Current property val + modification.
- Update propval: Current property val.
- Check reading the property with check_get_prop_offset() that the property has been really updated.

Quoted 8 lines
Quoted 4 lines

If instead I use only propval, I use only one buffer and so
- propval = modified value
- check that get check_get_prop_offset() which will also return the propval buffer matches the propval buffer.

Ah, missed that, that makes sense. Personally I'd probably go with a static buffer with the value to write in (and then compare), but either way is fine.

Will keep malloc()/memcpy().

The static buffer needs to know about the lengh of data, at least a maximum allowed length.

Best regards,
Hervé

#69 lore raw

PATCH v3 12/15 libfdt: Introduce fdt_getprop_offset_namelen()

In reply to Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to get an offset to a property based on the node offset and the property name.

Several function exists to get a property based on the node offset and the property name but none of them allows to get the property offset.

Fill the lack and introduce fdt_getprop_offset_namelen() and its simple variant fdt_getprop_offset().

---
 libfdt/fdt_ro.c          | 13 +++++++++++++
 libfdt/libfdt_internal.h |  8 ++++++++
 2 files changed, 21 insertions(+)
libfdt/fdt_ro.c +13 -0
index 856c62f1..50c0a8bc 100644
@@ -536,6 +536,19 @@ const void *fdt_getprop(const void *fdt, int nodeoffset,
 	return fdt_getprop_namelen(fdt, nodeoffset, name, strlen(name), lenp);
 }
 
+int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
+			       const char *name, int namelen)
+{
+	const struct fdt_property *prop;
+	int lenp, offset;
+
+	prop = fdt_get_property_namelen_(fdt, nodeoffset, name, namelen,
+					 &lenp, &offset);
+	if (!prop)
+		return lenp;
+	return offset;
+}
+
 uint32_t fdt_get_phandle(const void *fdt, int nodeoffset)
 {
 	const fdt32_t *php;
libfdt/libfdt_internal.h +8 -0
index 3c83d9a7..e3923629 100644
@@ -26,6 +26,14 @@ uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset,
 int fdt_check_node_offset_(const void *fdt, int offset);
 int fdt_check_prop_offset_(const void *fdt, int offset);
 
+int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
+			       const char *name, int namelen);
+static inline int fdt_getprop_offset(const void *fdt, int nodeoffset,
+				     const char *name)
+{
+	return fdt_getprop_offset_namelen(fdt, nodeoffset, name, strlen(name));
+}
+
 const char *fdt_find_string_len_(const char *strtab, int tabsize, const char *s,
 				 int s_len);
 static inline const char *fdt_find_string_(const char *strtab, int tabsize,
Signature · 1 line
2.55.0
#70 lore raw

Re: [PATCH v3 12/15] libfdt: Introduce fdt_getprop_offset_namelen()

Quoted 4 lines · Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to get an offset to a property based on the node offset and the property name.

Quoted 8 lines

Several function exists to get a property based on the node offset and the property name but none of them allows to get the property offset.

Fill the lack and introduce fdt_getprop_offset_namelen() and its simple variant fdt_getprop_offset().

This seems redundant with fdt_ptr_offset_(), which can trivially get this information when combined with fdt_get_property().

Quoted 52 lines
---
 libfdt/fdt_ro.c          | 13 +++++++++++++
 libfdt/libfdt_internal.h |  8 ++++++++
 2 files changed, 21 insertions(+)
libfdt/fdt_ro.c +13 -0
index 856c62f1..50c0a8bc 100644
@@ -536,6 +536,19 @@ const void *fdt_getprop(const void *fdt, int nodeoffset,
 	return fdt_getprop_namelen(fdt, nodeoffset, name, strlen(name), lenp);
 }
 
+int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
+			       const char *name, int namelen)
+{
+	const struct fdt_property *prop;
+	int lenp, offset;
+
+	prop = fdt_get_property_namelen_(fdt, nodeoffset, name, namelen,
+					 &lenp, &offset);
+	if (!prop)
+		return lenp;
+	return offset;
+}
+
 uint32_t fdt_get_phandle(const void *fdt, int nodeoffset)
 {
 	const fdt32_t *php;
libfdt/libfdt_internal.h +8 -0
index 3c83d9a7..e3923629 100644
@@ -26,6 +26,14 @@ uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset,
 int fdt_check_node_offset_(const void *fdt, int offset);
 int fdt_check_prop_offset_(const void *fdt, int offset);
 
+int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
+			       const char *name, int namelen);
+static inline int fdt_getprop_offset(const void *fdt, int nodeoffset,
+				     const char *name)
+{
+	return fdt_getprop_offset_namelen(fdt, nodeoffset, name, strlen(name));
+}
+
 const char *fdt_find_string_len_(const char *strtab, int tabsize, const char *s,
 				 int s_len);
 static inline const char *fdt_find_string_(const char *strtab, int tabsize,
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#71 lore raw

Re: [PATCH v3 12/15] libfdt: Introduce fdt_getprop_offset_namelen()

Quoted 9 lines · On Mon, 21 Sep 2026 16:07:21 +1000 David Gibson <[email protected]>…
Quoted 8 lines · Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to get an offset to a property based on the node offset and the property name.

Several function exists to get a property based on the node offset and the property name but none of them allows to get the property offset.

Quoted 7 lines
Quoted 4 lines

Fill the lack and introduce fdt_getprop_offset_namelen() and its simple variant fdt_getprop_offset().

This seems redundant with fdt_ptr_offset_(), which can trivially get this information when combined with fdt_get_property().

Indeed, It should be ok using both functions you pointed out.

I will remove fdt_getprop_offset_namelen() introduced here and use directly functions mentionned in the next iteration without wrapping those calls in a new function.

Best regards,
Hervé

#72 lore raw

Re: [PATCH v3 12/15] libfdt: Introduce fdt_getprop_offset_namelen()

Hi David,

Quoted 17 lines · On Tue, 22 Sep 2026 18:25:47 +0200 Herve Codina <[email protected]>…
Quoted 14 lines · On Mon, 21 Sep 2026 16:07:21 +1000 David Gibson <[email protected]>…
Quoted 12 lines · Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to get an offset to a property based on the node offset and the property name.

Several function exists to get a property based on the node offset and the property name but none of them allows to get the property offset.

Fill the lack and introduce fdt_getprop_offset_namelen() and its simple variant fdt_getprop_offset().

Quoted 8 lines
Quoted 2 lines

This seems redundant with fdt_ptr_offset_(), which can trivially get this information when combined with fdt_get_property().

Indeed, It should be ok using both functions you pointed out.

I will remove fdt_getprop_offset_namelen() introduced here and use directly functions mentionned in the next iteration without wrapping those calls in a new function.

I've started to replace fdt_getprop_offset_namelen() by the combination of fdt_ptr_offset_() and fdt_get_property_namelen().

As a reminder fdt_getprop_offset_namelen() I proposed was the following:
--- 8< ---

libfdt/fdt_ro.c const void *fdt_getprop(const void *fdt, int nodeoffset, · line 550

Quoted 12 lines
libfdt/fdt_ro.c +12 -0
+int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
+			       const char *name, int namelen)
+{
+	const struct fdt_property *prop;
+	int lenp, offset;
+
+	prop = fdt_get_property_namelen_(fdt, nodeoffset, name, namelen,
+					 &lenp, &offset);
+	if (!prop)
+		return lenp;
+	return offset;
+}

--- 8< ---

fdt_get_property_namelen_() was called.

Switching to fdt_get_property_namelen() introduces a regression.

fdt_get_property_namelen() calls fdt_get_property_namelen() and this function (without the '_' suffix) performs a check on fdt_version() returning an error on version < 16.

Using it to replace my fdt_getprop_offset_namelen() function will break write-in-place setprop() for dtb version < 16. Indeed, it is used in [1]

[1]: https://lore.kernel.org/devicetree-compiler/[email protected]/#Z31libfdt:fdt_wip.c

Now, several options:

a) No problem if we break dtb version < 16
Ok, I will use directly fdt_get_property_namelen() + fdt_ptr_offset_() to get an offset and remove my fdt_getprop_offset_namelen() wrapper.

b) Keep my fdt_getprop_offset_namelen() function without any modification We support version < 16, problem solved.

c) Keep my fdt_getprop_offset_namelen() but static inline in libfdt_internal.h Export fdt_get_property_namelen_() in libfdt_internal.h and use it in the static inline fdt_getprop_offset_namelen().
This implies that fdt_get_property_namelen_() will be no more static and usable internally out of fdt_ro.c but only the fdt_getprop_offset_namelen() wrapper should be used.

d) Use directly fdt_get_property_namelen_()
Export fdt_get_property_namelen_() in libfdt_internal.h and use it directly to get the offset.
I don't really like this solution. I would prefer to have a wrapper to explicitly return the offset instead of exposing and using directly fdt_get_property_namelen_().

On my side, I would prefer b) as it support version < 16 without the need to expose fdt_get_property_namelen_() out of fdt_ro.c.

I would like to have your opinion on this point.
Is also option b) ok on your side ?

Best regards,
Hervé

#73 lore raw

Re: [PATCH v3 12/15] libfdt: Introduce fdt_getprop_offset_namelen()

Quoted 61 lines · Herve Codina

Hi David,

Quoted 17 lines · On Tue, 22 Sep 2026 18:25:47 +0200 Herve Codina <[email protected]>…
Quoted 14 lines · On Mon, 21 Sep 2026 16:07:21 +1000 David Gibson <[email protected]>…
Quoted 12 lines · Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to get an offset to a property based on the node offset and the property name.

Several function exists to get a property based on the node offset and the property name but none of them allows to get the property offset.

Fill the lack and introduce fdt_getprop_offset_namelen() and its simple variant fdt_getprop_offset().

Quoted 8 lines
Quoted 2 lines

This seems redundant with fdt_ptr_offset_(), which can trivially get this information when combined with fdt_get_property().

Indeed, It should be ok using both functions you pointed out.

I will remove fdt_getprop_offset_namelen() introduced here and use directly functions mentionned in the next iteration without wrapping those calls in a new function.

I've started to replace fdt_getprop_offset_namelen() by the combination of fdt_ptr_offset_() and fdt_get_property_namelen().

As a reminder fdt_getprop_offset_namelen() I proposed was the following:
--- 8< ---

libfdt/fdt_ro.c const void *fdt_getprop(const void *fdt, int nodeoffset, · line 550

Quoted 12 lines
libfdt/fdt_ro.c +12 -0
+int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
+			       const char *name, int namelen)
+{
+	const struct fdt_property *prop;
+	int lenp, offset;
+
+	prop = fdt_get_property_namelen_(fdt, nodeoffset, name, namelen,
+					 &lenp, &offset);
+	if (!prop)
+		return lenp;
+	return offset;
+}

--- 8< ---

fdt_get_property_namelen_() was called.

Switching to fdt_get_property_namelen() introduces a regression.

fdt_get_property_namelen() calls fdt_get_property_namelen() and this function (without the '_' suffix) performs a check on fdt_version() returning an error on version < 16.

Using it to replace my fdt_getprop_offset_namelen() function will break write-in-place setprop() for dtb version < 16. Indeed, it is used in [1]

Quoted 7 lines

[1]: https://lore.kernel.org/devicetree-compiler/[email protected]/#Z31libfdt:fdt_wip.c

Now, several options:

a) No problem if we break dtb version < 16
Ok, I will use directly fdt_get_property_namelen() + fdt_ptr_offset_() to get an offset and remove my fdt_getprop_offset_namelen() wrapper.

So, practically speaking this is probably true. Version before 16 are truly ancient, and versions 1..3 were all before dtbs really caught on.

Quoted 2 lines

b) Keep my fdt_getprop_offset_namelen() function without any modification We support version < 16, problem solved.

Still don't like it.

Quoted 6 lines

c) Keep my fdt_getprop_offset_namelen() but static inline in libfdt_internal.h Export fdt_get_property_namelen_() in libfdt_internal.h and use it in the static inline fdt_getprop_offset_namelen().
This implies that fdt_get_property_namelen_() will be no more static and usable internally out of fdt_ro.c but only the fdt_getprop_offset_namelen() wrapper should be used.

Eh.

Quoted 6 lines

d) Use directly fdt_get_property_namelen_()
Export fdt_get_property_namelen_() in libfdt_internal.h and use it directly to get the offset.
I don't really like this solution. I would prefer to have a wrapper to explicitly return the offset instead of exposing and using directly fdt_get_property_namelen_().

Hm, I think this is my preferred option. libfdt_internal.h exists precisely to "expose" things across modules internally, but without exposing them to external users. Maybe I'm missing something, I don't really see why that's objectionable.

Quoted 9 lines

On my side, I would prefer b) as it support version < 16 without the need to expose fdt_get_property_namelen_() out of fdt_ro.c.

I would like to have your opinion on this point.
Is also option b) ok on your side ?

Best regards,
Hervé

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#74 lore raw

Re: [PATCH v3 12/15] libfdt: Introduce fdt_getprop_offset_namelen()

Hi David,

Quoted 95 lines · On Sun, 25 Oct 2026 13:32:41 +1100 David Gibson <[email protected]>…
Quoted 61 lines · Herve Codina

Hi David,

Quoted 17 lines · On Tue, 22 Sep 2026 18:25:47 +0200 Herve Codina <[email protected]>…
Quoted 14 lines · On Mon, 21 Sep 2026 16:07:21 +1000 David Gibson <[email protected]>…
Quoted 12 lines · Herve Codina

Future operations, such as handling unknown tags on dtb modifications, need to get an offset to a property based on the node offset and the property name.

Several function exists to get a property based on the node offset and the property name but none of them allows to get the property offset.

Fill the lack and introduce fdt_getprop_offset_namelen() and its simple variant fdt_getprop_offset().

Quoted 8 lines
Quoted 2 lines

This seems redundant with fdt_ptr_offset_(), which can trivially get this information when combined with fdt_get_property().

Indeed, It should be ok using both functions you pointed out.

I will remove fdt_getprop_offset_namelen() introduced here and use directly functions mentionned in the next iteration without wrapping those calls in a new function.

I've started to replace fdt_getprop_offset_namelen() by the combination of fdt_ptr_offset_() and fdt_get_property_namelen().

As a reminder fdt_getprop_offset_namelen() I proposed was the following:
--- 8< ---

libfdt/fdt_ro.c const void *fdt_getprop(const void *fdt, int nodeoffset, · line 550

Quoted 12 lines
libfdt/fdt_ro.c +12 -0
+int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
+			       const char *name, int namelen)
+{
+	const struct fdt_property *prop;
+	int lenp, offset;
+
+	prop = fdt_get_property_namelen_(fdt, nodeoffset, name, namelen,
+					 &lenp, &offset);
+	if (!prop)
+		return lenp;
+	return offset;
+}  

--- 8< ---

fdt_get_property_namelen_() was called.

Switching to fdt_get_property_namelen() introduces a regression.

fdt_get_property_namelen() calls fdt_get_property_namelen() and this function (without the '_' suffix) performs a check on fdt_version() returning an error on version < 16.

Using it to replace my fdt_getprop_offset_namelen() function will break write-in-place setprop() for dtb version < 16. Indeed, it is used in [1]

Quoted 7 lines

[1]: https://lore.kernel.org/devicetree-compiler/[email protected]/#Z31libfdt:fdt_wip.c

Now, several options:

a) No problem if we break dtb version < 16
Ok, I will use directly fdt_get_property_namelen() + fdt_ptr_offset_() to get an offset and remove my fdt_getprop_offset_namelen() wrapper.

So, practically speaking this is probably true. Version before 16 are truly ancient, and versions 1..3 were all before dtbs really caught on.

Quoted 2 lines

b) Keep my fdt_getprop_offset_namelen() function without any modification We support version < 16, problem solved.

Still don't like it.

Quoted 6 lines

c) Keep my fdt_getprop_offset_namelen() but static inline in libfdt_internal.h Export fdt_get_property_namelen_() in libfdt_internal.h and use it in the static inline fdt_getprop_offset_namelen().
This implies that fdt_get_property_namelen_() will be no more static and usable internally out of fdt_ro.c but only the fdt_getprop_offset_namelen() wrapper should be used.

Eh.

Quoted 6 lines

d) Use directly fdt_get_property_namelen_()
Export fdt_get_property_namelen_() in libfdt_internal.h and use it directly to get the offset.
I don't really like this solution. I would prefer to have a wrapper to explicitly return the offset instead of exposing and using directly fdt_get_property_namelen_().

Quoted 4 lines

Hm, I think this is my preferred option. libfdt_internal.h exists precisely to "expose" things across modules internally, but without exposing them to external users. Maybe I'm missing something, I don't really see why that's objectionable.

Well, my first feeling was to avoid exposing this function and use a wrapper. I've looked again and indeed the wrapper isn't really worth it.

I will expose (internally) and use directly fdt_get_property_namelen_().

Best regards,
Hervé

#75 lore raw

PATCH v3 13/15 tests: Add wip_func utility

In reply to Herve Codina

wip_func is a test utility allowing to wrap the write inplace functions.

It allows to create tests with custom wip write sequence.

Also the modified dtb is saved allowing to perform later checks on this modified dtb.

---
 tests/Makefile.tests |   3 +-
 tests/meson.build    |   1 +
 tests/wip_func.c     | 127 +++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 130 insertions(+), 1 deletion(-)
 create mode 100644 tests/wip_func.c
tests/Makefile.tests +2 -1
index 0d4d399f..a71c4cbf 100644
@@ -31,7 +31,8 @@ LIB_TESTS_L = get_mem_rsv \
 	check_path check_header check_full \
 	fs_tree1 \
 	truncated_property truncated_string \
-	truncated_memrsv unterminated_memrsv
+	truncated_memrsv unterminated_memrsv \
+	wip_func
 LIB_TESTS = $(LIB_TESTS_L:%=$(TESTS_PREFIX)%)
 
 ifneq ($(STATIC_BUILD),1)
tests/meson.build +1 -0
index dae6a941..e7a88936 100644
@@ -96,6 +96,7 @@ tests = [
   'truncated_string',
   'unterminated_memrsv',
   'utilfdt_test',
+  'wip_func',
 ]
 
 test_deps = [testutil_dep, util_dep, libfdt_dep]
tests/wip_func.c new file +127 -0

127 lines not on this page · raw message

Signature · 1 line
2.55.0
#76 lore raw

Re: [PATCH v3 13/15] tests: Add wip_func utility

Quoted 6 lines · Herve Codina

wip_func is a test utility allowing to wrap the write inplace functions.

It allows to create tests with custom wip write sequence.

Also the modified dtb is saved allowing to perform later checks on this modified dtb.

It's not clear to me what this is useful for that's not already covered by the existing write-in-place tests (nop_node.c, nop_property.c and setprop_inplace.c).

Quoted 172 lines
---
 tests/Makefile.tests |   3 +-
 tests/meson.build    |   1 +
 tests/wip_func.c     | 127 +++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 130 insertions(+), 1 deletion(-)
 create mode 100644 tests/wip_func.c
tests/Makefile.tests +2 -1
index 0d4d399f..a71c4cbf 100644
@@ -31,7 +31,8 @@ LIB_TESTS_L = get_mem_rsv \
 	check_path check_header check_full \
 	fs_tree1 \
 	truncated_property truncated_string \
-	truncated_memrsv unterminated_memrsv
+	truncated_memrsv unterminated_memrsv \
+	wip_func
 LIB_TESTS = $(LIB_TESTS_L:%=$(TESTS_PREFIX)%)
 
 ifneq ($(STATIC_BUILD),1)
tests/meson.build +1 -0
index dae6a941..e7a88936 100644
@@ -96,6 +96,7 @@ tests = [
   'truncated_string',
   'unterminated_memrsv',
   'utilfdt_test',
+  'wip_func',
 ]
 
 test_deps = [testutil_dep, util_dep, libfdt_dep]
tests/wip_func.c new file +127 -0
new file mode 100644
index 00000000..3becc4f1
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: LGPL-2.1-or-later
+/*
+ * libfdt - Flat Device Tree manipulation
+ *	Wrapper wip functions family
+ * Copyright (C) 2026 Herve Codina, Bootlin.
+ */
+
+#include <inttypes.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+#include <stdint.h>
+#include <errno.h>
+
+#include <libfdt.h>
+
+#include "tests.h"
+
+struct args {
+	char *dtb_path;
+	enum {
+		NOP_NODE,
+		NOP_PROP,
+		SET_PROP,
+	} op;
+	char *node_path;
+	char *prop_name;
+	int index;
+	char *value;
+};
+
+const char *usage_txt = "Usage:\n"
+	"  - wip_func <dtb> nop_node <node_path>\n"
+	"  - wip_func <dtb> nop_prop <node_path> <prop_name>\n"
+	"  - wip_func <dtb> set_prop <node_path> <prop_name> <index> <str>\n"
+	;
+
+static void parse_args(struct args *args, int argc, char *argv[])
+{
+	char *endptr;
+
+	memset(args, 0, sizeof(*args));
+
+	if (argc < 3)
+		goto fail;
+
+	args->dtb_path = argv[1];
+
+	if (!strcmp(argv[2], "nop_node")) {
+		args->op = NOP_NODE;
+		if (argc != 4)
+			goto fail;
+		args->node_path = argv[3];
+	} else if (!strcmp(argv[2], "nop_prop")) {
+		args->op = NOP_PROP;
+		if (argc != 5)
+			goto fail;
+		args->node_path = argv[3];
+		args->prop_name = argv[4];
+	} else if (!strcmp(argv[2], "set_prop")) {
+		args->op = SET_PROP;
+		if (argc != 7)
+			goto fail;
+		args->node_path = argv[3];
+		args->prop_name = argv[4];
+		errno = 0;
+		args->index = strtol(argv[5], &endptr, 0);
+		if (*endptr != '\0' || errno)
+			goto fail;
+		args->value = argv[6];
+	} else {
+		goto fail;
+	}
+
+	return;
+
+fail:
+	CONFIG("%s\n", usage_txt);
+}
+
+int main(int argc, char *argv[])
+{
+	struct args args;
+	void *fdt;
+	int node;
+	int err;
+
+	test_init(argc, argv);
+
+	parse_args(&args, argc, argv);
+
+	fdt = load_blob(args.dtb_path);
+
+	node = fdt_path_offset(fdt, args.node_path);
+	if (node < 0)
+		FAIL("Fail to get '%s': %s", args.node_path, fdt_strerror(node));
+
+	switch (args.op) {
+	case NOP_NODE:
+		err = fdt_nop_node(fdt, node);
+		if (err)
+			FAIL("fdt_nop_node('%s'): %s", args.node_path, fdt_strerror(err));
+		break;
+
+	case NOP_PROP:
+		err = fdt_nop_property(fdt, node, args.prop_name);
+		if (err)
+			FAIL("fdt_nop_node('%s', '%s'): %s", args.node_path,
+			     args.prop_name, fdt_strerror(err));
+		break;
+
+	case SET_PROP:
+		err = fdt_setprop_inplace_namelen_partial(fdt, node,
+			args.prop_name, strlen(args.prop_name), args.index,
+			args.value, strlen(args.value) + 1);
+		if (err)
+			FAIL("fdt_setprop_inplace_namelen_partial('%s', '%s', %d, \"%s\"): %s",
+			     args.node_path, args.prop_name, args.index,
+			     args.value, fdt_strerror(err));
+		break;
+	}
+
+	save_blob(args.dtb_path, fdt);
+
+	PASS();
+}
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#77 lore raw

Re: [PATCH v3 13/15] tests: Add wip_func utility

Hi David,

Quoted 12 lines · On Wed, 16 Sep 2026 20:00:40 +1000 David Gibson <[email protected]>…
Quoted 6 lines · Herve Codina

wip_func is a test utility allowing to wrap the write inplace functions.

It allows to create tests with custom wip write sequence.

Also the modified dtb is saved allowing to perform later checks on this modified dtb.

It's not clear to me what this is useful for that's not already covered by the existing write-in-place tests (nop_node.c, nop_property.c and setprop_inplace.c).

Used in tests to check dtb updates when "unknown" tags are involved. See '[PATCH v3 14/15] libfdt: Handle unknown tags on dtb modifications' [0] or full source at [1].

Depending on modification performed, "unknown" tags must be removed or not and the version must be downgrade or not. The test checked for rules defined for modification when "unknown" tags are involved (see patch 14/15 commit log)

I don't think that this could be covered in a simple way by existing write-in-place tests.

[0] https://lore.kernel.org/devicetree-compiler/[email protected]/
[1] https://github.com/bootlin/dtc/blob/2653bb9cd4414780c863051467b5e77eea6e5bdd/tests/run_tests.sh#L590

Best regards,
Hervé

#78 lore raw

PATCH v3 14/15 libfdt: Handle unknown tags on dtb modifications

In reply to Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error.

When the dtb is modified those unknown tags have to be taken into account.

First, depending on the unknown tag location, the item associated with the tag is identified:
- An unknown tag located just after a FDT_BEGIN_NODE is related to the node.

- An unknown tag located just after a FDT_PROP is related to the property.

- An unknown tag out of any node (i.e located before the first FDT_BEGIN_NODE or after the last FDT_END_NODE) is a global tag related to the dtb itself.

Then, if we are allowed to write a dtb containing unknown tags, the following rules are used:
- When a property is modified, tags related to this property are removed and the dtb version is downgraded.

- When a property is removed, tags related to this property are obviously removed. The dtb version is kept unchanged.

- When a property or a node is added, obviously no unknown tags are added and the dtb version is kept unchanged.

- When a node is removed, tags related to this node are obviously removed. The dtb version is kept unchanged.

- Adding, removing or modifying a property is not considered as a node modification and so, those operations have no impacts on unknown tags related to the node. Those node related tags are kept unchanged.

- The only modification considered as a node modification is setting its name. We consider that this operation has no impact on tags related to the node. Here also, those node related tags and the dtb version are kept unchanged.

- Global (dtb related) unknown tags are kept unchanged regardless the modification done.

Implement those rules when a dtb is modified.

---
 libfdt/fdt_rw.c                               | 129 +++++++++++++++++-
 libfdt/fdt_wip.c                              |  28 +++-
 libfdt/libfdt_internal.h                      |   3 +
 tests/run_tests.sh                            |  78 +++++++++++
 ...own_tags_can_skip.fdtput.test.dtb.0.expect |  31 +++++
 ...own_tags_can_skip.fdtput.test.dtb.1.expect |  35 +++++
 ...own_tags_can_skip.fdtput.test.dtb.2.expect |  33 +++++
 ...own_tags_can_skip.fdtput.test.dtb.3.expect |  35 +++++
 ...own_tags_can_skip.fdtput.test.dtb.4.expect |  34 +++++
 ...own_tags_can_skip.fdtput.test.dtb.5.expect |  32 +++++
 ...own_tags_can_skip.fdtput.test.dtb.6.expect |  27 ++++
 ...nknown_tags_can_skip.wip.test.dtb.0.expect |  31 +++++
 ...nknown_tags_can_skip.wip.test.dtb.1.expect |  35 +++++
 ...nknown_tags_can_skip.wip.test.dtb.2.expect |  37 +++++
 ...nknown_tags_can_skip.wip.test.dtb.3.expect |  38 ++++++
 15 files changed, 603 insertions(+), 3 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.3.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.4.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.5.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.6.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.3.expect
libfdt/fdt_rw.c +128 -1
index ceef49b8..87776609 100644
@@ -197,10 +197,69 @@ int fdt_del_mem_rsv(void *fdt, int n)
 	return fdt_splice_mem_rsv_(fdt, re, 1, 0);
 }
 
+static void fdt_nopify_area(void *fdt, int start_offset, int next_offset)
+{
+	int count = (next_offset - start_offset) / sizeof(fdt32_t);
+	fdt32_t fdt32_nop = cpu_to_fdt32(FDT_NOP);
+	fdt32_t *ptr;
+
+	ptr = fdt_offset_ptr_w_(fdt, start_offset);
+	while (count--)
+		*(ptr++) = fdt32_nop;
+};
+
+int fdt_prop_remove_unknown_tags(void *fdt, bool force_inplace,
+				 int prop_offset, bool downgrade_version)
+{
+	int nextoffset, offset;
+	bool is_unknown;
+	uint32_t tag;
+
+	/*
+	 * Only inplace using nopify is supported even if we could use an other
+	 * method involving splices if force_inplace is set to false.
+	 */
+
+	tag = fdt_next_tag(fdt, prop_offset, &nextoffset);
+	if (tag == FDT_END)
+		return nextoffset;
+
+	/*
+	 * Look at all tags related to the current property. I.e. tags after the
+	 * current property and before either the next property, a sub-node  or
+	 * the end of current node
+	 */
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag_(fdt, offset, &nextoffset, &is_unknown);
+		if (tag == FDT_END)
+			return nextoffset;
+
+		/*
+		 * Unknown tags are returned as NOP. Force FDT_NOP to be really
+		 * present in the area to remove the unknown tag and its related
+		 * data. Also, as a tag is removed, downgrade the dtb version
+		 * if asked for.
+		 */
+		if (tag == FDT_NOP) {
+			if (is_unknown) {
+				if (downgrade_version)
+					fdt_downgrade_version(fdt);
+				fdt_nopify_area(fdt, offset, nextoffset);
+			}
+		}
+
+	} while ((tag != FDT_PROP) && (tag != FDT_BEGIN_NODE) &&
+		 (tag != FDT_END_NODE));
+
+	return 0;
+}
+
 static int fdt_resize_property_(void *fdt, int nodeoffset,
 				const char *name, int namelen,
 				int len, struct fdt_property **prop)
 {
+	int prop_offset;
 	int oldlen;
 	int err;
 
@@ -209,6 +268,15 @@ static int fdt_resize_property_(void *fdt, int nodeoffset,
 	if (!*prop)
 		return oldlen;
 
+	/*
+	 * The property is resized. Remove possible unknown tags related to the
+	 * property downgrading the dtb version.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, *prop);
+	err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset, true);
+	if (err)
+		return err;
+
 	if ((err = fdt_splice_struct_(fdt, (*prop)->data, FDT_TAGALIGN(oldlen),
 				      FDT_TAGALIGN(len))))
 		return err;
@@ -217,6 +285,29 @@ static int fdt_resize_property_(void *fdt, int nodeoffset,
 	return 0;
 }
 
+static int fdt_node_skip_unknown_tags(void *fdt, int next)
+{
+	int nextoffset = next;
+	int offset;
+	uint32_t tag;
+
+	/*
+	 * Skip all tags related to the current node. I.e. tags after the
+	 * current node and before either the next property, a sub-node or the
+	 * end of current node.
+	 */
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		if (tag == FDT_END)
+			return nextoffset;
+
+	} while ((tag != FDT_PROP) && (tag != FDT_BEGIN_NODE) &&
+		 (tag != FDT_END_NODE));
+
+	return offset;
+}
+
 static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 			     int namelen, int len, struct fdt_property **prop)
 {
@@ -235,6 +326,15 @@ static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 	if ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
 		return nextoffset;
 
+	/*
+	 * nextoffset it at the first tag after the node.
+	 * Skip possible unknown tags related to the node in order to add the
+	 * property after those tags.
+	 */
+	nextoffset = fdt_node_skip_unknown_tags(fdt, nextoffset);
+	if (nextoffset < 0)
+		return nextoffset;
+
 	namestroff = fdt_find_add_string_(fdt, name, namelen, &allocated);
 	if (namestroff < 0)
 		return namestroff;
@@ -333,11 +433,22 @@ int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
 {
 	struct fdt_property *prop;
 	int err, oldlen, newlen;
+	int prop_offset;
 
 	FDT_RW_PROBE(fdt);
 
 	prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);
 	if (prop) {
+		/*
+		 * The property is going to be modified. Remove possible unknown
+		 * tags related to this property downgrading the dtb version.
+		 */
+		prop_offset = fdt_ptr_offset_(fdt, prop);
+		err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset,
+						   true);
+		if (err)
+			return err;
+
 		newlen = len + oldlen;
 		err = fdt_splice_struct_(fdt, prop->data,
 					 FDT_TAGALIGN(oldlen),
@@ -360,6 +471,8 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)
 {
 	struct fdt_property *prop;
 	int len, proplen;
+	int prop_offset;
+	int err;
 
 	FDT_RW_PROBE(fdt);
 
@@ -367,6 +480,15 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)
 	if (!prop)
 		return len;
 
+	/*
+	 * The property is going to be removed. Remove also possible unknown
+	 * tags related to this property. Keep the dtb version unchanged.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, prop);
+	err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset, false);
+	if (err)
+		return err;
+
 	proplen = sizeof(*prop) + FDT_TAGALIGN(len);
 	return fdt_splice_struct_(fdt, prop, proplen, 0);
 }
@@ -395,7 +517,12 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 	else if (offset != -FDT_ERR_NOTFOUND)
 		return offset;
 
-	/* Try to place the new node after the parent's properties */
+	/*
+	 * Try to place the new node after the parent's properties and unknown
+	 * tags related to those properties.
+	 * Unknown tags are reported as FDT_NOP tags by fdt_next_tag.
+	 * Skipping FDT_NOP tags will correctly skip unknown tags.
+	 */
 	tag = fdt_next_tag(fdt, parentoffset, &nextoffset);
 	/* the fdt_subnode_offset_namelen() should ensure this never hits */
 	if (!can_assume(LIBFDT_FLAWLESS) && (tag != FDT_BEGIN_NODE))
libfdt/fdt_wip.c +26 -2
index c2d7566a..7ca3ffbc 100644
@@ -15,17 +15,30 @@ int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset,
 					uint32_t idx, const void *val,
 					int len)
 {
+	int prop_offset;
 	void *propval;
 	int proplen;
+	int err;
 
-	propval = fdt_getprop_namelen_w(fdt, nodeoffset, name, namelen,
-					&proplen);
+	prop_offset = fdt_getprop_offset_namelen(fdt, nodeoffset, name, namelen);
+	if (prop_offset < 0)
+		return prop_offset;
+
+	propval = fdt_getprop_by_offset_w(fdt, prop_offset, NULL, &proplen);
 	if (!propval)
 		return proplen;
 
 	if ((unsigned)proplen < (len + idx))
 		return -FDT_ERR_NOSPACE;
 
+	/*
+	 * Remove unknown tags related to the property downgrading the dtb
+	 * version.
+	 */
+	err = fdt_prop_remove_unknown_tags(fdt, true, prop_offset, true);
+	if (err)
+		return err;
+
 	memcpy((char *)propval + idx, val, len);
 	return 0;
 }
@@ -59,12 +72,23 @@ static void fdt_nop_region_(void *start, int len)
 int fdt_nop_property(void *fdt, int nodeoffset, const char *name)
 {
 	struct fdt_property *prop;
+	int prop_offset;
 	int len;
+	int err;
 
 	prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
 	if (!prop)
 		return len;
 
+	/*
+	 * The property is going to be removed (nopified). Remove unknown tags
+	 * related to this property. Keep the dtb version unchanged.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, prop);
+	err = fdt_prop_remove_unknown_tags(fdt, true, prop_offset, false);
+	if (err)
+		return err;
+
 	fdt_nop_region_(prop, len + sizeof(*prop));
 
 	return 0;
libfdt/libfdt_internal.h +3 -0
index e3923629..ce128fda 100644
@@ -26,6 +26,9 @@ uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset,
 int fdt_check_node_offset_(const void *fdt, int offset);
 int fdt_check_prop_offset_(const void *fdt, int offset);
 
+int fdt_prop_remove_unknown_tags(void *fdt, bool force_inplace,
+				 int prop_offset, bool downgrade_version);
+
 int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
 			       const char *name, int namelen);
 static inline int fdt_getprop_offset(const void *fdt, int nodeoffset,
tests/run_tests.sh +78 -0

90 lines not on this page · raw message

tests/unknown_tags_can_skip.fdtput.test.dtb.0.expect new file +31 -0
new file mode 100644
index 00000000..75883593
@@ -0,0 +1,31 @@
+/dts-v1/;
+// version:		4294967295
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.1.expect new file +35 -0
new file mode 100644
index 00000000..b4d3ae29
@@ -0,0 +1,35 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "vwxyz";
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.2.expect new file +33 -0
new file mode 100644
index 00000000..a196bed3
@@ -0,0 +1,33 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    tst-fdtput {
+    };
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.3.expect new file +35 -0
new file mode 100644
index 00000000..52faa1dd
@@ -0,0 +1,35 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    tst-fdtput {
+        n2 {
+        };
+    };
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.4.expect new file +34 -0
new file mode 100644
index 00000000..1ddc694b
@@ -0,0 +1,34 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.5.expect new file +32 -0
new file mode 100644
index 00000000..f955ac1c
@@ -0,0 +1,32 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-tst-fdtput = "Test fdtput";
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.6.expect new file +27 -0
new file mode 100644
index 00000000..59247478
@@ -0,0 +1,27 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.wip.test.dtb.0.expect new file +31 -0
new file mode 100644
index 00000000..75883593
@@ -0,0 +1,31 @@
+/dts-v1/;
+// version:		4294967295
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.wip.test.dtb.1.expect new file +35 -0
new file mode 100644
index 00000000..2a0dd4a0
@@ -0,0 +1,35 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "vwxy";
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.wip.test.dtb.2.expect new file +37 -0
new file mode 100644
index 00000000..bc08885b
@@ -0,0 +1,37 @@
+/dts-v1/;
+// version:		4294967295
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.wip.test.dtb.3.expect new file +38 -0
new file mode 100644
index 00000000..aa6e9394
@@ -0,0 +1,38 @@
+/dts-v1/;
+// version:		4294967295
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
Signature · 1 line
2.55.0
#79 lore raw

Re: [PATCH v3 14/15] libfdt: Handle unknown tags on dtb modifications

Quoted 11 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error.

When the dtb is modified those unknown tags have to be taken into account.

First, depending on the unknown tag location, the item associated with the tag is identified:
- An unknown tag located just after a FDT_BEGIN_NODE is related to the node.

Quoted 6 lines

- An unknown tag located just after a FDT_PROP is related to the property.

- An unknown tag out of any node (i.e located before the first FDT_BEGIN_NODE or after the last FDT_END_NODE) is a global tag related to the dtb itself.

Since we rely on those constraings here, it seems like those should probably be written into the structured tag specs / description. Which to my mind strengthens the case for explicitly calling them "metadata tags".

Quoted 4 lines

Then, if we are allowed to write a dtb containing unknown tags, the following rules are used:
- When a property is modified, tags related to this property are removed and the dtb version is downgraded.

Hmm. This seems weird to me, but maybe that's because we haven't pinned down in specs / docs what the interaction is between new skippable tags and the overall version.

My assumption had been that tags - even structured tags - newer than vNNN must not appear in a dtb with version == NNN (but they can appear in a dtb with last_compat_version < NNN).

With that model, this seems kind of backwards - downgrading the version would require removing newer tags throughout the tree, rather than removing some tags causing the version to be downgraded.

Quoted 5 lines

- When a property is removed, tags related to this property are obviously removed. The dtb version is kept unchanged.

- When a property or a node is added, obviously no unknown tags are added and the dtb version is kept unchanged.

This seems weird to me in combination with the behaviour on modification. The previous one makes more sense to me in the context of an alternative model: newer versions might *require* certain metadata tags are present. But in that case this part doesn't work.

Quoted 6 lines

- When a node is removed, tags related to this node are obviously removed. The dtb version is kept unchanged.

- Adding, removing or modifying a property is not considered as a node modification and so, those operations have no impacts on unknown tags related to the node. Those node related tags are kept unchanged.

That.. certainly constrains what it's possible to put in skippable tags, in a way that we'd have to document, though it's not especially easy to do so.

Quoted 46 lines

- The only modification considered as a node modification is setting its name. We consider that this operation has no impact on tags related to the node. Here also, those node related tags and the dtb version are kept unchanged.

- Global (dtb related) unknown tags are kept unchanged regardless the modification done.

Implement those rules when a dtb is modified.

---
 libfdt/fdt_rw.c                               | 129 +++++++++++++++++-
 libfdt/fdt_wip.c                              |  28 +++-
 libfdt/libfdt_internal.h                      |   3 +
 tests/run_tests.sh                            |  78 +++++++++++
 ...own_tags_can_skip.fdtput.test.dtb.0.expect |  31 +++++
 ...own_tags_can_skip.fdtput.test.dtb.1.expect |  35 +++++
 ...own_tags_can_skip.fdtput.test.dtb.2.expect |  33 +++++
 ...own_tags_can_skip.fdtput.test.dtb.3.expect |  35 +++++
 ...own_tags_can_skip.fdtput.test.dtb.4.expect |  34 +++++
 ...own_tags_can_skip.fdtput.test.dtb.5.expect |  32 +++++
 ...own_tags_can_skip.fdtput.test.dtb.6.expect |  27 ++++
 ...nknown_tags_can_skip.wip.test.dtb.0.expect |  31 +++++
 ...nknown_tags_can_skip.wip.test.dtb.1.expect |  35 +++++
 ...nknown_tags_can_skip.wip.test.dtb.2.expect |  37 +++++
 ...nknown_tags_can_skip.wip.test.dtb.3.expect |  38 ++++++
 15 files changed, 603 insertions(+), 3 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.3.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.4.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.5.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.6.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.3.expect
libfdt/fdt_rw.c +0 -0
index ceef49b8..87776609 100644

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 200

Quoted 4 lines
libfdt/fdt_rw.c +1 -0
@@ -197,10 +197,69 @@ int fdt_del_mem_rsv(void *fdt, int n)
 	return fdt_splice_mem_rsv_(fdt, re, 1, 0);
 }
 
+static void fdt_nopify_area(void *fdt, int start_offset, int next_offset)

This should be written in terms of fdt_nop_region_() from fdt_wip.c (or else the other way around). It should also probably live in fdt_wip.c.

Quoted 10 lines
libfdt/fdt_rw.c +10 -0
+{
+	int count = (next_offset - start_offset) / sizeof(fdt32_t);
+	fdt32_t fdt32_nop = cpu_to_fdt32(FDT_NOP);
+	fdt32_t *ptr;
+
+	ptr = fdt_offset_ptr_w_(fdt, start_offset);
+	while (count--)
+		*(ptr++) = fdt32_nop;
+};
+

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 220

Quoted 10 lines
libfdt/fdt_rw.c +10 -0
+int fdt_prop_remove_unknown_tags(void *fdt, bool force_inplace,
+				 int prop_offset, bool downgrade_version)
+{
+	int nextoffset, offset;
+	bool is_unknown;
+	uint32_t tag;
+
+	/*
+	 * Only inplace using nopify is supported even if we could use an other
+	 * method involving splices if force_inplace is set to false.

This comment is fairly hard to understand without reading a lot of the rest of the patch first. It's also really not ideal - when we're in the fdt_rw context, we want to be able to really truly remove the stale tags, not just NOP them.

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 226

Quoted 6 lines
libfdt/fdt_rw.c +6 -0
+	 */
+
+	tag = fdt_next_tag(fdt, prop_offset, &nextoffset);
+	if (tag == FDT_END)
+		return nextoffset;
+

Should this error out if tag != FDT_PROP?

Quoted 8 lines
libfdt/fdt_rw.c +8 -0
+	/*
+	 * Look at all tags related to the current property. I.e. tags after the
+	 * current property and before either the next property, a sub-node  or
+	 * the end of current node
+	 */
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag_(fdt, offset, &nextoffset, &is_unknown);

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 244

Quoted 10 lines
libfdt/fdt_rw.c +10 -0
+		if (tag == FDT_END)
+			return nextoffset;
+
+		/*
+		 * Unknown tags are returned as NOP. Force FDT_NOP to be really
+		 * present in the area to remove the unknown tag and its related
+		 * data. Also, as a tag is removed, downgrade the dtb version
+		 * if asked for.
+		 */
+		if (tag == FDT_NOP) {

It seems to me this would be more natural using fdt_next_tag_all() (or whatever it ends up being called) and handling the nopping in the 'default' case.

Quoted 38 lines
libfdt/fdt_rw.c +23 -0
+			if (is_unknown) {
+				if (downgrade_version)
+					fdt_downgrade_version(fdt);
+				fdt_nopify_area(fdt, offset, nextoffset);
+			}
+		}
+
+	} while ((tag != FDT_PROP) && (tag != FDT_BEGIN_NODE) &&
+		 (tag != FDT_END_NODE));
+
+	return 0;
+}
+
 static int fdt_resize_property_(void *fdt, int nodeoffset,
 				const char *name, int namelen,
 				int len, struct fdt_property **prop)
 {
+	int prop_offset;
 	int oldlen;
 	int err;
 
@@ -209,6 +268,15 @@ static int fdt_resize_property_(void *fdt, int nodeoffset,
 	if (!*prop)
 		return oldlen;
 
+	/*
+	 * The property is resized. Remove possible unknown tags related to the
+	 * property downgrading the dtb version.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, *prop);
+	err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset, true);
+	if (err)
+		return err;
+
 	if ((err = fdt_splice_struct_(fdt, (*prop)->data, FDT_TAGALIGN(oldlen),
 				      FDT_TAGALIGN(len))))
 		return err;

libfdt/fdt_rw.c static int fdt_resize_property_(void *fdt, int nodeoffset, · line 288

Quoted 4 lines
libfdt/fdt_rw.c +1 -0
@@ -217,6 +285,29 @@ static int fdt_resize_property_(void *fdt, int nodeoffset,
 	return 0;
 }
 
+static int fdt_node_skip_unknown_tags(void *fdt, int next)

Is 'next' the offset of a node? If so it should probably have a more suggestive name.

Quoted 50 lines
libfdt/fdt_rw.c +32 -0
+{
+	int nextoffset = next;
+	int offset;
+	uint32_t tag;
+
+	/*
+	 * Skip all tags related to the current node. I.e. tags after the
+	 * current node and before either the next property, a sub-node or the
+	 * end of current node.
+	 */
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		if (tag == FDT_END)
+			return nextoffset;
+
+	} while ((tag != FDT_PROP) && (tag != FDT_BEGIN_NODE) &&
+		 (tag != FDT_END_NODE));
+
+	return offset;
+}
+
 static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 			     int namelen, int len, struct fdt_property **prop)
 {
@@ -235,6 +326,15 @@ static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 	if ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
 		return nextoffset;
 
+	/*
+	 * nextoffset it at the first tag after the node.
+	 * Skip possible unknown tags related to the node in order to add the
+	 * property after those tags.
+	 */
+	nextoffset = fdt_node_skip_unknown_tags(fdt, nextoffset);
+	if (nextoffset < 0)
+		return nextoffset;
+
 	namestroff = fdt_find_add_string_(fdt, name, namelen, &allocated);
 	if (namestroff < 0)
 		return namestroff;
@@ -333,11 +433,22 @@ int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
 {
 	struct fdt_property *prop;
 	int err, oldlen, newlen;
+	int prop_offset;
 
 	FDT_RW_PROBE(fdt);
 
 	prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);

libfdt/fdt_rw.c int fdt_appendprop(void *fdt, int nodeoffset, const char *name, · line 450

Quoted 10 lines
libfdt/fdt_rw.c +9 -0
 	if (prop) {
+		/*
+		 * The property is going to be modified. Remove possible unknown
+		 * tags related to this property downgrading the dtb version.
+		 */
+		prop_offset = fdt_ptr_offset_(fdt, prop);
+		err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset,
+						   true);
+		if (err)
+			return err;

Just NOPing the unknown tags isn't ideal here. This function can already insert/remove stuff from the structure block, so removing the tags entirely would be preferable.

Quoted 15 lines
libfdt/fdt_rw.c +2 -0
 		newlen = len + oldlen;
 		err = fdt_splice_struct_(fdt, prop->data,
 					 FDT_TAGALIGN(oldlen),
@@ -360,6 +471,8 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)
 {
 	struct fdt_property *prop;
 	int len, proplen;
+	int prop_offset;
+	int err;
 
 	FDT_RW_PROBE(fdt);
 
@@ -367,6 +480,15 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)
 	if (!prop)

libfdt/fdt_rw.c int fdt_delprop(void *fdt, int nodeoffset, const char *name) · line 490

Quoted 10 lines
libfdt/fdt_rw.c +8 -0
 		return len;
 
+	/*
+	 * The property is going to be removed. Remove also possible unknown
+	 * tags related to this property. Keep the dtb version unchanged.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, prop);
+	err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset, false);
+	if (err)
+		return err;

Here, only NOPing the tags is worse, since delprop is expected to entirely remove the property without leaving NOPs.

Also.. just NOPing unknown tags isn't correct either. The property is being removed, so *all* the associated skippable tags should be removed as well (ideally with a single fdt_splice_struct_()).

Quoted 5 lines
libfdt/fdt_rw.c +1 -0
+
 	proplen = sizeof(*prop) + FDT_TAGALIGN(len);
 	return fdt_splice_struct_(fdt, prop, proplen, 0);
 }

libfdt/fdt_rw.c int fdt_add_subnode_namelen(void *fdt, int parentoffset, · line 524

Quoted 9 lines
libfdt/fdt_rw.c +5 -1
@@ -395,7 +517,12 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 	else if (offset != -FDT_ERR_NOTFOUND)
 		return offset;
 
-	/* Try to place the new node after the parent's properties */
+	/*
+	 * Try to place the new node after the parent's properties and unknown
+	 * tags related to those properties.
+	 * Unknown tags are reported as FDT_NOP tags by fdt_next_tag.
+	 * Skipping FDT_NOP tags will correctly skip unknown tags.

True, but I think it would be clearer and more robust to explicitly look for an FDT_BEGIN_NODE or FDT_END_NODE tag instead.

Quoted 25 lines
libfdt/fdt_rw.c +1 -0
+	 */
 	tag = fdt_next_tag(fdt, parentoffset, &nextoffset);
 	/* the fdt_subnode_offset_namelen() should ensure this never hits */
 	if (!can_assume(LIBFDT_FLAWLESS) && (tag != FDT_BEGIN_NODE))
libfdt/fdt_wip.c +7 -2
index c2d7566a..7ca3ffbc 100644
@@ -15,17 +15,30 @@ int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset,
 					uint32_t idx, const void *val,
 					int len)
 {
+	int prop_offset;
 	void *propval;
 	int proplen;
+	int err;
 
-	propval = fdt_getprop_namelen_w(fdt, nodeoffset, name, namelen,
-					&proplen);
+	prop_offset = fdt_getprop_offset_namelen(fdt, nodeoffset, name, namelen);
+	if (prop_offset < 0)
+		return prop_offset;
+
+	propval = fdt_getprop_by_offset_w(fdt, prop_offset, NULL, &proplen);
 	if (!propval)

libfdt/fdt_wip.c int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset, · line 38

Quoted 10 lines
libfdt/fdt_wip.c +5 -0
 		return proplen;
 
 	if ((unsigned)proplen < (len + idx))
 		return -FDT_ERR_NOSPACE;
 
+	/*
+	 * Remove unknown tags related to the property downgrading the dtb
+	 * version.
+	 */
+	err = fdt_prop_remove_unknown_tags(fdt, true, prop_offset, true);

Functions in fdt_wip.c should not depend on functions in fdw_rw.c. Part of the reason for organising things this way is so that a client only uses write-in-place functions, the linker will omit the more complex full read-write code (even if an old or limited linker that doesn't do e.g. function sections). fdt_rw.c by contrast _is_ permitted to rely on fdt_wip.c

Quoted 16 lines
libfdt/fdt_wip.c +5 -0
+	if (err)
+		return err;
+
 	memcpy((char *)propval + idx, val, len);
 	return 0;
 }
@@ -59,12 +72,23 @@ static void fdt_nop_region_(void *start, int len)
 int fdt_nop_property(void *fdt, int nodeoffset, const char *name)
 {
 	struct fdt_property *prop;
+	int prop_offset;
 	int len;
+	int err;
 
 	prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
 	if (!prop)

libfdt/fdt_wip.c static void fdt_nop_region_(void *start, int len) · line 90

Quoted 10 lines
libfdt/fdt_wip.c +8 -0
 		return len;
 
+	/*
+	 * The property is going to be removed (nopified). Remove unknown tags
+	 * related to this property. Keep the dtb version unchanged.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, prop);
+	err = fdt_prop_remove_unknown_tags(fdt, true, prop_offset, false);
+	if (err)
+		return err;

Similar to fdt_delprop() this needs to NOP *all* the properties associated with the property we're killing, not just the unknown ones (again, ideally with a single fdt_nop_region_()).

Quoted 23 lines
libfdt/fdt_wip.c +0 -0
 	fdt_nop_region_(prop, len + sizeof(*prop));
 
 	return 0;
libfdt/libfdt_internal.h +3 -0
index e3923629..ce128fda 100644
@@ -26,6 +26,9 @@ uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset,
 int fdt_check_node_offset_(const void *fdt, int offset);
 int fdt_check_prop_offset_(const void *fdt, int offset);
 
+int fdt_prop_remove_unknown_tags(void *fdt, bool force_inplace,
+				 int prop_offset, bool downgrade_version);
+
 int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
 			       const char *name, int namelen);
 static inline int fdt_getprop_offset(const void *fdt, int nodeoffset,
tests/run_tests.sh +0 -0
index 419a24d8..980ed6a0 100755
@@ -586,6 +586,34 @@ libfdt_tests () {
 		unknown_tags_no_skip.dtb; do

tests/run_tests.sh libfdt_tests () { · line 596

Quoted 10 lines
tests/run_tests.sh +8 -0
 	run_test check_full -n $bad
     done
+
+    # Check inplace modification with "unknown" tags that can be skipped
+    dtb=unknown_tags_can_skip.wip.test.dtb
+    cp unknown_tags_can_skip.dtb $dtb
+    base_run_test wrap_fdtdump $dtb $dtb.0.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.0.out
+    base_run_test check_diff $dtb.0.out "$SRCDIR/$dtb.0.expect"

As noted earlier in the series, tests of binary-level behaviour shouldn't depend on specific source formatting. The use of wip_func to essentially do some of the test steps in shell seems clumsy to me - I think this would be nicer as explicit tests written in C which directly look at the binary dtb contents.

Quoted 29 lines
tests/run_tests.sh +22 -0
+    run_test wip_func $dtb set_prop / prop-str 0 "vwxy"
+    base_run_test wrap_fdtdump $dtb $dtb.1.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.1.out
+    base_run_test check_diff $dtb.1.out "$SRCDIR/$dtb.1.expect"
+
+    cp unknown_tags_can_skip.dtb $dtb
+    run_test wip_func $dtb nop_prop /subnode2 prop-int1
+    base_run_test wrap_fdtdump $dtb $dtb.2.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.2.out
+    base_run_test check_diff $dtb.2.out "$SRCDIR/$dtb.2.expect"
+
+    cp unknown_tags_can_skip.dtb $dtb
+    run_test wip_func $dtb nop_node /subnode2/subsubnode
+    base_run_test wrap_fdtdump $dtb $dtb.3.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.3.out
+    base_run_test check_diff $dtb.3.out "$SRCDIR/$dtb.3.expect"
 }
 
 dtc_tests () {
@@ -1045,6 +1073,56 @@ fdtput_tests () {
     run_wrap_error_test $DTPUT $dtb -d /chosen   non-existent-prop
 
     # TODO: Add tests for verbose mode?
+
+    # Modify a dtb containing some "unknown" tags that can be skipped
+    dtb=unknown_tags_can_skip.fdtput.test.dtb

tests/run_tests.sh fdtput_tests () { · line 1088

Quoted 10 lines
tests/run_tests.sh +10 -0
+    cp unknown_tags_can_skip.dtb $dtb
+    base_run_test wrap_fdtdump $dtb $dtb.0.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.0.out
+    base_run_test check_diff $dtb.0.out "$SRCDIR/$dtb.0.expect"
+    run_fdtput_test "vwxyz" $dtb / prop-str -ts "vwxyz"
+    base_run_test wrap_fdtdump $dtb $dtb.1.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.1.out
+    base_run_test check_diff $dtb.1.out "$SRCDIR/$dtb.1.expect"

Doing these as fdtput tests again seems kind of clumsy, unless the point is explicitly to check the fdtput utility's behaviour. The core library functionality should be tested directly without introducing extra layers.

Quoted 476 lines
tests/run_tests.sh +35 -0
+    cp unknown_tags_can_skip.dtb $dtb
+    run_wrap_test $DTPUT $dtb -c /tst-fdtput
+    base_run_test wrap_fdtdump $dtb $dtb.2.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.2.out
+    base_run_test check_diff $dtb.2.out "$SRCDIR/$dtb.2.expect"
+    run_wrap_test $DTPUT $dtb -c /tst-fdtput/n1 /tst-fdtput/n2 /tst-fdtput/n3
+    run_wrap_test $DTPUT $dtb -r /tst-fdtput/n1 /tst-fdtput/n3
+    run_fdtget_test "n2" $dtb -l  /tst-fdtput
+    base_run_test wrap_fdtdump $dtb $dtb.3.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.3.out
+    base_run_test check_diff $dtb.3.out "$SRCDIR/$dtb.3.expect"
+
+    cp unknown_tags_can_skip.dtb $dtb
+    run_wrap_test $DTPUT $dtb -d / prop-str
+    run_fdtget_test "prop-int" $dtb -p  /
+    base_run_test wrap_fdtdump $dtb $dtb.4.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.4.out
+    base_run_test check_diff $dtb.4.out "$SRCDIR/$dtb.4.expect"
+
+    cp unknown_tags_can_skip.dtb $dtb
+    run_wrap_test $DTPUT $dtb /subnode2 prop-tst-fdtput -ts "Test fdtput"
+    base_run_test wrap_fdtdump $dtb $dtb.5.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.5.out
+    base_run_test check_diff $dtb.5.out "$SRCDIR/$dtb.5.expect"
+
+    cp unknown_tags_can_skip.dtb $dtb
+    run_wrap_test $DTPUT $dtb -r /subnode2/subsubnode
+    base_run_test wrap_fdtdump $dtb $dtb.6.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.6.out
+    base_run_test check_diff $dtb.6.out "$SRCDIR/$dtb.6.expect"
 }
 
 utilfdt_tests () {
tests/unknown_tags_can_skip.fdtput.test.dtb.0.expect new file +31 -0
new file mode 100644
index 00000000..75883593
@@ -0,0 +1,31 @@
+/dts-v1/;
+// version:		4294967295
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.1.expect new file +35 -0
new file mode 100644
index 00000000..b4d3ae29
@@ -0,0 +1,35 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "vwxyz";
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.2.expect new file +33 -0
new file mode 100644
index 00000000..a196bed3
@@ -0,0 +1,33 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    tst-fdtput {
+    };
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.3.expect new file +35 -0
new file mode 100644
index 00000000..52faa1dd
@@ -0,0 +1,35 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    tst-fdtput {
+        n2 {
+        };
+    };
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.4.expect new file +34 -0
new file mode 100644
index 00000000..1ddc694b
@@ -0,0 +1,34 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.5.expect new file +32 -0
new file mode 100644
index 00000000..f955ac1c
@@ -0,0 +1,32 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-tst-fdtput = "Test fdtput";
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.fdtput.test.dtb.6.expect new file +27 -0
new file mode 100644
index 00000000..59247478
@@ -0,0 +1,27 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.wip.test.dtb.0.expect new file +31 -0
new file mode 100644
index 00000000..75883593
@@ -0,0 +1,31 @@
+/dts-v1/;
+// version:		4294967295
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.wip.test.dtb.1.expect new file +35 -0
new file mode 100644
index 00000000..2a0dd4a0
@@ -0,0 +1,35 @@
+/dts-v1/;
+// version:		17
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "vwxy";
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    // [NOP]
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.wip.test.dtb.2.expect new file +37 -0
new file mode 100644
index 00000000..bc08885b
@@ -0,0 +1,37 @@
+/dts-v1/;
+// version:		4294967295
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        prop-int2 = <0x00032022>;
+        subsubnode {
+            // Unknown tag ignored: 0xe0000000, data len 8 0000123000001231
+            prop-bool;
+        };
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
tests/unknown_tags_can_skip.wip.test.dtb.3.expect new file +38 -0
new file mode 100644
index 00000000..aa6e9394
@@ -0,0 +1,38 @@
+/dts-v1/;
+// version:		4294967295
+// last_comp_version:	16
+
+// Unknown tag ignored: 0xd0000000, data len 4 00000001
+/ {
+    // Unknown tag ignored: 0xc0000000, data len 0
+    prop-int = <0x00003201>;
+    // Unknown tag ignored: 0xd0000000, data len 4 00000110
+    prop-str = "abcd";
+    // Unknown tag ignored: 0xe0000000, data len 8 0000012000000121
+    // Unknown tag ignored: 0xf0000000, data len 3 101112
+    subnode1 {
+        prop-int = <0x00006401 0x00006402>;
+        // Unknown tag ignored: 0xc0000000, data len 0
+    };
+    subnode2 {
+        // Unknown tag ignored: 0xd0000000, data len 4 00000121
+        prop-int1 = <0x00064020 0x00064021>;
+        // Unknown tag ignored: 0xe0000000, data len 8 0000122000001221
+        prop-int2 = <0x00032022>;
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // [NOP]
+        // Unknown tag ignored: 0xf0000000, data len 3 212223
+    };
+    // Unknown tag ignored: 0xf0000000, data len 4 31323334
+};
+// Unknown tag ignored: 0xd0000000, data len 4 00000002
+// Unknown tag ignored: 0xf0000000, data len 2 4041
Signature · 1 line
2.55.0
Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson
#80 lore raw

Re: [PATCH v3 14/15] libfdt: Handle unknown tags on dtb modifications

Quoted 15 lines · On Mon, 21 Sep 2026 16:06:13 +1000 David Gibson <[email protected]>…
Quoted 14 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error.

When the dtb is modified those unknown tags have to be taken into account.

First, depending on the unknown tag location, the item associated with the tag is identified:
- An unknown tag located just after a FDT_BEGIN_NODE is related to the node.

- An unknown tag located just after a FDT_PROP is related to the property.

Quoted 8 lines
Quoted 3 lines

- An unknown tag out of any node (i.e located before the first FDT_BEGIN_NODE or after the last FDT_END_NODE) is a global tag related to the dtb itself.

Since we rely on those constraings here, it seems like those should probably be written into the structured tag specs / description. Which to my mind strengthens the case for explicitly calling them "metadata tags".

Yes this need to be documented somewhere but where?
In the end it should be present in the Devicetree Specification.

Related to the term "metadata" I am not sure that all future tags will be "metadata" tags. Especially global tags (out of any nodes). At this point we have "skippable" tags without any more knowledge.

But anyway, I will use the term "metadata".

Quoted 10 lines
Quoted 5 lines

Then, if we are allowed to write a dtb containing unknown tags, the following rules are used:
- When a property is modified, tags related to this property are removed and the dtb version is downgraded.

Hmm. This seems weird to me, but maybe that's because we haven't pinned down in specs / docs what the interaction is between new skippable tags and the overall version.

Quoted 7 lines

My assumption had been that tags - even structured tags - newer than vNNN must not appear in a dtb with version == NNN (but they can appear in a dtb with last_compat_version < NNN).

With that model, this seems kind of backwards - downgrading the version would require removing newer tags throughout the tree, rather than removing some tags causing the version to be downgraded.

The discussion which led to this mechanism is available at [1].

If all tags are removed, there is no way to forward a dtb with unknown tags from a bootloader point of view (support for Vnnn in bootloader) to a Linux Kernel having support for newer dtb version.

[1] https://lore.kernel.org/all/CAL_JsqLRrbZje_gGZPBDni6StFa+6rdiECtk49on8VfkP7CDvw@mail.gmail.com/

Quoted 11 lines
Quoted 6 lines

- When a property is removed, tags related to this property are obviously removed. The dtb version is kept unchanged.

- When a property or a node is added, obviously no unknown tags are added and the dtb version is kept unchanged.

This seems weird to me in combination with the behaviour on modification. The previous one makes more sense to me in the context of an alternative model: newer versions might *require* certain metadata tags are present. But in that case this part doesn't work.

Suppose a tag defined at Vnnn. An older libfdt can add a property to a node but cannot add the tag defined at Vnnn. Indeed this tag is unknown.

At a given version, libfdt cannot add unknown tags and so as unknown tags are not involved when a property is added, there is no need to dowgrade the version.

Quoted 11 lines
Quoted 7 lines

- When a node is removed, tags related to this node are obviously removed. The dtb version is kept unchanged.

- Adding, removing or modifying a property is not considered as a node modification and so, those operations have no impacts on unknown tags related to the node. Those node related tags are kept unchanged.

That.. certainly constrains what it's possible to put in skippable tags, in a way that we'd have to document, though it's not especially easy to do so.

Yes, and that's why the FDT_BEGIN_NODE_REF tag defined by the support for addon cannot be skipped. If this tag is skipped by older libfdt weird behavior will happen. The old libfdt will think that the root node is a subnode of an orphan node.

top level dtb:
FDT_BEGIN_NODE_REF <--- Skip by old libfdt
FDT_BEGIN_NODE <---- Root node identified by old libfdt

To avoid that FDT_BEGIN_NODE_REF cannot be skipped and so old libfdt will report an error: Unknown tag which cannot be skipped.

Quoted 73 lines
Quoted 47 lines

- The only modification considered as a node modification is setting its name. We consider that this operation has no impact on tags related to the node. Here also, those node related tags and the dtb version are kept unchanged.

- Global (dtb related) unknown tags are kept unchanged regardless the modification done.

Implement those rules when a dtb is modified.

---
 libfdt/fdt_rw.c                               | 129 +++++++++++++++++-
 libfdt/fdt_wip.c                              |  28 +++-
 libfdt/libfdt_internal.h                      |   3 +
 tests/run_tests.sh                            |  78 +++++++++++
 ...own_tags_can_skip.fdtput.test.dtb.0.expect |  31 +++++
 ...own_tags_can_skip.fdtput.test.dtb.1.expect |  35 +++++
 ...own_tags_can_skip.fdtput.test.dtb.2.expect |  33 +++++
 ...own_tags_can_skip.fdtput.test.dtb.3.expect |  35 +++++
 ...own_tags_can_skip.fdtput.test.dtb.4.expect |  34 +++++
 ...own_tags_can_skip.fdtput.test.dtb.5.expect |  32 +++++
 ...own_tags_can_skip.fdtput.test.dtb.6.expect |  27 ++++
 ...nknown_tags_can_skip.wip.test.dtb.0.expect |  31 +++++
 ...nknown_tags_can_skip.wip.test.dtb.1.expect |  35 +++++
 ...nknown_tags_can_skip.wip.test.dtb.2.expect |  37 +++++
 ...nknown_tags_can_skip.wip.test.dtb.3.expect |  38 ++++++
 15 files changed, 603 insertions(+), 3 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.3.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.4.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.5.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.6.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.3.expect
libfdt/fdt_rw.c +0 -0
index ceef49b8..87776609 100644

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 200

Quoted 4 lines
libfdt/fdt_rw.c +1 -0
@@ -197,10 +197,69 @@ int fdt_del_mem_rsv(void *fdt, int n)
 	return fdt_splice_mem_rsv_(fdt, re, 1, 0);
 }
 
+static void fdt_nopify_area(void *fdt, int start_offset, int next_offset)  

This should be written in terms of fdt_nop_region_() from fdt_wip.c (or else the other way around). It should also probably live in fdt_wip.c.

Quoted 17 lines
libfdt/fdt_rw.c +17 -0
+{
+	int count = (next_offset - start_offset) / sizeof(fdt32_t);
+	fdt32_t fdt32_nop = cpu_to_fdt32(FDT_NOP);
+	fdt32_t *ptr;
+
+	ptr = fdt_offset_ptr_w_(fdt, start_offset);
+	while (count--)
+		*(ptr++) = fdt32_nop;
+};
+
+int fdt_prop_remove_unknown_tags(void *fdt, bool force_inplace,
+				 int prop_offset, bool downgrade_version)
+{
+	int nextoffset, offset;
+	bool is_unknown;
+	uint32_t tag;
+
Quoted 8 lines

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 220

Quoted 3 lines
libfdt/fdt_rw.c +3 -0
+	/*
+	 * Only inplace using nopify is supported even if we could use an other
+	 * method involving splices if force_inplace is set to false.  

This comment is fairly hard to understand without reading a lot of the rest of the patch first. It's also really not ideal - when we're in the fdt_rw context, we want to be able to really truly remove the stale tags, not just NOP them.

Well nopifying them is not optimized in the fdt_rw context but it is not incorrect.

Well if nopifying them in the fdt_rw context is a no go, I will add more complexity in the next iteration to really remove them instead of just nopifying them. Let me know what do you prefer.

Quoted 4 lines
Quoted 8 lines

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 226

Quoted 6 lines
libfdt/fdt_rw.c +6 -0
+	 */
+
+	tag = fdt_next_tag(fdt, prop_offset, &nextoffset);
+	if (tag == FDT_END)
+		return nextoffset;
+  

Should this error out if tag != FDT_PROP?

prop_offset points to a FDT_PROP. Already ckecked.

The check here is done to be sure that nextoffset if set to the next offset and not to a error code. Indeed, we use nextoffset as the next offset in the following loop.

Quoted 15 lines
Quoted 15 lines
libfdt/fdt_rw.c +14 -0
+	/*
+	 * Look at all tags related to the current property. I.e. tags after the
+	 * current property and before either the next property, a sub-node  or
+	 * the end of current node
+	 */
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag_(fdt, offset, &nextoffset, &is_unknown);
+		if (tag == FDT_END)
+			return nextoffset;
+
+		/*
+		 * Unknown tags are returned as NOP. Force FDT_NOP to be really
+		 * present in the area to remove the unknown tag and its related
Quoted 8 lines

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 244

Quoted 4 lines
libfdt/fdt_rw.c +4 -0
+		 * data. Also, as a tag is removed, downgrade the dtb version
+		 * if asked for.
+		 */
+		if (tag == FDT_NOP) {  

It seems to me this would be more natural using fdt_next_tag_all() (or whatever it ends up being called) and handling the nopping in the 'default' case.

This doesn't work in current implementation. All unknown tags are returned as FDT_NOP tags. That's fdt_next_tag_() is used. It allows to know if the returned FDT_NOP tag is a real FDT_NOP or an unknown tag translated to FDT_NOP.

This is the only use case where we really have to handle unknown tags. We need to remove them and so not skipping them.

Of course, you asked to change the fdt_next_tag() behavior to have it returned all tags (known and unknown skippable ones) and so this part of code will be updated accordingly.

Quoted 42 lines
Quoted 42 lines
libfdt/fdt_rw.c +23 -0
+			if (is_unknown) {
+				if (downgrade_version)
+					fdt_downgrade_version(fdt);
+				fdt_nopify_area(fdt, offset, nextoffset);
+			}
+		}
+
+	} while ((tag != FDT_PROP) && (tag != FDT_BEGIN_NODE) &&
+		 (tag != FDT_END_NODE));
+
+	return 0;
+}
+
 static int fdt_resize_property_(void *fdt, int nodeoffset,
 				const char *name, int namelen,
 				int len, struct fdt_property **prop)
 {
+	int prop_offset;
 	int oldlen;
 	int err;
 
@@ -209,6 +268,15 @@ static int fdt_resize_property_(void *fdt, int nodeoffset,
 	if (!*prop)
 		return oldlen;
 
+	/*
+	 * The property is resized. Remove possible unknown tags related to the
+	 * property downgrading the dtb version.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, *prop);
+	err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset, true);
+	if (err)
+		return err;
+
 	if ((err = fdt_splice_struct_(fdt, (*prop)->data, FDT_TAGALIGN(oldlen),
 				      FDT_TAGALIGN(len))))
 		return err;
@@ -217,6 +285,29 @@ static int fdt_resize_property_(void *fdt, int nodeoffset,
 	return 0;
 }
 
Quoted 4 lines

libfdt/fdt_rw.c static int fdt_resize_property_(void *fdt, int nodeoffset, · line 288

Quoted 1 line
libfdt/fdt_rw.c +1 -0
+static int fdt_node_skip_unknown_tags(void *fdt, int next)  

Is 'next' the offset of a node? If so it should probably have a more suggestive name.

No, next is the offset of the first tag available after a FDT_BEGIN_NODE.

Should I rename to 'node_next' ?

Quoted 50 lines
Quoted 50 lines
libfdt/fdt_rw.c +32 -0
+{
+	int nextoffset = next;
+	int offset;
+	uint32_t tag;
+
+	/*
+	 * Skip all tags related to the current node. I.e. tags after the
+	 * current node and before either the next property, a sub-node or the
+	 * end of current node.
+	 */
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		if (tag == FDT_END)
+			return nextoffset;
+
+	} while ((tag != FDT_PROP) && (tag != FDT_BEGIN_NODE) &&
+		 (tag != FDT_END_NODE));
+
+	return offset;
+}
+
 static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 			     int namelen, int len, struct fdt_property **prop)
 {
@@ -235,6 +326,15 @@ static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 	if ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
 		return nextoffset;
 
+	/*
+	 * nextoffset it at the first tag after the node.
+	 * Skip possible unknown tags related to the node in order to add the
+	 * property after those tags.
+	 */
+	nextoffset = fdt_node_skip_unknown_tags(fdt, nextoffset);
+	if (nextoffset < 0)
+		return nextoffset;
+
 	namestroff = fdt_find_add_string_(fdt, name, namelen, &allocated);
 	if (namestroff < 0)
 		return namestroff;
@@ -333,11 +433,22 @@ int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
 {
 	struct fdt_property *prop;
 	int err, oldlen, newlen;
+	int prop_offset;
 
 	FDT_RW_PROBE(fdt);
 
Quoted 15 lines

libfdt/fdt_rw.c int fdt_appendprop(void *fdt, int nodeoffset, const char *name, · line 450

Quoted 11 lines
libfdt/fdt_rw.c +9 -0
 	prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);
 	if (prop) {
+		/*
+		 * The property is going to be modified. Remove possible unknown
+		 * tags related to this property downgrading the dtb version.
+		 */
+		prop_offset = fdt_ptr_offset_(fdt, prop);
+		err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset,
+						   true);
+		if (err)
+			return err;  

Just NOPing the unknown tags isn't ideal here. This function can already insert/remove stuff from the structure block, so removing the tags entirely would be preferable.

I can add the complexity needed to fully remove those tags. IHMO it could be added later as an optimisation.

Quoted 30 lines
Quoted 16 lines
libfdt/fdt_rw.c +2 -0
 		newlen = len + oldlen;
 		err = fdt_splice_struct_(fdt, prop->data,
 					 FDT_TAGALIGN(oldlen),  
@@ -360,6 +471,8 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)
 {
 	struct fdt_property *prop;
 	int len, proplen;
+	int prop_offset;
+	int err;
 
 	FDT_RW_PROBE(fdt);
 
@@ -367,6 +480,15 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)
 	if (!prop)

libfdt/fdt_rw.c int fdt_delprop(void *fdt, int nodeoffset, const char *name) · line 490

Quoted 10 lines
libfdt/fdt_rw.c +8 -0
 		return len;
 
+	/*
+	 * The property is going to be removed. Remove also possible unknown
+	 * tags related to this property. Keep the dtb version unchanged.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, prop);
+	err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset, false);
+	if (err)
+		return err;  

Here, only NOPing the tags is worse, since delprop is expected to entirely remove the property without leaving NOPs.

Quoted 3 lines

Also.. just NOPing unknown tags isn't correct either. The property is being removed, so *all* the associated skippable tags should be removed as well (ideally with a single fdt_splice_struct_()).

Skippable tags are remove. They don't exist anymore in the resulting DT.

You have FDT_NOP tags. No issue with that.

It is not optimized but it is correct.

Here again, I can fully remove them.

Quoted 9 lines
Quoted 9 lines
libfdt/fdt_rw.c +1 -0
+
 	proplen = sizeof(*prop) + FDT_TAGALIGN(len);
 	return fdt_splice_struct_(fdt, prop, proplen, 0);
 }
@@ -395,7 +517,12 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 	else if (offset != -FDT_ERR_NOTFOUND)
 		return offset;
 
Quoted 9 lines

libfdt/fdt_rw.c int fdt_add_subnode_namelen(void *fdt, int parentoffset, · line 524

Quoted 6 lines
libfdt/fdt_rw.c +5 -1
-	/* Try to place the new node after the parent's properties */
+	/*
+	 * Try to place the new node after the parent's properties and unknown
+	 * tags related to those properties.
+	 * Unknown tags are reported as FDT_NOP tags by fdt_next_tag.
+	 * Skipping FDT_NOP tags will correctly skip unknown tags.  

True, but I think it would be clearer and more robust to explicitly look for an FDT_BEGIN_NODE or FDT_END_NODE tag instead.

Ok, will have look in that direction.

Quoted 31 lines
Quoted 31 lines
libfdt/fdt_rw.c +1 -0
+	 */
 	tag = fdt_next_tag(fdt, parentoffset, &nextoffset);
 	/* the fdt_subnode_offset_namelen() should ensure this never hits */
 	if (!can_assume(LIBFDT_FLAWLESS) && (tag != FDT_BEGIN_NODE))
libfdt/fdt_wip.c +7 -2
index c2d7566a..7ca3ffbc 100644
@@ -15,17 +15,30 @@ int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset,
 					uint32_t idx, const void *val,
 					int len)
 {
+	int prop_offset;
 	void *propval;
 	int proplen;
+	int err;
 
-	propval = fdt_getprop_namelen_w(fdt, nodeoffset, name, namelen,
-					&proplen);
+	prop_offset = fdt_getprop_offset_namelen(fdt, nodeoffset, name, namelen);
+	if (prop_offset < 0)
+		return prop_offset;
+
+	propval = fdt_getprop_by_offset_w(fdt, prop_offset, NULL, &proplen);
 	if (!propval)
 		return proplen;
 
 	if ((unsigned)proplen < (len + idx))
 		return -FDT_ERR_NOSPACE;
 
Quoted 12 lines

libfdt/fdt_wip.c int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset, · line 38

Quoted 5 lines
libfdt/fdt_wip.c +5 -0
+	/*
+	 * Remove unknown tags related to the property downgrading the dtb
+	 * version.
+	 */
+	err = fdt_prop_remove_unknown_tags(fdt, true, prop_offset, true);  

Functions in fdt_wip.c should not depend on functions in fdw_rw.c. Part of the reason for organising things this way is so that a client only uses write-in-place functions, the linker will omit the more complex full read-write code (even if an old or limited linker that doesn't do e.g. function sections). fdt_rw.c by contrast _is_ permitted to rely on fdt_wip.c

Makes sense.

I will take this relationship into account in the next iteration.

Quoted 19 lines
Quoted 19 lines
libfdt/fdt_wip.c +5 -0
+	if (err)
+		return err;
+
 	memcpy((char *)propval + idx, val, len);
 	return 0;
 }
@@ -59,12 +72,23 @@ static void fdt_nop_region_(void *start, int len)
 int fdt_nop_property(void *fdt, int nodeoffset, const char *name)
 {
 	struct fdt_property *prop;
+	int prop_offset;
 	int len;
+	int err;
 
 	prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
 	if (!prop)
 		return len;
 
Quoted 12 lines

libfdt/fdt_wip.c static void fdt_nop_region_(void *start, int len) · line 90

Quoted 8 lines
libfdt/fdt_wip.c +8 -0
+	/*
+	 * The property is going to be removed (nopified). Remove unknown tags
+	 * related to this property. Keep the dtb version unchanged.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, prop);
+	err = fdt_prop_remove_unknown_tags(fdt, true, prop_offset, false);
+	if (err)
+		return err;  

Similar to fdt_delprop() this needs to NOP *all* the properties associated with the property we're killing, not just the unknown ones (again, ideally with a single fdt_nop_region_()).

I don't follow you.

Only unknown tags need to be removed for the moment. What other tags do you want to remove?

Quoted 32 lines
Quoted 32 lines
libfdt/fdt_wip.c +0 -0
 	fdt_nop_region_(prop, len + sizeof(*prop));
 
 	return 0;
libfdt/libfdt_internal.h +3 -0
index e3923629..ce128fda 100644
@@ -26,6 +26,9 @@ uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset,
 int fdt_check_node_offset_(const void *fdt, int offset);
 int fdt_check_prop_offset_(const void *fdt, int offset);
 
+int fdt_prop_remove_unknown_tags(void *fdt, bool force_inplace,
+				 int prop_offset, bool downgrade_version);
+
 int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
 			       const char *name, int namelen);
 static inline int fdt_getprop_offset(const void *fdt, int nodeoffset,
tests/run_tests.sh +6 -0
index 419a24d8..980ed6a0 100755
@@ -586,6 +586,34 @@ libfdt_tests () {
 		unknown_tags_no_skip.dtb; do
 	run_test check_full -n $bad
     done
+
+    # Check inplace modification with "unknown" tags that can be skipped
+    dtb=unknown_tags_can_skip.wip.test.dtb
+    cp unknown_tags_can_skip.dtb $dtb
+    base_run_test wrap_fdtdump $dtb $dtb.0.out
+    # Remove unneeded header fields (keep those related to versions)
Quoted 8 lines

tests/run_tests.sh libfdt_tests () { · line 596

Quoted 2 lines
tests/run_tests.sh +2 -0
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.0.out
+    base_run_test check_diff $dtb.0.out "$SRCDIR/$dtb.0.expect"  

As noted earlier in the series, tests of binary-level behaviour shouldn't depend on specific source formatting. The use of wip_func to essentially do some of the test steps in shell seems clumsy to me - I think this would be nicer as explicit tests written in C which directly look at the binary dtb contents.

I don't like that.

We need to check all the output dtb to be sure that everything is correct and avoid missing something.

Here with unknown tag handling and with future metadata tags, we have to observe those tags in the binary blob.

If fdtdump is an issue, I will write fdtanalyze which dump a dtb blob in an other human readable format. We need to see all tags, and they raw data values an hex.

When I wrote the code, I did some mistake and using only binary files is really not easy to debug stuff. When a given test is broken by some modification, we need to have an easy way to see the root cause.

Quoted 37 lines
Quoted 37 lines
tests/run_tests.sh +29 -0
+    run_test wip_func $dtb set_prop / prop-str 0 "vwxy"
+    base_run_test wrap_fdtdump $dtb $dtb.1.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.1.out
+    base_run_test check_diff $dtb.1.out "$SRCDIR/$dtb.1.expect"
+
+    cp unknown_tags_can_skip.dtb $dtb
+    run_test wip_func $dtb nop_prop /subnode2 prop-int1
+    base_run_test wrap_fdtdump $dtb $dtb.2.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.2.out
+    base_run_test check_diff $dtb.2.out "$SRCDIR/$dtb.2.expect"
+
+    cp unknown_tags_can_skip.dtb $dtb
+    run_test wip_func $dtb nop_node /subnode2/subsubnode
+    base_run_test wrap_fdtdump $dtb $dtb.3.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.3.out
+    base_run_test check_diff $dtb.3.out "$SRCDIR/$dtb.3.expect"
 }
 
 dtc_tests () {
@@ -1045,6 +1073,56 @@ fdtput_tests () {
     run_wrap_error_test $DTPUT $dtb -d /chosen   non-existent-prop
 
     # TODO: Add tests for verbose mode?
+
+    # Modify a dtb containing some "unknown" tags that can be skipped
+    dtb=unknown_tags_can_skip.fdtput.test.dtb
+    cp unknown_tags_can_skip.dtb $dtb
+    base_run_test wrap_fdtdump $dtb $dtb.0.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.0.out
+    base_run_test check_diff $dtb.0.out "$SRCDIR/$dtb.0.expect"
+    run_fdtput_test "vwxyz" $dtb / prop-str -ts "vwxyz"
+    base_run_test wrap_fdtdump $dtb $dtb.1.out
Quoted 8 lines

tests/run_tests.sh libfdt_tests () { · line 602

Quoted 3 lines
tests/run_tests.sh +3 -0
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.1.out
+    base_run_test check_diff $dtb.1.out "$SRCDIR/$dtb.1.expect"  

Doing these as fdtput tests again seems kind of clumsy, unless the point is explicitly to check the fdtput utility's behaviour. The core library functionality should be tested directly without introducing extra layers.

Need to check the whole resulting binary skippable tags removed, version downgrade. We need to check that the whole binary is still correct.

'hexdump $dtb' could be used but having an array of hex value without any other formatting related to dtb defined format will be ugly.

Here also fdtanalyzer could output hex values with some formating based on dtb format definition. For instance:
(0x1-FDT_BEGIN_NODE): "my_node"

    (0x3-FDT_PROP): ...
    (0x3-FDT_PROP): ...

(0x2-FDT_END_NODE)
...
(0x9-FDT_END)

Maybe offset (absolute and/or based on the beginning of the structure block) could also be interesting in this kind of dumps.

Best regards,
Hervé

#81 lore raw

Re: [PATCH v3 14/15] libfdt: Handle unknown tags on dtb modifications

Quoted 22 lines · Herve Codina
Quoted 19 lines · On Mon, 21 Sep 2026 16:06:13 +1000 David Gibson <[email protected]>…
Quoted 17 lines · Herve Codina

The structured tag value definition introduced recently gives the ability to ignore unknown tags without any error.

When the dtb is modified those unknown tags have to be taken into account.

First, depending on the unknown tag location, the item associated with the tag is identified:
- An unknown tag located just after a FDT_BEGIN_NODE is related to the node.

- An unknown tag located just after a FDT_PROP is related to the property.

- An unknown tag out of any node (i.e located before the first FDT_BEGIN_NODE or after the last FDT_END_NODE) is a global tag related to the dtb itself.

Quoted 6 lines
Quoted 4 lines

Since we rely on those constraings here, it seems like those should probably be written into the structured tag specs / description. Which to my mind strengthens the case for explicitly calling them "metadata tags".

Yes this need to be documented somewhere but where?

Yeah, that's a good question.

Quoted 1 line

In the end it should be present in the Devicetree Specification.

Right, eventually. But that will take a while, plus it's preferable to have the documentation as close as possible to the things you'd be looking at when it becomes relevant.

So, for starters, I think your commit messages should include this kind of context and rationale at the point the concepts are introdcued to the code. It also might make sense to have some of this in comments in fdt.h. We haven't done much of that so far, but providing more detail around the bare structure and constant definitions is probably worthwhile.

Quoted 3 lines

Related to the term "metadata" I am not sure that all future tags will be "metadata" tags. Especially global tags (out of any nodes). At this point we have "skippable" tags without any more knowledge.

Hm, ok.

Quoted 16 lines

But anyway, I will use the term "metadata".

Quoted 14 lines
Quoted 5 lines

Then, if we are allowed to write a dtb containing unknown tags, the following rules are used:
- When a property is modified, tags related to this property are removed and the dtb version is downgraded.

Hmm. This seems weird to me, but maybe that's because we haven't pinned down in specs / docs what the interaction is between new skippable tags and the overall version.

My assumption had been that tags - even structured tags - newer than vNNN must not appear in a dtb with version == NNN (but they can appear in a dtb with last_compat_version < NNN).

Quoted 6 lines
Quoted 3 lines

With that model, this seems kind of backwards - downgrading the version would require removing newer tags throughout the tree, rather than removing some tags causing the version to be downgraded.

The discussion which led to this mechanism is available at [1].

Ah, thanks for the reminder.

Quoted 3 lines

If all tags are removed, there is no way to forward a dtb with unknown tags from a bootloader point of view (support for Vnnn in bootloader) to a Linux Kernel having support for newer dtb version.

I'm guessing that's with the assumption that the bootloader is making at least minor changes to the tree? Certainly a tree with unknown tags can be forwarded unmodified.

Quoted 1 line

[1] https://lore.kernel.org/all/CAL_JsqLRrbZje_gGZPBDni6StFa+6rdiECtk49on8VfkP7CDvw@mail.gmail.com/

TBH, I'm finding it pretty hard to follow what Rob's saying there. It does help me understand some things you've said elsewhere.

Quoted 11 lines
Quoted 10 lines
Quoted 5 lines

- When a property is removed, tags related to this property are obviously removed. The dtb version is kept unchanged.

- When a property or a node is added, obviously no unknown tags are added and the dtb version is kept unchanged.

This seems weird to me in combination with the behaviour on modification. The previous one makes more sense to me in the context of an alternative model: newer versions might *require* certain metadata tags are present. But in that case this part doesn't work.

Quoted 6 lines

Suppose a tag defined at Vnnn. An older libfdt can add a property to a node but cannot add the tag defined at Vnnn. Indeed this tag is unknown.

At a given version, libfdt cannot add unknown tags and so as unknown tags are not involved when a property is added, there is no need to dowgrade the version.

Only if we assume "skippable" tags are always optional. Making this assumption means we can't, for example, say: from v23, all properties _must_ have an FDT_XXX metadata tag. Constraining future versions that way seems undesirable to me, since a number of previous revisions exist to say "you can count on this particular information being present". That's been in the form of extra header fields previously, but I think the same principle applies. e.g. it seems like it would be pretty useful to tell an addon aware bootloader "if version >= NNN then you can rely on all necessary fixup tags being present.

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines

- When a node is removed, tags related to this node are obviously removed. The dtb version is kept unchanged.

- Adding, removing or modifying a property is not considered as a node modification and so, those operations have no impacts on unknown tags related to the node. Those node related tags are kept unchanged.

Quoted 8 lines
Quoted 3 lines

That.. certainly constrains what it's possible to put in skippable tags, in a way that we'd have to document, though it's not especially easy to do so.

Yes, and that's why the FDT_BEGIN_NODE_REF tag defined by the support for addon cannot be skipped. If this tag is skipped by older libfdt weird behavior will happen. The old libfdt will think that the root node is a subnode of an orphan node.

Sure, it's pretty clear than anything that would alter the tree structure can't be skipped. But the constraints on what needs to be dropped on what sorts of modification constrict things substantially further. For example. the fact that property modifications don't affect node tags means it wouldn't be possible to have a node tag which was, say, "total number of properties in this subtree". That's a contrived example, obviously, but it's not obvious to me there wouldn't be some use for "summary" tags of this nature, that is, something which collates information for an entire node or subtree for quick reference.

Quoted 89 lines

top level dtb:
FDT_BEGIN_NODE_REF <--- Skip by old libfdt
FDT_BEGIN_NODE <---- Root node identified by old libfdt

To avoid that FDT_BEGIN_NODE_REF cannot be skipped and so old libfdt will report an error: Unknown tag which cannot be skipped.

Quoted 73 lines
Quoted 47 lines

- The only modification considered as a node modification is setting its name. We consider that this operation has no impact on tags related to the node. Here also, those node related tags and the dtb version are kept unchanged.

- Global (dtb related) unknown tags are kept unchanged regardless the modification done.

Implement those rules when a dtb is modified.

---
 libfdt/fdt_rw.c                               | 129 +++++++++++++++++-
 libfdt/fdt_wip.c                              |  28 +++-
 libfdt/libfdt_internal.h                      |   3 +
 tests/run_tests.sh                            |  78 +++++++++++
 ...own_tags_can_skip.fdtput.test.dtb.0.expect |  31 +++++
 ...own_tags_can_skip.fdtput.test.dtb.1.expect |  35 +++++
 ...own_tags_can_skip.fdtput.test.dtb.2.expect |  33 +++++
 ...own_tags_can_skip.fdtput.test.dtb.3.expect |  35 +++++
 ...own_tags_can_skip.fdtput.test.dtb.4.expect |  34 +++++
 ...own_tags_can_skip.fdtput.test.dtb.5.expect |  32 +++++
 ...own_tags_can_skip.fdtput.test.dtb.6.expect |  27 ++++
 ...nknown_tags_can_skip.wip.test.dtb.0.expect |  31 +++++
 ...nknown_tags_can_skip.wip.test.dtb.1.expect |  35 +++++
 ...nknown_tags_can_skip.wip.test.dtb.2.expect |  37 +++++
 ...nknown_tags_can_skip.wip.test.dtb.3.expect |  38 ++++++
 15 files changed, 603 insertions(+), 3 deletions(-)
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.3.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.4.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.5.expect
 create mode 100644 tests/unknown_tags_can_skip.fdtput.test.dtb.6.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.0.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.1.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.2.expect
 create mode 100644 tests/unknown_tags_can_skip.wip.test.dtb.3.expect
libfdt/fdt_rw.c +0 -0
index ceef49b8..87776609 100644

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 200

Quoted 4 lines
libfdt/fdt_rw.c +1 -0
@@ -197,10 +197,69 @@ int fdt_del_mem_rsv(void *fdt, int n)
 	return fdt_splice_mem_rsv_(fdt, re, 1, 0);
 }
 
+static void fdt_nopify_area(void *fdt, int start_offset, int next_offset)  

This should be written in terms of fdt_nop_region_() from fdt_wip.c (or else the other way around). It should also probably live in fdt_wip.c.

Quoted 17 lines
libfdt/fdt_rw.c +17 -0
+{
+	int count = (next_offset - start_offset) / sizeof(fdt32_t);
+	fdt32_t fdt32_nop = cpu_to_fdt32(FDT_NOP);
+	fdt32_t *ptr;
+
+	ptr = fdt_offset_ptr_w_(fdt, start_offset);
+	while (count--)
+		*(ptr++) = fdt32_nop;
+};
+
+int fdt_prop_remove_unknown_tags(void *fdt, bool force_inplace,
+				 int prop_offset, bool downgrade_version)
+{
+	int nextoffset, offset;
+	bool is_unknown;
+	uint32_t tag;
+
Quoted 8 lines

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 220

Quoted 3 lines
libfdt/fdt_rw.c +3 -0
+	/*
+	 * Only inplace using nopify is supported even if we could use an other
+	 * method involving splices if force_inplace is set to false.  

This comment is fairly hard to understand without reading a lot of the rest of the patch first. It's also really not ideal - when we're in the fdt_rw context, we want to be able to really truly remove the stale tags, not just NOP them.

Quoted 2 lines

Well nopifying them is not optimized in the fdt_rw context but it is not incorrect.

It breaks the principle of least surprise, though. Especially since we don't have a "strip nops" function (aside: that would be a nice addition).

Quoted 3 lines

Well if nopifying them in the fdt_rw context is a no go, I will add more complexity in the next iteration to really remove them instead of just nopifying them. Let me know what do you prefer.

I don't think it's actually that much more complex. You already have to deal with tree splicing in this case.

Quoted 10 lines
Quoted 8 lines

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 226

Quoted 6 lines
libfdt/fdt_rw.c +6 -0
+	 */
+
+	tag = fdt_next_tag(fdt, prop_offset, &nextoffset);
+	if (tag == FDT_END)
+		return nextoffset;
+  

Should this error out if tag != FDT_PROP?

prop_offset points to a FDT_PROP. Already ckecked.

Not in this function, AFAICT. I assume the callers ensure this, but that's not obvious when looking just at this code. I'd prefer to see this checked here (unless can_assume(ASSUME_LIBFDT_FLAWLESS)) returning FDT_ERR_INTERNAL if it fails.

Quoted 3 lines

The check here is done to be sure that nextoffset if set to the next offset and not to a error code. Indeed, we use nextoffset as the next offset in the following loop.

Yes, but I get nervous whenever I see a non-exhaustive check on a return value.

Quoted 23 lines
Quoted 14 lines
Quoted 14 lines
libfdt/fdt_rw.c +14 -0
+	/*
+	 * Look at all tags related to the current property. I.e. tags after the
+	 * current property and before either the next property, a sub-node  or
+	 * the end of current node
+	 */
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag_(fdt, offset, &nextoffset, &is_unknown);
+		if (tag == FDT_END)
+			return nextoffset;
+
+		/*
+		 * Unknown tags are returned as NOP. Force FDT_NOP to be really
+		 * present in the area to remove the unknown tag and its related
Quoted 8 lines

libfdt/fdt_rw.c int fdt_del_mem_rsv(void *fdt, int n) · line 244

Quoted 4 lines
libfdt/fdt_rw.c +4 -0
+		 * data. Also, as a tag is removed, downgrade the dtb version
+		 * if asked for.
+		 */
+		if (tag == FDT_NOP) {  

It seems to me this would be more natural using fdt_next_tag_all() (or whatever it ends up being called) and handling the nopping in the 'default' case.

Quoted 6 lines

This doesn't work in current implementation. All unknown tags are returned as FDT_NOP tags. That's fdt_next_tag_() is used. It allows to know if the returned FDT_NOP tag is a real FDT_NOP or an unknown tag translated to FDT_NOP.

This is the only use case where we really have to handle unknown tags. We need to remove them and so not skipping them.

Yes, exactly, that's why I'm saying it would make more sense to use the iterator that *doesn't* skip unknown tags (whatever it gets called).

Quoted 3 lines

Of course, you asked to change the fdt_next_tag() behavior to have it returned all tags (known and unknown skippable ones) and so this part of code will be updated accordingly.

Sure.

Quoted 41 lines
Quoted 41 lines
Quoted 41 lines
libfdt/fdt_rw.c +23 -0
+			if (is_unknown) {
+				if (downgrade_version)
+					fdt_downgrade_version(fdt);
+				fdt_nopify_area(fdt, offset, nextoffset);
+			}
+		}
+
+	} while ((tag != FDT_PROP) && (tag != FDT_BEGIN_NODE) &&
+		 (tag != FDT_END_NODE));
+
+	return 0;
+}
+
 static int fdt_resize_property_(void *fdt, int nodeoffset,
 				const char *name, int namelen,
 				int len, struct fdt_property **prop)
 {
+	int prop_offset;
 	int oldlen;
 	int err;
 
@@ -209,6 +268,15 @@ static int fdt_resize_property_(void *fdt, int nodeoffset,
 	if (!*prop)
 		return oldlen;
 
+	/*
+	 * The property is resized. Remove possible unknown tags related to the
+	 * property downgrading the dtb version.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, *prop);
+	err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset, true);
+	if (err)
+		return err;
+
 	if ((err = fdt_splice_struct_(fdt, (*prop)->data, FDT_TAGALIGN(oldlen),
 				      FDT_TAGALIGN(len))))
 		return err;
@@ -217,6 +285,29 @@ static int fdt_resize_property_(void *fdt, int nodeoffset,
 	return 0;
 }
 
Quoted 6 lines
Quoted 4 lines

libfdt/fdt_rw.c static int fdt_resize_property_(void *fdt, int nodeoffset, · line 288

Quoted 1 line
libfdt/fdt_rw.c +1 -0
+static int fdt_node_skip_unknown_tags(void *fdt, int next)  

Is 'next' the offset of a node? If so it should probably have a more suggestive name.

No, next is the offset of the first tag available after a FDT_BEGIN_NODE.

Ah, right.

Quoted 1 line

Should I rename to 'node_next' ?

No, it's ok as is.

Quoted 98 lines
Quoted 49 lines
Quoted 49 lines
libfdt/fdt_rw.c +32 -0
+{
+	int nextoffset = next;
+	int offset;
+	uint32_t tag;
+
+	/*
+	 * Skip all tags related to the current node. I.e. tags after the
+	 * current node and before either the next property, a sub-node or the
+	 * end of current node.
+	 */
+	do {
+		offset = nextoffset;
+		tag = fdt_next_tag(fdt, offset, &nextoffset);
+		if (tag == FDT_END)
+			return nextoffset;
+
+	} while ((tag != FDT_PROP) && (tag != FDT_BEGIN_NODE) &&
+		 (tag != FDT_END_NODE));
+
+	return offset;
+}
+
 static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 			     int namelen, int len, struct fdt_property **prop)
 {
@@ -235,6 +326,15 @@ static int fdt_add_property_(void *fdt, int nodeoffset, const char *name,
 	if ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)
 		return nextoffset;
 
+	/*
+	 * nextoffset it at the first tag after the node.
+	 * Skip possible unknown tags related to the node in order to add the
+	 * property after those tags.
+	 */
+	nextoffset = fdt_node_skip_unknown_tags(fdt, nextoffset);
+	if (nextoffset < 0)
+		return nextoffset;
+
 	namestroff = fdt_find_add_string_(fdt, name, namelen, &allocated);
 	if (namestroff < 0)
 		return namestroff;
@@ -333,11 +433,22 @@ int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
 {
 	struct fdt_property *prop;
 	int err, oldlen, newlen;
+	int prop_offset;
 
 	FDT_RW_PROBE(fdt);
 
Quoted 15 lines

libfdt/fdt_rw.c int fdt_appendprop(void *fdt, int nodeoffset, const char *name, · line 450

Quoted 11 lines
libfdt/fdt_rw.c +9 -0
 	prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);
 	if (prop) {
+		/*
+		 * The property is going to be modified. Remove possible unknown
+		 * tags related to this property downgrading the dtb version.
+		 */
+		prop_offset = fdt_ptr_offset_(fdt, prop);
+		err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset,
+						   true);
+		if (err)
+			return err;  

Just NOPing the unknown tags isn't ideal here. This function can already insert/remove stuff from the structure block, so removing the tags entirely would be preferable.

I can add the complexity needed to fully remove those tags. IHMO it could be added later as an optimisation.

Quoted 30 lines
Quoted 16 lines
libfdt/fdt_rw.c +2 -0
 		newlen = len + oldlen;
 		err = fdt_splice_struct_(fdt, prop->data,
 					 FDT_TAGALIGN(oldlen),  
@@ -360,6 +471,8 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)
 {
 	struct fdt_property *prop;
 	int len, proplen;
+	int prop_offset;
+	int err;
 
 	FDT_RW_PROBE(fdt);
 
@@ -367,6 +480,15 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)
 	if (!prop)

libfdt/fdt_rw.c int fdt_delprop(void *fdt, int nodeoffset, const char *name) · line 490

Quoted 10 lines
libfdt/fdt_rw.c +8 -0
 		return len;
 
+	/*
+	 * The property is going to be removed. Remove also possible unknown
+	 * tags related to this property. Keep the dtb version unchanged.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, prop);
+	err = fdt_prop_remove_unknown_tags(fdt, false, prop_offset, false);
+	if (err)
+		return err;  

Here, only NOPing the tags is worse, since delprop is expected to entirely remove the property without leaving NOPs.

Quoted 5 lines
Quoted 3 lines

Also.. just NOPing unknown tags isn't correct either. The property is being removed, so *all* the associated skippable tags should be removed as well (ideally with a single fdt_splice_struct_()).

Skippable tags are remove. They don't exist anymore in the resulting DT.

No, *unknown* (by this libfdt version) tags are nopped. Known skippable tags are left unaltered. Presumably they would then apply to the previous property, which is definitely wrong.

Quoted 5 lines

You have FDT_NOP tags. No issue with that.

It is not optimized but it is correct.

Here again, I can fully remove them.

That would be good, but it's not the issue I'm pointing out above.

Quoted 100 lines
Quoted 8 lines
Quoted 8 lines
libfdt/fdt_rw.c +1 -0
+
 	proplen = sizeof(*prop) + FDT_TAGALIGN(len);
 	return fdt_splice_struct_(fdt, prop, proplen, 0);
 }
@@ -395,7 +517,12 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 	else if (offset != -FDT_ERR_NOTFOUND)
 		return offset;
 
Quoted 9 lines

libfdt/fdt_rw.c int fdt_add_subnode_namelen(void *fdt, int parentoffset, · line 524

Quoted 6 lines
libfdt/fdt_rw.c +5 -1
-	/* Try to place the new node after the parent's properties */
+	/*
+	 * Try to place the new node after the parent's properties and unknown
+	 * tags related to those properties.
+	 * Unknown tags are reported as FDT_NOP tags by fdt_next_tag.
+	 * Skipping FDT_NOP tags will correctly skip unknown tags.  

True, but I think it would be clearer and more robust to explicitly look for an FDT_BEGIN_NODE or FDT_END_NODE tag instead.

Ok, will have look in that direction.

Quoted 31 lines
Quoted 31 lines
libfdt/fdt_rw.c +1 -0
+	 */
 	tag = fdt_next_tag(fdt, parentoffset, &nextoffset);
 	/* the fdt_subnode_offset_namelen() should ensure this never hits */
 	if (!can_assume(LIBFDT_FLAWLESS) && (tag != FDT_BEGIN_NODE))
libfdt/fdt_wip.c +7 -2
index c2d7566a..7ca3ffbc 100644
@@ -15,17 +15,30 @@ int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset,
 					uint32_t idx, const void *val,
 					int len)
 {
+	int prop_offset;
 	void *propval;
 	int proplen;
+	int err;
 
-	propval = fdt_getprop_namelen_w(fdt, nodeoffset, name, namelen,
-					&proplen);
+	prop_offset = fdt_getprop_offset_namelen(fdt, nodeoffset, name, namelen);
+	if (prop_offset < 0)
+		return prop_offset;
+
+	propval = fdt_getprop_by_offset_w(fdt, prop_offset, NULL, &proplen);
 	if (!propval)
 		return proplen;
 
 	if ((unsigned)proplen < (len + idx))
 		return -FDT_ERR_NOSPACE;
 
Quoted 12 lines

libfdt/fdt_wip.c int fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset, · line 38

Quoted 5 lines
libfdt/fdt_wip.c +5 -0
+	/*
+	 * Remove unknown tags related to the property downgrading the dtb
+	 * version.
+	 */
+	err = fdt_prop_remove_unknown_tags(fdt, true, prop_offset, true);  

Functions in fdt_wip.c should not depend on functions in fdw_rw.c. Part of the reason for organising things this way is so that a client only uses write-in-place functions, the linker will omit the more complex full read-write code (even if an old or limited linker that doesn't do e.g. function sections). fdt_rw.c by contrast _is_ permitted to rely on fdt_wip.c

Makes sense.

I will take this relationship into account in the next iteration.

Quoted 19 lines
Quoted 19 lines
libfdt/fdt_wip.c +5 -0
+	if (err)
+		return err;
+
 	memcpy((char *)propval + idx, val, len);
 	return 0;
 }
@@ -59,12 +72,23 @@ static void fdt_nop_region_(void *start, int len)
 int fdt_nop_property(void *fdt, int nodeoffset, const char *name)
 {
 	struct fdt_property *prop;
+	int prop_offset;
 	int len;
+	int err;
 
 	prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
 	if (!prop)
 		return len;
 
Quoted 12 lines

libfdt/fdt_wip.c static void fdt_nop_region_(void *start, int len) · line 90

Quoted 8 lines
libfdt/fdt_wip.c +8 -0
+	/*
+	 * The property is going to be removed (nopified). Remove unknown tags
+	 * related to this property. Keep the dtb version unchanged.
+	 */
+	prop_offset = fdt_ptr_offset_(fdt, prop);
+	err = fdt_prop_remove_unknown_tags(fdt, true, prop_offset, false);
+	if (err)
+		return err;  

Similar to fdt_delprop() this needs to NOP *all* the properties associated with the property we're killing, not just the unknown ones (again, ideally with a single fdt_nop_region_()).

Quoted 4 lines

I don't follow you.

Only unknown tags need to be removed for the moment. What other tags do you want to remove?

Again, all skippable tags on the property need to be nopped, not just unknown ones. Otherwise they'll stay there and now apply to the previous property.

Quoted 40 lines
Quoted 31 lines
Quoted 31 lines
libfdt/fdt_wip.c +0 -0
 	fdt_nop_region_(prop, len + sizeof(*prop));
 
 	return 0;
libfdt/libfdt_internal.h +3 -0
index e3923629..ce128fda 100644
@@ -26,6 +26,9 @@ uint32_t fdt_next_tag_(const void *fdt, int startoffset, int *nextoffset,
 int fdt_check_node_offset_(const void *fdt, int offset);
 int fdt_check_prop_offset_(const void *fdt, int offset);
 
+int fdt_prop_remove_unknown_tags(void *fdt, bool force_inplace,
+				 int prop_offset, bool downgrade_version);
+
 int fdt_getprop_offset_namelen(const void *fdt, int nodeoffset,
 			       const char *name, int namelen);
 static inline int fdt_getprop_offset(const void *fdt, int nodeoffset,
tests/run_tests.sh +6 -0
index 419a24d8..980ed6a0 100755
@@ -586,6 +586,34 @@ libfdt_tests () {
 		unknown_tags_no_skip.dtb; do
 	run_test check_full -n $bad
     done
+
+    # Check inplace modification with "unknown" tags that can be skipped
+    dtb=unknown_tags_can_skip.wip.test.dtb
+    cp unknown_tags_can_skip.dtb $dtb
+    base_run_test wrap_fdtdump $dtb $dtb.0.out
+    # Remove unneeded header fields (keep those related to versions)
Quoted 8 lines

tests/run_tests.sh libfdt_tests () { · line 596

Quoted 2 lines
tests/run_tests.sh +2 -0
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.0.out
+    base_run_test check_diff $dtb.0.out "$SRCDIR/$dtb.0.expect"  

As noted earlier in the series, tests of binary-level behaviour shouldn't depend on specific source formatting. The use of wip_func to essentially do some of the test steps in shell seems clumsy to me - I think this would be nicer as explicit tests written in C which directly look at the binary dtb contents.

Quoted 4 lines

I don't like that.

We need to check all the output dtb to be sure that everything is correct and avoid missing something.

Yes.. a C program can do that...

Quoted 2 lines

Here with unknown tag handling and with future metadata tags, we have to observe those tags in the binary blob.

Certainly.

Quoted 2 lines

If fdtdump is an issue, I will write fdtanalyze which dump a dtb blob in an other human readable format. We need to see all tags, and they raw data values an hex.

fdtdump is an issue - it's a sometimes-useful hack, not a tool to be relied on. What would probably make more sense here is a 'dtbs_equal_with_tags' or something, that performs a stricter comparison that the existing dtbs_equal_ordered.

Quoted 50 lines

When I wrote the code, I did some mistake and using only binary files is really not easy to debug stuff. When a given test is broken by some modification, we need to have an easy way to see the root cause.

Quoted 37 lines
Quoted 37 lines
tests/run_tests.sh +29 -0
+    run_test wip_func $dtb set_prop / prop-str 0 "vwxy"
+    base_run_test wrap_fdtdump $dtb $dtb.1.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.1.out
+    base_run_test check_diff $dtb.1.out "$SRCDIR/$dtb.1.expect"
+
+    cp unknown_tags_can_skip.dtb $dtb
+    run_test wip_func $dtb nop_prop /subnode2 prop-int1
+    base_run_test wrap_fdtdump $dtb $dtb.2.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.2.out
+    base_run_test check_diff $dtb.2.out "$SRCDIR/$dtb.2.expect"
+
+    cp unknown_tags_can_skip.dtb $dtb
+    run_test wip_func $dtb nop_node /subnode2/subsubnode
+    base_run_test wrap_fdtdump $dtb $dtb.3.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.3.out
+    base_run_test check_diff $dtb.3.out "$SRCDIR/$dtb.3.expect"
 }
 
 dtc_tests () {
@@ -1045,6 +1073,56 @@ fdtput_tests () {
     run_wrap_error_test $DTPUT $dtb -d /chosen   non-existent-prop
 
     # TODO: Add tests for verbose mode?
+
+    # Modify a dtb containing some "unknown" tags that can be skipped
+    dtb=unknown_tags_can_skip.fdtput.test.dtb
+    cp unknown_tags_can_skip.dtb $dtb
+    base_run_test wrap_fdtdump $dtb $dtb.0.out
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.0.out
+    base_run_test check_diff $dtb.0.out "$SRCDIR/$dtb.0.expect"
+    run_fdtput_test "vwxyz" $dtb / prop-str -ts "vwxyz"
+    base_run_test wrap_fdtdump $dtb $dtb.1.out
Quoted 8 lines

tests/run_tests.sh libfdt_tests () { · line 602

Quoted 3 lines
tests/run_tests.sh +3 -0
+    # Remove unneeded header fields (keep those related to versions)
+    sed -i '/^\/.*\(magic\|off\|size\|cpu\)/d' $dtb.1.out
+    base_run_test check_diff $dtb.1.out "$SRCDIR/$dtb.1.expect"  

Doing these as fdtput tests again seems kind of clumsy, unless the point is explicitly to check the fdtput utility's behaviour. The core library functionality should be tested directly without introducing extra layers.

Quoted 2 lines

Need to check the whole resulting binary skippable tags removed, version downgrade. We need to check that the whole binary is still correct.

Yes, but how does that relate to the use of fdtput?

Quoted 2 lines

'hexdump $dtb' could be used but having an array of hex value without any other formatting related to dtb defined format will be ugly.

Sure. Again, seems like what you want is a dtbs_equal_with_tags.

Quoted 16 lines

Here also fdtanalyzer could output hex values with some formating based on dtb format definition. For instance:
(0x1-FDT_BEGIN_NODE): "my_node"

    (0x3-FDT_PROP): ...
    (0x3-FDT_PROP): ...

(0x2-FDT_END_NODE)
...
(0x9-FDT_END)

Maybe offset (absolute and/or based on the beginning of the structure block) could also be interesting in this kind of dumps.

Best regards,
Hervé

Signature · 4 lines
David Gibson (he or they)	| I'll have my music baroque, and my code
david AT gibson.dropbear.id.au	| minimalist, thank you, not the other way
				| around.
http://www.ozlabs.org/~dgibson