fdtfactor: Introduce fdtfactor to auto-factor overlays
Subsystems (2)
v4 cover fdtfactor: Introduce fdtfactor to auto-factor overlays
Devicetree overlays exist at both the source level (via /include/ and .dtsi files) and the binary level (where a compiled .dtbo overlay is applied to a "base" .dtb at runtime to add or modify nodes).
Binary .dtbo overlays were created by transcribing source-level overlay semantics to .dtb blobs to serve two main use cases:
1. Supporting add-on boards (like "hats" on a dev board), where a base board's .dtb is combined with an add-on board's .dtbo at boot or runtime (a use case that Hervé Codina's upcoming "addons" work aims to model more cleanly).
2. Allowing constrained bootloaders or firmware images to support a "family" of similar boards in a space-efficient way without shipping a full .dtb for every variant. In upstream Linux, for example, there are 47 distinct sc7180-trogdor boards supported. At the source level these boards share common .dtsi files, but we still compile (and ship) 47 separate full .dtb blobs. Binary devicetree overlays can make this much more efficient by factoring the common bits into a single base .dtb and representing each of the 47 boards as a small .dtbo overlay.
Even though .dtbo overlay semantics are a natural fit for case #2 (since they derive from source-level .dts overlays, which were designed for board/SoC families), upstream Linux has mostly reserved compiled .dtso -> .dtbo overlays for case #1. Many Android phones attempt to use .dtso overlays for case #2 by describing the SoC as the base devicetree and describing boards in .dtso overlays, but forcing the binary base/overlay split into the source files has drawbacks: there is still lots of duplication between board overlays, and upstream reception towards structuring board source files this way has been lukewarm [1].
This patch series introduces a tool to decouple binary .dtbo generation from .dts source structure. The idea (suggested by Konrad Dybcio at LPC) is to continue to represent all the boards in a family as normal standalone device trees in source code (using .dtsi includes as makes sense for human readability). Then, after building the full .dtb blobs, fdtfactor automatically factors them into a common base .dtb and a set of per-board .dtbo overlays.
This tool has quite a few advantages over other solutions:
1. No change to the way device trees are stored / arranged upstream.
2. No need to deal with some of the awkwardness / limitations of overlays.
3. Better savings than just a simple partitioning, like between SoC and boards.
I've used fdtfactor -S to reduce sc7180-trogdor device tree files (which are stored lz4 compressed) from 1.08 MB (built without -@ -L) to 214 KB, an 80.2% savings.
To compare against the manual SoC-base + board-overlay split used by downstream Android kernels, I also tested fdtfactor -S on the downstream Pixel 10 family device trees (29 physical hardware board
variants: 27 phone variants across Pixel 10, Pixel 10 Pro, and Pixel 10 Pro XL plus 2 socketed dev board variants) by combining the downstream base + overlays into full board DTBs and re-factoring them with fdtfactor -S:
* Just B0 silicon (29 boards):
- Full unfactored DTBs (29 .dtbs): 26.30 MB uncompressed (5.28 MB
lz4)
- Downstream manual SoC base (`lga-b0.dtb`) + 29 board `.dtbo`s:
8.06 MB uncompressed (1.66 MB lz4) - Auto-factored with fdtfactor -S (1 base.dtb + 29 .dtbos):
3.27 MB uncompressed (668 KB lz4) -- 2.48x smaller than the manual SoC split (and 3.68x smaller across the 27 phone boards alone, where average overlay size drops from 252 KB to 44 KB uncompressed, or 52 KB to 9.1 KB lz4).
* Both A0 and B0 SoC steppings:
In practice, phone Proto boards (8 variants) only ever use A0 silicon, phone EVT1.1+ boards (15 variants) only ever use B0 silicon, and only phone EVT1 boards (4 variants) and the socketed dev boards (2 variants) can have either A0 or B0 silicon -- giving 35 realistic (board, stepping) combinations (14 A0 + 21 B0), compared to 58 for a naive 29 x 2 cross-product:
- Full unfactored DTBs (35 .dtbs): 31.71 MB uncompressed (6.37 MB
lz4)
- Downstream manual split (2 SoC bases `lga-a0.dtb` + `lga-b0.dtb` +
29 board `.dtbo`s): 8.78 MB uncompressed (1.79 MB lz4) - Auto-factored with fdtfactor -S (1 shared base.dtb + 35 .dtbos): 4.00 MB uncompressed (855 KB lz4). This could likely be improved more with multiple levels of overlays, but we're already 2x smaller than what downstream is doing today.
NOTE: on Chromebooks like sc7180-trogdor, using overlays like this is an optimization. On Android phones like Pixel 10, the bootloader logic bakes in the need for overlays. Specifically, if we want to be able to build a single image that supports multiple boards and have the bootloader auto-construct the right devicetree, we need the boards to be represented by overlays. This fdtfactor tool can make that a reality.
The fdtfactor tool can either work directly on a set of compiled devicetree files or it can work on a FIT (flattened image tree) file. The idea is that you'd create the FIT file containing all of the duplicated devicetree files and then fdtfactor would "optimize" them.
To test multi-SoC FIT factoring, I also built an upstream Linux arch/arm64 image.fit containing all 438 Qualcomm device trees (367 standalone .dtbs plus 71 composite .dtbs built from 30 add-on .dtbos; gzip-compressed). Comparing the embedded FDT blob totals (with non-factored cases built without -@ -L, and factored cases using fdtfactor -S):
* Plain FIT (438 full .dtbs): 49.13 MB uncompressed (9.27 MB gzip)
* FIT_DECOMPOSE_DTBS=1 alone (deduplicating the 71 composite .dtbs into 367 .dtbs + 30 add-on .dtbos): 36.23 MB uncompressed (6.94 MB gzip)
* fdtfactor alone (41 fdt-base-* groups, 426 board .dtbos, 12 single-board SoCs): 18.26 MB uncompressed (3.59 MB gzip -- 61.3% compressed savings vs. plain)
* FIT_DECOMPOSE_DTBS=1 + fdtfactor (41 fdt-base-* groups, 355 board .dtbos, 30 add-on .dtbos, 12 single-board SoCs): 15.28 MB uncompressed (3.03 MB gzip -- 67.3% compressed savings vs. plain, 56.3% vs. FIT_DECOMPOSE_DTBS=1 alone)
Before introducing fdtfactor itself, the series starts with a few preparatory patches: documenting the existing tools in README.md, adding a DeviceTree live-tree abstraction in pylibfdt/libpydt.py (with supporting Property, FdtRo, and FdtSw enhancements), speeding up libfdt string-table lookups with memchr(), and teaching libfdt's fdt_overlay_apply() to update /__local_fixups__ on the base tree so merged trees retain complete and accurate phandle location metadata (for runtime consumers, composite .dtbs built by fdtoverlay that are later fed into fdtfactor, and round-trip verification against dtc -L).
I'll freely admit that the patches in this series were pretty heavily vibe coded. I'll not pretend that I have a deep understanding of the intricacies of how overlays are implemented. That being said:
* I've spent quite a bit of time reviewing the code from a high-level
perspective: confirming that functions are well documented, well structured, and make sense.
* I believe that what the tool is doing and how the tool is used make sense.
* I have had quite a number of internal "the AI reviews the AI" rounds to the point of diminishing returns.
At this point, I'm not embarrassed to put my name behind this. While I won't promise that there are zero cases of the AI doing something really stupid, I'd be willing to bet that the end result is better (and cleaner / better structured) than what I would have coded up if I had spent a few weeks doing this on my own.
[1] https://lore.kernel.org/all/20251114-elite-refined-yak-bf9e64@kuoka/
v1: https://lore.kernel.org/r/[email protected]
v2: https://lore.kernel.org/r/[email protected]
v3: https://lore.kernel.org/r/[email protected]
Changes in v4:
- New patch adding README.md blurbs for dtc and ancillary tools (David Gibson)
- New patch making Property a subclass of bytes instead of bytearray (David Gibson)
- New patch trimming the returned Fdt bytearray in FdtSw.as_fdt() so DeviceTree.flatten() does not need to call fdt.pack() (David Gibson)
- New patch adding Property.from_*() creation classmethods so DeviceTree does not need its own get_*/set_* wrapper methods (David Gibson)
- New patch speeding up Property.as_list() with a single struct.unpack() call
- New patch speeding up FdtRo.properties() with a C helper
- Start the commit message with the motivation for a live tree and condense the summary (Simon Glass)
- Rename devicetree.py to libpydt.py (under pylibfdt/) to avoid colliding with PyPI's python-devicetree package, and move its unit tests into a separate tests/libpydt_tests.py file (Simon Glass, David Gibson)
- Unflatten the tree in a single O(n) pass using fdt.next_node() instead of recursive O(d * n) fdt.subnodes() traversal, raising FdtException on corrupt/truncated trees, and add a unit test (David Gibson, Simon Glass)
- Implement DeviceTree.walk() iteratively with an explicit stack instead of recursive yield from, and populate node.props directly in unflatten()
- Drop redundant fdt.pack() call from DeviceTree.flatten() (David Gibson)
- Drop get_*/set_* typed wrapper methods from DeviceTree in favor of Property.as_*() and Property.from_*() plus DeviceTree.set_prop() (David Gibson)
- Drop unnecessary copy.deepcopy() and compare unordered node/child sets instead of ordered lists in round-trip test (David Gibson)
- New patch speeding up fdt_find_string_len_() with memchr()
- Split out internal helper fdt_add_empty_subnode_() so overlay_fragment_local_fixups() avoids passing an in-blob pointer to fdt_add_subnode_namelen() or casting fdt_get_name() (Simon Glass)
- Add test cases in tests/overlay.c where the overlay target has no existing subnode under /__local_fixups__, with /__local_fixups__ both before and after the target in the blob (Simon Glass)
- Pass OVERLAY_LOCAL_FIXUPS to tests/run_tests.sh, adjust fdtoverlay_tests for all three modes, and use 4-space indentation (Simon Glass, David Gibson)
- Rename -o/--outdir to -o/--output so standalone DTB mode and FIT mode share the same output option, and use 4-space indentation in tests/run_tests.sh (David Gibson)
- Update for libpydt rename, use Property.as_*(), Property.from_*(), and DeviceTree.set_prop() instead of DeviceTree get_*/set_* wrapper methods, and drop redundant bytes() copies on Property instances (David Gibson, Simon Glass)
- Replace ParsedDtb.raw_bytes with uncompressed_size, use early continue to reduce loop nesting, drop redundant set() before sorted() on local fixup offsets, and clarify pre-order walk and phandle comments (David Gibson)
- Allow dtc -@ -L inputs with no phandles (where dtc omits /__symbols__ and /__local_fixups__)
- Check _is_dtbo_overlay() on the unflattened DeviceTree, index ParsedDtb.nodes and base_nodes by path, and skip unchanged base nodes in _build_board_dtbo() to avoid repeated O(depth) traversals and per-property comparisons
- Handle OVERLAY_LOCAL_FIXUPS != 2 in fdtfactor_tests (Simon Glass)
- Use 4-space indentation instead of mixed tabs and spaces in tests/run_tests.sh, and update context for -o/--output (David Gibson)
- Replace magic-byte/extension auto-detection and --base-compression with a single explicit -C/--compression option controlling both input and output compression (David Gibson)
- Drop unnecessary --stats documentation/help changes and use 4-space indentation in tests/run_tests.sh (David Gibson)
- Use check_factored_dtb in fdtfactor_tests so tests pass when OVERLAY_LOCAL_FIXUPS != 2 (Simon Glass)
- Unify --outfile into -o/--output, and split standalone DTB vs. FIT options into separate README.md subsections and --help groups (David Gibson)
- Check _is_dtbo_overlay() directly in _extract_fit_fdt_entries() instead of adding OverlayBlobError to ParsedDtb (David Gibson)
- Map standard FIT hash algorithm names explicitly via FIT_HASH_ALGOS instead of passing raw names to hashlib.new() (David Gibson)
- Remove compression and entry from FIT grouping, document load, expose --min-overlap, and compute FIT group overlap using normalized property byte costs via _prop_byte_cost() instead of unweighted node paths (David Gibson)
- Strip /__local_fixups__ from unfactored single-board FIT flat_dt entries when -S/--strip-local-fixups is passed, and pick the next unused fdt-base-N node name instead of rejecting FITs that already contain fdt-base-* nodes
- Pass already-unflattened FactoredTree into ParsedDtb and intern normalized properties to integer IDs in group_fit_dtbs() to speed up multi-SoC FIT factoring
- Preserve whether input FIT FDT descriptions include a compression extension instead of unconditionally appending one
- Update for libpydt rename, use Property.as_*(), Property.from_*(), and DeviceTree.set_prop() instead of DeviceTree get_*/set_* wrapper methods, and drop redundant bytes() copies on Property instances (David Gibson, Simon Glass)
- Use check_factored_dtb and 4-space indentation in tests/run_tests.sh (Simon Glass, David Gibson)
- Drop patches 1-6 and 8-10 from v3 (applied upstream by David Gibson)
- Add preparatory README.md patch documenting dtc and ancillary tools (David Gibson)
- Add pylibfdt preparatory patches making Property a subclass of bytes, trimming FdtSw.as_fdt() to totalsize(), adding Property.from_*() creation helpers (David Gibson), and speeding up Property.as_list() and FdtRo.properties()
- Rename devicetree.py to pylibfdt/libpydt.py and address v3 review feedback on DeviceTree (Simon Glass, David Gibson)
- Add preparatory libfdt patch speeding up fdt_find_string_len_() with memchr()
- Update cover letter motivation for fdt_overlay_apply() /__local_fixups__ handling (Simon Glass)
- Replace compression auto-detection with explicit -C/--compression, unify -o/--output across DTB and FIT modes, and group FIT FDTs by configurable --min-overlap shared normalized property byte cost instead of a hardcoded 50% node-path heuristic (David Gibson)
- Speed up multi-SoC FIT factoring, parallelize blob compression/decompression, and add Qualcomm FIT space-savings numbers (and non--@ -L sc7180-trogdor baseline) to cover letter
- New patch parallelizing blob compression and decompression across worker threads
Changes in v3:
- Move NodeTree out of pylibfdt/libfdt.i into a new devicetree.py module and rename it to DeviceTree (David Gibson)
- Store libfdt.Property objects in self.props instead of raw bytes (David Gibson)
- Return a packed libfdt.Fdt object from flatten() instead of raw bytes and use fdt.set_boot_cpuid_phys() (David Gibson, Simon Glass)
- Raise ValueError in unflatten() on duplicate property or sibling subnode names (Simon Glass)
- Move constifying fdto in overlay_apply_node() into a standalone preparatory patch (David Gibson)
- Gate /__local_fixups__ handling behind a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS flag (0=ignore, 1=strip, 2=update), defaulting to 0 (IGNORE) in libfdt_internal.h for embedded builds and 2 (UPDATE) in Meson/Make desktop builds (Simon Glass, David Gibson)
- Rewrite commit message in the present tense with motivation up front, and update fdt_overlay_apply() documentation in libfdt/libfdt.h (Simon Glass)
- Require a strict relative path in overlay_create_path() and return -FDT_ERR_BADOVERLAY on empty path components or trailing '/' (David Gibson)
- Eliminate the 256-byte namebuf limit in overlay_fragment_local_fixups() by re-reading the node name from the shifted ancestor offset after fdt_add_subnode_namelen() (David Gibson, Simon Glass)
- Return -FDT_ERR_BADVALUE instead of -FDT_ERR_BADSTRUCTURE in overlay_add_local_fixup_offset() when an existing /__local_fixups__ property length is not a multiple of 4 (David Gibson, Simon Glass)
- Drop redundant overlay_validate_local_fixups() pre-pass and inline single-use helpers (Simon Glass)
- Update fdtfactor to use devicetree.DeviceTree and a FactoredTree subclass initializing self.phandle and self.fixups in __init__() (David Gibson, Simon Glass)
- Rename -b/--base-dtb to --output-base-dtb to avoid confusion with an input base DTB (David Gibson)
- Move the test rejecting input DTBs lacking /__local_fixups__ from the -S patch into this base patch (Simon Glass)
- Include both non--S (932 KB) and -S (634 KB) Trogdor size numbers in the commit message to show the savings of -S itself (Simon Glass)
- Pass -S to the negative test verifying that inputs lacking /__local_fixups__ are still rejected when -S is used, and move the non--S rejection test to the base fdtfactor patch (Simon Glass)
- Update for -b/--base-dtb rename to --output-base-dtb (David Gibson)
- Use "FIT" instead of "FIT image" in documentation, comments, and commit messages (Simon Glass)
- Update for DeviceTree and --output-base-dtb (Simon Glass, David Gibson)
- Drop "pylibfdt: Fix FdtSw.as_fdt() when buffer is nearly full" and "pylibfdt: Add subnode/property iterators and get_mem_rsv_list()" (applied upstream by David Gibson)
- Split fixup offset overflow fix, redundant memchr() check cleanup, iterator docstring/test follow-up, Property.as_str()/as_stringlist() empty-property handling, Fdt.set_boot_cpuid_phys(), Property.__copy__()/__deepcopy__(), and overlay_apply_node() const fdto into standalone patches (David Gibson, Simon Glass)
- Move NodeTree into a new devicetree.py module as DeviceTree (David Gibson)
- Gate fdt_overlay_apply() /__local_fixups__ handling behind a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS option (Simon Glass, David Gibson)
Changes in v2:
- Split live tree representation out of fdtfactor (David Gibson)
- New patch updating base /__local_fixups__ in libfdt fdt_overlay_apply() instead of stripping /__local_fixups__ by default (David Gibson)
- Preserve /__local_fixups__ on base.dtb by default (David Gibson)
- Store parsed trees directly in NodeTree with node.phandle and node.fixups attributes instead of parallel dicts (David Gibson)
- Extract phandles in a separate pass after unflattening and reject legacy linux,phandle properties (David Gibson)
- Exclude non-root common phandle nodes lacking a common symbol from base.dtb instead of synthesizing __fdtfactor_ph_* symbols (David Gibson)
- Drop -q/--quiet, rename -v/--verbose to -s/--stats, and move tests to a dedicated fdtfactor test suite (David Gibson)
- Split -S/--strip-local-fixups into a separate opt-in patch (David Gibson)
- Add --base-compression to explicitly control base.dtb compression while documenting auto-detection from --base-dtb's filename suffix (David Gibson)
- Support legacy LZ4 frames (lz4 -l) and use CRC32 check for XZ outputs (Simon Glass)
- Rename -f/--fit and -F/--fit-out to -F/--fit and --outfile and clarify FIT mode in the --help description (David Gibson, Simon Glass)
- Reject signed FIT images with signature* subnodes (Simon Glass)
- Use '<base-node-name>.dtb' for FIT base FDT descriptions instead of common-prefix heuristics (Simon Glass)
- Compare FIT group node overlap against the group's common node set instead of only the first entry (Simon Glass)
- Document in README.md that U-Boot's boot_get_fdt_fit() currently requires FIT overlays to be uncompressed (Simon Glass)
- Drop "tests: Fix Python test environment setup in meson.build" (applied upstream by David Gibson)
- Clarify source-level (.dts/.dtsi) vs. binary-level (.dtb/.dtbo) overlay history in cover letter (David Gibson)
- Add Pixel 10 (Tensor G5) base + overlay comparison numbers to cover letter (Simon Glass)
Douglas Anderson (14):
README: Add overview blurbs for dtc and ancillary tools
pylibfdt: Make Property a subclass of bytes instead of bytearray
pylibfdt: Trim Fdt bytearray to totalsize() in FdtSw.as_fdt()
pylibfdt: Add Property.from_*() creation methods
pylibfdt: Unpack Property.as_list() in a single struct.unpack() call
pylibfdt: Speed up FdtRo.properties() with a C helper
libpydt: Add DeviceTree live tree representation
libfdt: Speed up fdt_find_string_len_() with memchr()
libfdt: overlay: Update base /__local_fixups__ on apply
fdtfactor: Add tool to split DTBs into a base DTB and overlays
fdtfactor: Add -S/--strip-local-fixups option
fdtfactor: Support compressed DTB inputs and outputs
fdtfactor: Add compiled FIT factoring support
fdtfactor: Parallelize blob compression and decompression
Makefile | 8 +- README.md | 189 +++ fdtfactor | 1852 ++++++++++++++++++++++++++++ libfdt/fdt.c | 14 +- libfdt/fdt_overlay.c | 525 +++++++- libfdt/fdt_rw.c | 37 +- libfdt/libfdt.h | 7 + libfdt/libfdt_internal.h | 23 + meson.build | 6 + meson_options.txt | 2 + pylibfdt/libfdt.i | 141 ++- pylibfdt/libpydt.py | 184 +++ pylibfdt/meson.build | 2 + tests/Makefile.tests | 13 +- tests/fdtfactor_board1.dts | 72 ++ tests/fdtfactor_board2.dts | 70 ++ tests/fdtfactor_board3.dts | 68 + tests/fdtfactor_board3_shifted.dts | 68 + tests/fdtfactor_lz4.its | 109 ++ tests/fdtfactor_other1.dts | 67 + tests/fdtfactor_other2.dts | 67 + tests/fdtfactor_test.its | 109 ++ tests/libpydt_tests.py | 106 ++ tests/meson.build | 5 +- tests/overlay.c | 154 +++ tests/pylibfdt_tests.py | 55 + tests/run_tests.sh | 446 ++++++- tests/testutils.sh | 1 + 28 files changed, 4354 insertions(+), 46 deletions(-) create mode 100755 fdtfactor create mode 100644 pylibfdt/libpydt.py create mode 100644 tests/fdtfactor_board1.dts create mode 100644 tests/fdtfactor_board2.dts create mode 100644 tests/fdtfactor_board3.dts create mode 100644 tests/fdtfactor_board3_shifted.dts create mode 100644 tests/fdtfactor_lz4.its create mode 100644 tests/fdtfactor_other1.dts create mode 100644 tests/fdtfactor_other2.dts create mode 100644 tests/fdtfactor_test.its create mode 100644 tests/libpydt_tests.py
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 1/14 README: Add overview blurbs for dtc and ancillary tools
README.md currently jumps directly from building dtc and pylibfdt to mailing list information without mentioning dtc itself or the ancillary utilities built and installed alongside it.
Add brief overview sections with basic usage examples for dtc, dtdiff, fdtget, fdtput, fdtdump, convert-dtsv0, and fdtoverlay (along with a pointer to Documentation/manual.txt for full command-line details).
---
Changes in v4:
- New patch adding README.md blurbs for dtc and ancillary tools (David Gibson)
README.md | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+)
README.md +89 -0
@@ -112,6 +112,95 @@ $ meson setup -Dpython=disabled build More work remains to support all of libfdt, including access to numeric values. +## dtc + +`dtc` compiles device tree source (`.dts`) into flattened device tree +blobs (`.dtb`), decompiles `.dtb` blobs or `/proc/device-tree`-style +filesystem trees (`fs`) back to `.dts`, emits YAML (`.yaml`, when built +with `libyaml`) or assembly (`.S`), and runs semantic checks on the +tree: + +``` +$ dtc -I dts -O dtb -o board.dtb board.dts +$ dtc -I dtb -O dts -o board.dts board.dtb +``` + +See `Documentation/manual.txt` for full command-line reference +documentation for `dtc` and the C utility tools below. + +## dtdiff + +`dtdiff` normalizes and sorts two device trees via `dtc -s -O dts` and +prints a unified diff between them. Each input may be a `.dts` source +file, a `.dtb` / `.dtbo` blob, or a `/proc/device-tree`-style directory: + +``` +$ dtdiff before.dtb after.dtb +$ dtdiff board.dts /proc/device-tree +``` + +## fdtget + +`fdtget` reads property values (`<node> <property>` pairs), lists +property names (`-p`, `--properties`), or lists subnode names (`-l`, +`--list`) from a `.dtb` blob. Use `-t`, `--type` (e.g. `-ts` for +strings, `-ti` / `-tu` / `-tx` for signed, unsigned, or hex integers, or +`-tr` for raw bytes) to control formatting, and `-d`, `--default` to +provide a fallback when a node or property is missing: + +``` +$ fdtget board.dtb / model /cpus/cpu@0 reg +$ fdtget -tx board.dtb /soc/serial@1000 reg +$ fdtget -l board.dtb /soc +``` + +## fdtput + +`fdtput` modifies a `.dtb` blob in place: writing property values, +creating nodes (`-c`, `--create`), deleting nodes and their subnodes +(`-r`, `--remove`), or deleting properties (`-d`, `--delete`). Pass +`-t`, `--type` (e.g. `-ts` for strings or `-tx` for hex integers; +default is decimal integers) to control value encoding, and `-p`, +`--auto-path` to create any missing nodes along the target path: + +``` +$ fdtput -p -ts board.dtb /soc/i2c@3000 compatible vendor,i2c +$ fdtput -tx board.dtb /soc/serial@1000 reg 1000 100 +$ fdtput -d board.dtb /soc/i2c@3000 compatible +``` + +## fdtdump + +`fdtdump` is a low-level debugging tool that dumps the FDT header, +`/memreserve/` entries, and raw structure-block contents of a `.dtb` +blob (`-d`, `--debug` prints tag offsets; `-s`, `--scan` scans a larger +file for an embedded FDT). For general decompilation of a `.dtb` to +`.dts`, use `dtc -I dtb -O dts` instead: + +``` +$ fdtdump -d board.dtb +``` + +## convert-dtsv0 + +`convert-dtsv0` converts obsolete version 0 `.dts` source files to +`/dts-v1/;` syntax, writing each output to `<filename>v1`: + +``` +$ convert-dtsv0 old-board.dts +``` + +## fdtoverlay + +`fdtoverlay` applies one or more compiled `.dtbo` overlays (`-v`, +`--verbose` for progress) onto a base `.dtb` blob (`-i`, `--input`, +compiled with `dtc -@` when overlays reference symbols) and writes the +merged blob to `-o`, `--output`: + +``` +$ fdtoverlay -i base.dtb -o merged.dtb overlay1.dtbo overlay2.dtbo +``` + ## Mailing lists * The [devicetree-compiler](mailto:[email protected])
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 2/14 pylibfdt: Make Property a subclass of bytes instead of bytearray
In reply to Douglas AndersonProperty represents a snapshot of a property's name and value read from a flattened device tree. Making Property a subclass of the immutable bytes type instead of mutable bytearray prevents callers from accidentally mutating a Property instance in place when sharing it across data structures (such as DeviceTree), makes Property hashable, and allows Property instances to be passed directly to Fdt.setprop() without converting to bytes first.
Also return bytes instead of bytearray from the fdt_get_property_by_offset() SWIG typemap and drop the redundant bytearray() conversion in FdtRo.getprop().
---
Changes in v4:
- New patch making Property a subclass of bytes instead of bytearray (David Gibson)
pylibfdt/libfdt.i | 17 +++++++++-------- tests/pylibfdt_tests.py | 1 + 2 files changed, 10 insertions(+), 8 deletions(-)
pylibfdt/libfdt.i +9 -8
@@ -492,7 +492,7 @@ class FdtRo(object): Returns: Value of property as a Property object (which can be used as a - bytearray/string), or -ve error number. On failure, returns an + bytes/string), or -ve error number. On failure, returns an integer error Raises:
@@ -502,7 +502,7 @@ class FdtRo(object): quiet) if pdata[0] is None: return pdata[1] - return Property(prop_name, bytearray(pdata[0])) + return Property(prop_name, pdata[0]) def hasprop(self, nodeoffset, prop_name, quiet=()): """Check if a node has a property
@@ -893,7 +893,7 @@ class Fdt(FdtRo): return check_err(fdt_del_node(self._fdt, nodeoffset), quiet) -class Property(bytearray): +class Property(bytes): """Holds a device tree property name and value. This holds a copy of a property taken from the device tree. It does not
@@ -902,11 +902,12 @@ class Property(bytearray): Properties: name: Property name - value: Property value as a bytearray + value: Property value as bytes """ - def __init__(self, name, value): - bytearray.__init__(self, value) - self.name = name + def __new__(cls, name, value): + obj = super().__new__(cls, value) + obj.name = name + return obj def __copy__(self): return type(self)(self.name, self)
@@ -1275,7 +1276,7 @@ typedef uint32_t fdt32_t; if ($1) { resultobj = PyUnicode_FromString( fdt_string(fdt1, fdt32_to_cpu($1->nameoff))); - buff = PyByteArray_FromStringAndSize( + buff = PyBytes_FromStringAndSize( (const char *)($1 + 1), fdt32_to_cpu($1->len)); resultobj = SWIG_AppendOutput(resultobj, buff); }
tests/pylibfdt_tests.py +1 -0
@@ -191,6 +191,7 @@ class PyLibfdtBasicTests(unittest.TestCase): root = 0 poffset = self.fdt.first_property_offset(root) prop = self.fdt.get_property_by_offset(poffset) + self.assertIsInstance(prop, bytes) self.assertEqual(prop.name, 'compatible') self.assertEqual(prop, b'test_tree1\0') for copied in (copy.copy(prop), copy.deepcopy(prop)):
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 3/14 pylibfdt: Trim Fdt bytearray to totalsize() in FdtSw.as_fdt()
In reply to Douglas Andersonfdt_finish() relocates the string table directly after the structure block and updates the FDT header totalsize to the packed size, but FdtSw.as_fdt() left the backing Python bytearray at the pre-allocated FdtSw buffer size (with trailing zero bytes beyond totalsize()), forcing callers that serialize fdt.as_bytearray() to call fdt.pack() just to truncate _fdt.
Truncate fdtsw to fdt_totalsize(fdtsw) in FdtSw.as_fdt() (matching Fdt.pack()) so the returned Fdt's as_bytearray() length matches its totalsize() immediately.
---
Changes in v4:
- New patch trimming the returned Fdt bytearray in FdtSw.as_fdt() so DeviceTree.flatten() does not need to call fdt.pack() (David Gibson)
pylibfdt/libfdt.i | 1 + tests/pylibfdt_tests.py | 2 ++ 2 files changed, 3 insertions(+)
pylibfdt/libfdt.i +1 -0
@@ -1026,6 +1026,7 @@ class FdtSw(FdtRo): fdtsw = bytearray(self._fdt) while self.check_space(fdt_finish(fdtsw)): fdtsw = bytearray(self._fdt) + del fdtsw[fdt_totalsize(fdtsw):] return Fdt(fdtsw) def check_space(self, val):
tests/pylibfdt_tests.py +2 -0
@@ -684,6 +684,7 @@ class PyLibfdtSwTests(unittest.TestCase): # Make sure we did at least two resizes self.assertTrue(len(fdt.as_bytearray()) > FdtSw.INC_SIZE * 2) + self.assertEqual(fdt.totalsize(), len(fdt.as_bytearray())) # Check that as_fdt() resizes when fewer than 4 bytes remain for FDT_END sw_exact = FdtSw(76)
@@ -692,6 +693,7 @@ class PyLibfdtSwTests(unittest.TestCase): sw_exact.end_node() fdt_exact = sw_exact.as_fdt() self.assertEqual(80, fdt_exact.totalsize()) + self.assertEqual(80, len(fdt_exact.as_bytearray())) class PyLibfdtRoTests(unittest.TestCase):
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 4/14 pylibfdt: Add Property.from_*() creation methods
In reply to Douglas Andersonlibfdt.Property provides as_*() methods (as_cell, as_uint32, as_int32, as_uint64, as_int64, as_list, as_uint32_list, as_int32_list, as_uint64_list, as_int64_list, as_str, and as_stringlist) to decode typed values from a Property, but lacks the corresponding creation methods to construct a Property from typed values.
Add from_*() classmethods mirroring each as_*() method so callers (such as DeviceTree users) can construct typed Property instances directly without duplicating encoding helpers on DeviceTree.
---
Changes in v4:
- New patch adding Property.from_*() creation classmethods so DeviceTree does not need its own get_*/set_* wrapper methods (David Gibson)
pylibfdt/libfdt.i | 56 +++++++++++++++++++++++++++++++++++++++++ tests/pylibfdt_tests.py | 49 ++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+)
pylibfdt/libfdt.i +56 -0
@@ -962,6 +962,62 @@ class Property(bytes): parts = self[:-1].split(b'\x00') return list(map(lambda x: x.decode('utf-8'), parts)) + @classmethod + def from_cell(cls, name, fmt, val): + return cls(name, struct.pack('>' + fmt, val)) + + @classmethod + def from_uint32(cls, name, val): + return cls.from_cell(name, 'L', val) + + @classmethod + def from_int32(cls, name, val): + return cls.from_cell(name, 'l', val) + + @classmethod + def from_uint64(cls, name, val): + return cls.from_cell(name, 'Q', val) + + @classmethod + def from_int64(cls, name, val): + return cls.from_cell(name, 'q', val) + + @classmethod + def from_list(cls, name, fmt, vals): + vals = list(vals) + return cls(name, struct.pack(f'>{len(vals)}{fmt}', *vals)) + + @classmethod + def from_uint32_list(cls, name, vals): + return cls.from_list(name, 'L', vals) + + @classmethod + def from_int32_list(cls, name, vals): + return cls.from_list(name, 'l', vals) + + @classmethod + def from_uint64_list(cls, name, vals): + return cls.from_list(name, 'Q', vals) + + @classmethod + def from_int64_list(cls, name, vals): + return cls.from_list(name, 'q', vals) + + @classmethod + def from_str(cls, name, val): + """Unicode is supported by encoding to UTF-8""" + if '\x00' in val: + raise ValueError('String value contains embedded nul characters') + return cls(name, val.encode('utf-8') + b'\x00') + + @classmethod + def from_stringlist(cls, name, vals): + """Unicode is supported by encoding to UTF-8""" + vals = list(vals) + if any('\x00' in v for v in vals): + raise ValueError('String value contains embedded nul characters') + return cls(name, b''.join(v.encode('utf-8') + b'\x00' for v in vals)) + class FdtSw(FdtRo): """Software interface to create a device tree from scratch
tests/pylibfdt_tests.py +49 -0
73 lines not on this page · raw message
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 5/14 pylibfdt: Unpack Property.as_list() in a single struct.unpack() call
In reply to Douglas AndersonProperty.as_list() currently decodes multi-cell properties via list(map(lambda x: x[0], struct.iter_unpack('>' + fmt, self))), which constructs an iterator and map wrapper and invokes a Python lambda for every cell.
Compute the element size via struct.calcsize('>' + fmt) and unpack all elements in a single C struct.unpack() call instead.
On one stress test (decoding ~301k /__local_fixups__ cell lists across 438 arm64 Qualcomm DTBs) this reduced Property.as_list() time by ~2.1x.
---
Found this speedup while benchmarking fdtfactor. It's not critical to functionality, but seems like a nice win.
Changes in v4:
- New patch speeding up Property.as_list() with a single struct.unpack() call
pylibfdt/libfdt.i | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
pylibfdt/libfdt.i +2 -1
@@ -931,7 +931,8 @@ class Property(bytes): return self.as_cell('q') def as_list(self, fmt): - return list(map(lambda x: x[0], struct.iter_unpack('>' + fmt, self))) + size = struct.calcsize('>' + fmt) + return list(struct.unpack(f'>{len(self) // size}{fmt}', self)) def as_uint32_list(self): return self.as_list('L')
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 6/14 pylibfdt: Speed up FdtRo.properties() with a C helper
In reply to Douglas AndersonIterating over a node's properties via FdtRo.properties() currently crosses the Python/SWIG boundary 1 + 2 * num_props times per node (first_property_offset(), get_property_by_offset(), and next_property_offset(), along with their Python check_err() and check_err_null() wrappers). When walking every property across large device trees from Python, those per-property SWIG round-trips dominate runtime.
Add a C helper fdt_node_properties_stub() in pylibfdt/libfdt.i backing FdtRo.properties() so all Property objects for a node are collected in a single C call per node, interning property name strings via PyUnicode_InternFromString(). Also add an invalid-offset exception check to testPropertiesIterator in tests/pylibfdt_tests.py.
On one stress test (walking all ~573k nodes and ~2.06M properties across 438 arm64 Qualcomm DTBs) this reduced FdtRo.properties() time by ~1.8x.
---
Found this speedup while benchmarking fdtfactor. It's not critical to functionality, but seems like a nice win.
Changes in v4:
- New patch speeding up FdtRo.properties() with a C helper
pylibfdt/libfdt.i | 64 ++++++++++++++++++++++++++++++++++++++--- tests/pylibfdt_tests.py | 3 ++ 2 files changed, 63 insertions(+), 4 deletions(-)
pylibfdt/libfdt.i +60 -4
@@ -24,6 +24,61 @@ static int fdt_property_stub(void *fdt, const char *name, const void *val, return fdt_property(fdt, name, val, len); } +static PyObject *fdt_node_properties_stub(const void *fdt, int nodeoffset, + PyObject *prop_cls) +{ + PyObject *list = PyList_New(0); + int poff; + + if (!list) + return NULL; + + poff = fdt_first_property_offset(fdt, nodeoffset); + while (poff >= 0) { + const char *pname; + int len; + const void *val = fdt_getprop_by_offset(fdt, poff, &pname, &len); + PyObject *name_obj, *val_obj, *prop_obj; + int rc; + + if (!val) { + Py_DECREF(list); + return PyLong_FromLong(len); + } + name_obj = PyUnicode_InternFromString(pname); + if (!name_obj) { + Py_DECREF(list); + return NULL; + } + val_obj = PyBytes_FromStringAndSize((const char *)val, len); + if (!val_obj) { + Py_DECREF(name_obj); + Py_DECREF(list); + return NULL; + } + prop_obj = PyObject_CallFunctionObjArgs(prop_cls, name_obj, val_obj, + NULL); + Py_DECREF(name_obj); + Py_DECREF(val_obj); + if (!prop_obj) { + Py_DECREF(list); + return NULL; + } + rc = PyList_Append(list, prop_obj); + Py_DECREF(prop_obj); + if (rc < 0) { + Py_DECREF(list); + return NULL; + } + poff = fdt_next_property_offset(fdt, poff); + } + if (poff != -FDT_ERR_NOTFOUND) { + Py_DECREF(list); + return PyLong_FromLong(poff); + } + return list; +} + %} %pythoncode %{
@@ -477,10 +532,9 @@ class FdtRo(object): Raises: FdtException on error (e.g. invalid nodeoffset) """ - poff = self.first_property_offset(nodeoffset, quiet=QUIET_NOTFOUND) - while poff >= 0: - yield self.get_property_by_offset(poff) - poff = self.next_property_offset(poff, quiet=QUIET_NOTFOUND) + return iter(check_err( + fdt_node_properties_stub(self._fdt, nodeoffset, Property) + )) def getprop(self, nodeoffset, prop_name, quiet=()): """Get a property from a node
@@ -1420,5 +1474,7 @@ int fdt_property_cell(void *fdt, const char *name, uint32_t val); * function and a struct, which confuses SWIG. */ int fdt_property_stub(void *fdt, const char *name, const void *val, int len); +PyObject *fdt_node_properties_stub(const void *fdt, int nodeoffset, + PyObject *prop_cls); %include <libfdt.h>
tests/pylibfdt_tests.py +3 -0
@@ -270,6 +270,9 @@ class PyLibfdtBasicTests(unittest.TestCase): self.assertEqual(props[0], b'subnode1\0') leaf = self.fdt.path_offset('/subnode@1/ss1') self.assertEqual(list(self.fdt.properties(leaf)), []) + with self.assertRaises(FdtException) as e: + list(self.fdt.properties(-1)) + self.assertEqual(e.exception.err, -libfdt.BADOFFSET) def testFirstNextSubnodeOffsetExceptions(self): """Check except handling for first/next subnode functions"""
Signature · 1 line
2.56.0.679.gc527c65306-goog
Re: [PATCH v4 06/14] pylibfdt: Speed up FdtRo.properties() with a C helper
Quoted 14 lines · Douglas Anderson
Iterating over a node's properties via
FdtRo.properties()currently crosses the Python/SWIG boundary1 + 2 * num_propstimes per node (first_property_offset(),get_property_by_offset(), andnext_property_offset(), along with their Pythoncheck_err()andcheck_err_null()wrappers). When walking every property across large device trees from Python, those per-property SWIG round-trips dominate runtime.Add a C helper
fdt_node_properties_stub()inpylibfdt/libfdt.ibackingFdtRo.properties()so allPropertyobjects for a node are collected in a single C call per node, interning property name strings viaPyUnicode_InternFromString(). Also add an invalid-offset exception check totestPropertiesIteratorintests/pylibfdt_tests.py.
Quoted 6 lines
On one stress test (walking all ~573k nodes and ~2.06M properties across 438 arm64 Qualcomm DTBs) this reduced
FdtRo.properties()time by ~1.8x.Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>
Hm, optimizing pylibfdt has never been a focus, on the general assumption that if speed is really important to you, you shouldn't be using Python. I'm happy enough with patch 4, because it's a speed win with a very small and simple change. This optimization is a much larger chunk of code, so I'm not so convinced this is worth the source complexity we pay for it.
That's not an outright rejection, but I'd need convincing this is worth it.
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
Re: [PATCH v4 06/14] pylibfdt: Speed up FdtRo.properties() with a C helper
Hi David,
Quoted 12 lines · David Gibson
Quoted 4 lines
On one stress test (walking all ~573k nodes and ~2.06M properties across 438 arm64 Qualcomm DTBs) this reduced
FdtRo.properties()time by ~1.8x.Hm, optimizing pylibfdt has never been a focus, on the general assumption that if speed is really important to you, you shouldn't be using Python. I'm happy enough with patch 4, because it's a speed win with a very small and simple change. This optimization is a much larger chunk of code, so I'm not so convinced this is worth the source complexity we pay for it.
Quoted 2 lines
That's not an outright rejection, but I'd need convincing this is worth it.
Right, if we're trying to get the absolute maximum speed then of course we wouldn't choose Python. For a tool like fdtfactor, speed is certainly not the top priority and Python is the superior choice. Writing it in C would have been a much bigger pain.
That all being said, just because speed isn't the top priority doesn't mean it doesn't matter at all. When I started looking at optimizations I was seeing my 438-DTB run take ~25 seconds, which is just a bit too much. With all the optimizations I ended up with ~12 seconds. That's still a lot and it would be nice to make it even better, but it also starts getting into the realm of acceptable.
FdtRo.properties() stood out in profiling because DeviceTree.unflatten() calls it on every node (~573k nodes / ~2.06M properties across the 438 Qualcomm DTBs). In the pure-Python generator, each node makes 1 + 2 * num_props SWIG calls (~4.7M boundary crossings, each going through Python check_err / check_err_null wrappers and generator suspension/resumption) and allocates a fresh non-interned str for repeated property names like compatible, reg, status, and phandle.
Below is a small standalone script (bench_properties.py) that builds a 1,300-node (~140 KB) DTB in memory via FdtSw and walks it 400 times (~520k nodes, ~2.08M properties) with patch 06/14 applied. On my machine:
* Default meson setup build (-O0):
- FdtRo.properties(): 2.52s -> 1.50s (1.68x faster)
- Full tree walk: 3.35s -> 2.25s (1.49x faster)
* meson setup --buildtype=release (-O3):
- FdtRo.properties(): 1.76s -> 0.98s (1.81x faster)
- Full tree walk: 2.24s -> 1.43s (1.57x faster)
On the source-complexity side, roughly half of fdt_node_properties_stub() in v4 is repetitive Py_DECREF error-cleanup boilerplate -- using PyObject_CallFunction(prop_cls, "Oy#", ...) and a single err: label trims it from 55 lines down to ~30 lines. That said, as noted in the patch notes, ~1 second on a 400-DTB run isn't make-or-break, so if you'd still rather not carry the C helper in pylibfdt/libfdt.i I'm totally fine dropping this patch in v5 (or trimming it to the ~30-line version if that tips the balance).
---8<---
#!/usr/bin/env python3
# SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) # Run from the dtc repo root after applying patch 06/14 and building:
# meson compile -C build && python3 bench_properties.py
import os
import sys
import time
if os.path.isdir('build/pylibfdt') and 'build/pylibfdt' not in sys.path:
sys.path.insert(0, 'build/pylibfdt')
import libfdt
from libfdt import QUIET_NOTFOUND
def old_properties(fdt, nodeoffset):
poff = fdt.first_property_offset(nodeoffset, quiet=QUIET_NOTFOUND) while poff >= 0:
yield fdt.get_property_by_offset(poff)
poff = fdt.next_property_offset(poff, quiet=QUIET_NOTFOUND)
def unflatten_walk(fdt, props_fn):
off, depth = 0, 0
while depth >= 0:
props = {p.name: p for p in props_fn(fdt, off)} if depth > 0:
fdt.get_name(off)
off, depth = fdt.next_node(off, depth)
return props
def make_sample_dtb(num_nodes=1300):
sw = libfdt.FdtSw()
sw.finish_reservemap()
with sw.add_node(''):
sw.property_string('compatible', 'example,board')
sw.property_u32('#address-cells', 2)
sw.property_u32('#size-cells', 2)
with sw.add_node('soc@0'):
for i in range(num_nodes):
with sw.add_node(f'dev@{i:x}'):
sw.property_string('compatible', 'vendor,periph')
sw.property('reg', b'\x00\x00\x00\x00' * 4)
sw.property_string('status', 'okay')
sw.property_u32('phandle', i + 1)
return sw.as_fdt()def main():
if not hasattr(libfdt, 'fdt_node_properties_stub'):
sys.exit('Apply patch 06/14 and rebuild pylibfdt first')
fdt = make_sample_dtb()
offsets = []
off, depth = 0, 0
while depth >= 0:
offsets.append(off)
off, depth = fdt.next_node(off, depth)
iters = 400 # ~520k nodes, ~2.08M props (similar to 438 arm64 DTBs)
t0 = time.perf_counter()
for _ in range(iters):
for o in offsets:
for _ in old_properties(fdt, o):
pass
dt_old = time.perf_counter() - t0
t0 = time.perf_counter()
for _ in range(iters):
for o in offsets:
for _ in fdt.properties(o):
pass
dt_new = time.perf_counter() - t0
t0 = time.perf_counter()
for _ in range(iters):
unflatten_walk(fdt, old_properties)
dt_unf_old = time.perf_counter() - t0
t0 = time.perf_counter()
for _ in range(iters):
unflatten_walk(fdt, libfdt.FdtRo.properties)
dt_unf_new = time.perf_counter() - t0
sz = fdt.totalsize()
print(f'{len(offsets)} nodes ({sz:,} B) x {iters} trees:') print(f' FdtRo.properties() old (SWIG loop): {dt_old:.3f} s') print(f' FdtRo.properties() new (C helper): {dt_new:.3f} s '
f'({dt_old / dt_new:.2f}x faster)')
print(f' Full tree walk old: {dt_unf_old:.3f} s')
print(f' Full tree walk new: {dt_unf_new:.3f} s '
f'({dt_unf_old / dt_unf_new:.2f}x faster)')
if __name__ == '__main__':
main()
--->8---
-Doug
Re: [PATCH v4 06/14] pylibfdt: Speed up FdtRo.properties() with a C helper
Quoted 51 lines · Doug Anderson
Hi David,
Quoted 12 lines · David Gibson
Quoted 4 lines
On one stress test (walking all ~573k nodes and ~2.06M properties across 438 arm64 Qualcomm DTBs) this reduced
FdtRo.properties()time by ~1.8x.Hm, optimizing pylibfdt has never been a focus, on the general assumption that if speed is really important to you, you shouldn't be using Python. I'm happy enough with patch 4, because it's a speed win with a very small and simple change. This optimization is a much larger chunk of code, so I'm not so convinced this is worth the source complexity we pay for it.
Quoted 2 lines
That's not an outright rejection, but I'd need convincing this is worth it.
Right, if we're trying to get the absolute maximum speed then of course we wouldn't choose Python. For a tool like
fdtfactor, speed is certainly not the top priority and Python is the superior choice. Writing it in C would have been a much bigger pain.That all being said, just because speed isn't the top priority doesn't mean it doesn't matter at all. When I started looking at optimizations I was seeing my 438-DTB run take ~25 seconds, which is just a bit too much. With all the optimizations I ended up with ~12 seconds. That's still a lot and it would be nice to make it even better, but it also starts getting into the realm of acceptable.
FdtRo.properties()stood out in profiling becauseDeviceTree.unflatten()calls it on every node (~573k nodes / ~2.06M properties across the 438 Qualcomm DTBs). In the pure-Python generator, each node makes1 + 2 * num_propsSWIG calls (~4.7M boundary crossings, each going through Pythoncheck_err/check_err_nullwrappers and generator suspension/resumption) and allocates a fresh non-internedstrfor repeated property names likecompatible,reg,status, andphandle.Below is a small standalone script (
bench_properties.py) that builds a 1,300-node (~140 KB) DTB in memory viaFdtSwand walks it 400 times (~520k nodes, ~2.08M properties) with patch 06/14 applied. On my machine:
* Defaultmeson setup build(-O0):
-FdtRo.properties():2.52s -> 1.50s(1.68x faster)
- Full tree walk:3.35s -> 2.25s(1.49x faster)
*meson setup --buildtype=release(-O3):
-FdtRo.properties():1.76s -> 0.98s(1.81x faster)
- Full tree walk:2.24s -> 1.43s(1.57x faster)
Quoted 9 lines
On the source-complexity side, roughly half of
fdt_node_properties_stub()in v4 is repetitivePy_DECREFerror-cleanup boilerplate -- usingPyObject_CallFunction(prop_cls, "Oy#", ...)and a singleerr:label trims it from 55 lines down to ~30 lines. That said, as noted in the patch notes, ~1 second on a 400-DTB run isn't make-or-break, so if you'd still rather not carry the C helper inpylibfdt/libfdt.iI'm totally fine dropping this patch in v5 (or trimming it to the ~30-line version if that tips the balance).
Let's leave it out for this series. I'm ok with revisiting this later. Fwiw, gotos for error handling are generally acceptable (along the lines commonly used in the kernel, if that helps).
Quoted 104 lines
---8<---
#!/usr/bin/env python3
# SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) # Run from the dtc repo root after applying patch 06/14 and building:
# meson compile -C build && python3bench_properties.py
import os
import sys
import timeif
os.path.isdir('build/pylibfdt')and 'build/pylibfdt' not in sys.path:
sys.path.insert(0, 'build/pylibfdt')import libfdt
from libfdt importQUIET_NOTFOUNDdef
old_properties(fdt, nodeoffset):
poff =fdt.first_property_offset(nodeoffset, quiet=QUIET_NOTFOUND)while poff >= 0:
yieldfdt.get_property_by_offset(poff)
poff =fdt.next_property_offset(poff, quiet=QUIET_NOTFOUND)def
unflatten_walk(fdt, props_fn):
off, depth = 0, 0
while depth >= 0:
props = {p.name: p for p inprops_fn(fdt, off)} if depth > 0:
fdt.get_name(off)
off, depth =fdt.next_node(off, depth)
return propsdef
make_sample_dtb(num_nodes=1300):sw = libfdt.FdtSw() sw.finish_reservemap() with sw.add_node(''): sw.property_string('compatible', 'example,board') sw.property_u32('#address-cells', 2) sw.property_u32('#size-cells', 2) with sw.add_node('soc@0'): for i in range(num_nodes): with sw.add_node(f'dev@{i:x}'): sw.property_string('compatible', 'vendor,periph') sw.property('reg', b'\x00\x00\x00\x00' * 4) sw.property_string('status', 'okay') sw.property_u32('phandle', i + 1) return sw.as_fdt()def
main():
if nothasattr(libfdt, 'fdt_node_properties_stub'):
sys.exit('Apply patch 06/14 and rebuild pylibfdt first')fdt =
make_sample_dtb()
offsets = []
off, depth = 0, 0
while depth >= 0:
offsets.append(off)
off, depth =fdt.next_node(off, depth)iters = 400 # ~520k nodes, ~2.08M props (similar to 438 arm64 DTBs)
t0 =
time.perf_counter()
for _ in range(iters):
for o in offsets:
for _ inold_properties(fdt, o):
pass
dt_old=time.perf_counter()- t0t0 =
time.perf_counter()
for _ in range(iters):
for o in offsets:
for _ infdt.properties(o):
pass
dt_new=time.perf_counter()- t0t0 =
time.perf_counter()
for _ in range(iters):
unflatten_walk(fdt, old_properties)
dt_unf_old=time.perf_counter()- t0t0 =
time.perf_counter()
for _ in range(iters):
unflatten_walk(fdt, libfdt.FdtRo.properties)
dt_unf_new=time.perf_counter()- t0sz =
fdt.totalsize()
print(f'{len(offsets)} nodes ({sz:,} B) x {iters} trees:')print(f' FdtRo.properties() old (SWIG loop): {dt_old:.3f} s')print(f'FdtRo.properties()new (C helper): {dt_new:.3f} s '
f'({dt_old / dt_new:.2f}x faster)')
print(f' Full tree walk old: {dt_unf_old:.3f} s')
print(f' Full tree walk new: {dt_unf_new:.3f} s '
f'({dt_unf_old / dt_unf_new:.2f}x faster)')if
__name__== '__main__':main()--->8---
-Doug
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
Re: [PATCH v4 06/14] pylibfdt: Speed up FdtRo.properties() with a C helper
Hi,
Quoted 63 lines · David Gibson
Quoted 51 lines · Doug Anderson
Hi David,
Quoted 12 lines · David Gibson
Quoted 4 lines
On one stress test (walking all ~573k nodes and ~2.06M properties across 438 arm64 Qualcomm DTBs) this reduced
FdtRo.properties()time by ~1.8x.Hm, optimizing pylibfdt has never been a focus, on the general assumption that if speed is really important to you, you shouldn't be using Python. I'm happy enough with patch 4, because it's a speed win with a very small and simple change. This optimization is a much larger chunk of code, so I'm not so convinced this is worth the source complexity we pay for it.
Quoted 2 lines
That's not an outright rejection, but I'd need convincing this is worth it.
Right, if we're trying to get the absolute maximum speed then of course we wouldn't choose Python. For a tool like
fdtfactor, speed is certainly not the top priority and Python is the superior choice. Writing it in C would have been a much bigger pain.That all being said, just because speed isn't the top priority doesn't mean it doesn't matter at all. When I started looking at optimizations I was seeing my 438-DTB run take ~25 seconds, which is just a bit too much. With all the optimizations I ended up with ~12 seconds. That's still a lot and it would be nice to make it even better, but it also starts getting into the realm of acceptable.
FdtRo.properties()stood out in profiling becauseDeviceTree.unflatten()calls it on every node (~573k nodes / ~2.06M properties across the 438 Qualcomm DTBs). In the pure-Python generator, each node makes1 + 2 * num_propsSWIG calls (~4.7M boundary crossings, each going through Pythoncheck_err/check_err_nullwrappers and generator suspension/resumption) and allocates a fresh non-internedstrfor repeated property names likecompatible,reg,status, andphandle.Below is a small standalone script (
bench_properties.py) that builds a 1,300-node (~140 KB) DTB in memory viaFdtSwand walks it 400 times (~520k nodes, ~2.08M properties) with patch 06/14 applied. On my machine:
* Defaultmeson setup build(-O0):
-FdtRo.properties():2.52s -> 1.50s(1.68x faster)
- Full tree walk:3.35s -> 2.25s(1.49x faster)
*meson setup --buildtype=release(-O3):
-FdtRo.properties():1.76s -> 0.98s(1.81x faster)
- Full tree walk:2.24s -> 1.43s(1.57x faster)Quoted 9 lines
On the source-complexity side, roughly half of
fdt_node_properties_stub()in v4 is repetitivePy_DECREFerror-cleanup boilerplate -- usingPyObject_CallFunction(prop_cls, "Oy#", ...)and a singleerr:label trims it from 55 lines down to ~30 lines. That said, as noted in the patch notes, ~1 second on a 400-DTB run isn't make-or-break, so if you'd still rather not carry the C helper inpylibfdt/libfdt.iI'm totally fine dropping this patch in v5 (or trimming it to the ~30-line version if that tips the balance).
Quoted 3 lines
Let's leave it out for this series. I'm ok with revisiting this later. Fwiw, gotos for error handling are generally acceptable (along the lines commonly used in the kernel, if that helps).
Sure. Dropped from my draft v5.
-Doug
Re: [PATCH v4 06/14] pylibfdt: Speed up FdtRo.properties() with a C helper
In reply to Douglas AndersonHi Douglas,
Quoted 28 lines · Douglas Anderson
pylibfdt: Speed up
FdtRo.properties()with a C helperIterating over a node's properties via
FdtRo.properties()currently crosses the Python/SWIG boundary1 + 2 * num_propstimes per node (first_property_offset(),get_property_by_offset(), andnext_property_offset(), along with their Pythoncheck_err()andcheck_err_null()wrappers). When walking every property across large device trees from Python, those per-property SWIG round-trips dominate runtime.Add a C helper
fdt_node_properties_stub()inpylibfdt/libfdt.ibackingFdtRo.properties()so allPropertyobjects for a node are collected in a single C call per node, interning property name strings viaPyUnicode_InternFromString(). Also add an invalid-offset exception check totestPropertiesIteratorintests/pylibfdt_tests.py.On one stress test (walking all ~573k nodes and ~2.06M properties across 438 arm64 Qualcomm DTBs) this reduced
FdtRo.properties()time by ~1.8x.[...]
pylibfdt/libfdt.i | 64 +++++++++++++++++++++++++++++++++++++++++++++---- tests/pylibfdt_tests.py | 3 +++ 2 files changed, 63 insertions(+), 4 deletions(-)
pylibfdt/libfdt.i static int fdt_property_stub(void *fdt, const char *name, const void *val, · line 28
Quoted 5 lines
pylibfdt/libfdt.i +5
-0@@ -24,6 +24,61 @@ static int fdt_property_stub(void *fdt, const char *name, const void *val, + name_obj = PyUnicode_InternFromString(pname); + if (!name_obj) { + Py_DECREF(list); + return NULL; + }
Just to check, how much of the 1.8x comes from interning? My understanding is that interned strings are immortal in Python 3.12 (I am not sure about later versions), so every distinct property name seen in any blob stays allocated for the life of the process. If the gain is small, PyUnicode_FromString() would be safer.
pylibfdt/libfdt.i class FdtRo(object): · line 534
Quoted 9 lines
pylibfdt/libfdt.i +3
-4@@ -477,10 +532,9 @@ class FdtRo(object): - poff = self.first_property_offset(nodeoffset, quiet=QUIET_NOTFOUND) - while poff >= 0: - yield self.get_property_by_offset(poff) - poff = self.next_property_offset(poff, quiet=QUIET_NOTFOUND) + return iter(check_err( + fdt_node_properties_stub(self._fdt, nodeoffset, Property) + ))
This changes the behaviour a little, since properties() is no longer a generator. The FdtException is now raised by the call itself rather than on the first next(), and an error part-way through a node (e.g. a truncated blob) now produces no properties at all, where before the caller saw the earlier ones first.
I think that is OK, but please can you mention it in the commit message and update the docstring, which still says 'Yields'.
tests/pylibfdt_tests.py class PyLibfdtBasicTests(unittest.TestCase): · line 272
Quoted 5 lines
tests/pylibfdt_tests.py +3
-0@@ -270,6 +270,9 @@ class PyLibfdtBasicTests(unittest.TestCase): + with self.assertRaises(FdtException) as e: + list(self.fdt.properties(-1)) + self.assertEqual(e.exception.err, -libfdt.BADOFFSET)
There is already an identical check a little further up in this file (just before testGetName()) and, since it wraps the call in list(), it passes with both the old and new code.
It would be worth replacing it with a test for the new error path, i.e. a failure after the first property, such as a blob truncated in the middle of a node's properties.
Regards,
Simon
Re: [PATCH v4 06/14] pylibfdt: Speed up FdtRo.properties() with a C helper
Hi Simon,
Quoted 14 lines · Simon Glass
pylibfdt/libfdt.i static int fdt_property_stub(void *fdt, const char *name, const void *val, · line 28
Quoted 8 lines
pylibfdt/libfdt.i +5
-0@@ -24,6 +24,61 @@ static int fdt_property_stub(void *fdt, const char *name, const void *val, + name_obj = PyUnicode_InternFromString(pname); + if (!name_obj) { + Py_DECREF(list); + return NULL; + }Just to check, how much of the 1.8x comes from interning? My understanding is that interned strings are immortal in Python 3.12 (I am not sure about later versions), so every distinct property name seen in any blob stays allocated for the life of the process. If the gain is small,
PyUnicode_FromString()would be safer.
Interning isn't where the 1.8x comes from. Switching to PyUnicode_FromString() keeps the same ~1.8x speedup in FdtRo.properties(). Switched to PyUnicode_FromString() for v5.
Quoted 16 lines
pylibfdt/libfdt.i class FdtRo(object): · line 534
Quoted 9 lines
pylibfdt/libfdt.i +3
-4@@ -477,10 +532,9 @@ class FdtRo(object): - poff = self.first_property_offset(nodeoffset, quiet=QUIET_NOTFOUND) - while poff >= 0: - yield self.get_property_by_offset(poff) - poff = self.next_property_offset(poff, quiet=QUIET_NOTFOUND) + return iter(check_err( + fdt_node_properties_stub(self._fdt, nodeoffset, Property) + ))This changes the behaviour a little, since
properties()is no longer a generator. The FdtException is now raised by the call itself rather than on the firstnext(), and an error part-way through a node (e.g. a truncated blob) now produces no properties at all, where before the caller saw the earlier ones first.
Quoted 2 lines
I think that is OK, but please can you mention it in the commit message and update the docstring, which still says 'Yields'.
Done. Updated the docstring (Yields: -> Returns: plus a note on eager evaluation) and noted the behavior change in the commit message.
Quoted 10 lines
tests/pylibfdt_tests.py class PyLibfdtBasicTests(unittest.TestCase): · line 272
Quoted 5 lines
tests/pylibfdt_tests.py +3
-0@@ -270,6 +270,9 @@ class PyLibfdtBasicTests(unittest.TestCase): + with self.assertRaises(FdtException) as e: + list(self.fdt.properties(-1)) + self.assertEqual(e.exception.err, -libfdt.BADOFFSET)There is already an identical check a little further up in this file (just before
testGetName()) and, since it wraps the call inlist(), it passes with both the old and new code.
Quoted 3 lines
It would be worth replacing it with a test for the new error path, i.e. a failure after the first property, such as a blob truncated in the middle of a node's properties.
Done. Replaced the duplicate check in testPropertiesIterator with a test that truncates size_dt_struct after /subnode@1's first property and verifies fdt_trunc.properties(node) raises -libfdt.TRUNCATED directly on the call.
-Doug
PATCH v4 7/14 libpydt: Add DeviceTree live tree representation
In reply to Douglas Andersonpylibfdt's Fdt and FdtRo classes operate directly on flattened device tree blobs, where inserting or deleting nodes and properties shifts subsequent node offsets. That works well for in-place queries and localized edits, but makes multi-tree comparison, structural diffing, and bottom-up tree construction (as needed by the upcoming fdtfactor tool) awkward and error-prone.
Add pylibfdt/libpydt.py providing DeviceTree, an in-memory live tree representation where each node holds props (a dict mapping property name to libfdt.Property) and children (a dict mapping child node name to child DeviceTree), along with unflatten() and flatten() to convert between FdtRo/Fdt blobs and live trees, and helpers for path lookup, node creation, and pre-order traversal.
Add unit tests in tests/libpydt_tests.py covering DeviceTree round-tripping, subtree unflattening, duplicate-name and corrupt-tree rejection, and navigation helpers.
---
Changes in v4:
- Start the commit message with the motivation for a live tree and condense the summary (Simon Glass)
- Rename devicetree.py to libpydt.py (under pylibfdt/) to avoid colliding with PyPI's python-devicetree package, and move its unit tests into a separate tests/libpydt_tests.py file (Simon Glass, David Gibson)
- Unflatten the tree in a single O(n) pass using fdt.next_node() instead of recursive O(d * n) fdt.subnodes() traversal, raising FdtException on corrupt/truncated trees, and add a unit test (David Gibson, Simon Glass)
- Implement DeviceTree.walk() iteratively with an explicit stack instead of recursive yield from, and populate node.props directly in unflatten()
- Drop redundant fdt.pack() call from DeviceTree.flatten() (David Gibson)
- Drop get_*/set_* typed wrapper methods from DeviceTree in favor of Property.as_*() and Property.from_*() plus DeviceTree.set_prop() (David Gibson)
- Drop unnecessary copy.deepcopy() and compare unordered node/child sets instead of ordered lists in round-trip test (David Gibson)
Changes in v3:
- Move NodeTree out of pylibfdt/libfdt.i into a new devicetree.py module and rename it to DeviceTree (David Gibson)
- Store libfdt.Property objects in self.props instead of raw bytes (David Gibson)
- Return a packed libfdt.Fdt object from flatten() instead of raw bytes and use fdt.set_boot_cpuid_phys() (David Gibson, Simon Glass)
- Raise ValueError in unflatten() on duplicate property or sibling subnode names (Simon Glass)
Changes in v2:
- Split live tree representation out of fdtfactor (David Gibson)
pylibfdt/libpydt.py | 184 +++++++++++++++++++++++++++++++++++++++++ pylibfdt/meson.build | 2 + tests/libpydt_tests.py | 106 ++++++++++++++++++++++++ tests/meson.build | 2 +- tests/run_tests.sh | 13 ++- 5 files changed, 302 insertions(+), 5 deletions(-) create mode 100644 pylibfdt/libpydt.py create mode 100644 tests/libpydt_tests.py
pylibfdt/libpydt.py new file +184 -0
@@ -0,0 +1,184 @@ +# SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) +"""libpydt - Non-flattened in-memory device tree representation in Python.""" + +import libfdt + + +class DeviceTree: + """In-memory live tree representation of a devicetree node and its subtree. + + `props` and `children` are public dictionaries intended to be accessed and + manipulated directly by callers (e.g. `node.props['status'].as_str()`, + `node.props.get('reg')`, `node.children.get('soc')`), with `set_prop()` + provided as a convenience for inserting a `libfdt.Property` under its own + `prop.name`. + + Attributes: + props: Dict mapping property name (str) to `libfdt.Property`. + children: Dict mapping child node name (str) to child `DeviceTree`. + """ + + def __init__(self): + self.props = {} + self.children = {} + + @classmethod + def unflatten(cls, fdt, offset=0): + """Unflatten an FdtRo subtree starting at `offset` into a DeviceTree. + + Args: + fdt: An `FdtRo` (or `Fdt`) instance. + offset: Starting node offset (default 0 for the root node). + + Returns: + A `DeviceTree` representing the node at `offset` and its + descendants. + + Raises: + ValueError: If a node contains duplicate property names or + duplicate sibling subnode names. + """ + stack = [] + depth = 0 + while depth >= 0: + node = cls() + props = node.props + for prop in fdt.properties(offset): + name = prop.name + if name in props: + raise ValueError(f'Duplicate property {name!r}') + props[name] = prop + if depth == 0: + stack = [node] + else: + parent = stack[depth - 1] + subname = fdt.get_name(offset) + if subname in parent.children: + raise ValueError(f'Duplicate subnode {subname!r}') + parent.children[subname] = node + del stack[depth:] + stack.append(node) + offset, depth = fdt.next_node(offset, depth) + if offset < 0: + libfdt.check_err(offset) + return stack[0] + + def _flatten_subtree(self, sw, name): + """Recursively write this DeviceTree and its children into an FdtSw. + + Args: + sw: An `FdtSw` sequential-write instance. + name: Node name for this subtree (empty string `''` for root). + """ + with sw.add_node(name): + for prop_name, val in self.props.items(): + sw.property(prop_name, val) + for child_name, child_node in self.children.items(): + child_node._flatten_subtree(sw, child_name) + + def flatten(self, mem_rsv=(), boot_cpuid_phys=0): + """Serialize this root DeviceTree into a packed `libfdt.Fdt` object. + + Args: + mem_rsv: Iterable of (address, size) tuples for the FDT memory + reservation block. + boot_cpuid_phys: Physical boot CPU ID for the FDT header. + + Returns: + Packed `libfdt.Fdt` instance. + """ + sw = libfdt.FdtSw() + for addr, size in mem_rsv: + sw.add_reservemap_entry(addr, size) + sw.finish_reservemap() + self._flatten_subtree(sw, '') + fdt = sw.as_fdt() + fdt.set_boot_cpuid_phys(boot_cpuid_phys) + return fdt + + def set_prop(self, prop): + """Insert or replace a `libfdt.Property` in `self.props` under `prop.name`. + + Args: + prop: `libfdt.Property` instance to store at `self.props[prop.name]`. + """ + self.props[prop.name] = prop + + def get_node(self, path): + """Look up a descendant DeviceTree by path without modifying the tree. + + Follows the slash-separated node names in `path` starting from `self` + (leading, trailing, and repeated `'/'` characters are ignored, so + `'/soc/i2c@4000'` and `'soc/i2c@4000'` behave identically, and `''` or + `'/'` returns `self`). If any component along `path` is not present in + `children`, returns `None`. + + Args: + path: Slash-separated node path starting from `self` (e.g. + `'/soc/i2c@4000'` or `'soc/i2c@4000'`). + + Returns: + The `DeviceTree` at `path`, or `None` if not found. + """ + node = self + for part in path.split('/'): + if not part: + continue + node = node.children.get(part) + if node is None: + return None + return node + + def create_path(self, path): + """Return the descendant DeviceTree at `path`, creating missing nodes. + + Looks up a child or deeper descendant `DeviceTree` by following the + slash-separated node names in `path` starting from `self` (leading, + trailing, and repeated `'/'` characters are ignored, so + `'/soc/i2c@4000'` and `'soc/i2c@4000'` behave identically). If any + node along `path` does not exist yet in `children`, a new empty + `DeviceTree` is created for it automatically (similar to `mkdir -p`). + Passing `''` or `'/'` returns `self`. + + Example: + root = DeviceTree() + # Automatically creates root.children['soc'] and + # root.children['soc'].children['i2c@4000'], and returns the + # 'i2c@4000' DeviceTree. + i2c = root.create_path('/soc/i2c@4000') + i2c.set_prop(libfdt.Property.from_str('status', 'okay')) + + Args: + path: Slash-separated node path starting from `self` (e.g. + `'/soc/i2c@4000'` or `'soc/i2c@4000'`). + + Returns: + The `DeviceTree` instance at `path`. + """ + node = self + for part in path.split('/'): + if not part: + continue + if part not in node.children: + node.children[part] = type(self)() + node = node.children[part] + return node + + def walk(self, path=''): + """Yield `(path, node)` pairs for this subtree in pre-order. + + Args: + path: Path prefix for `self` (defaults to `''` for the root node, + producing paths like `''`, `'/soc'`, `'/soc/i2c@4000'`). + + Yields: + Tuple of `(path, node)` for `self` followed in pre-order by each + descendant `DeviceTree`. + """ + stack = [(path, self)] + while stack: + cur_path, node = stack.pop() + yield cur_path, node + prefix = cur_path.rstrip('/') + for name, child in reversed(node.children.items()): + stack.append((f'{prefix}/{name}', child))
pylibfdt/meson.build +2 -0
@@ -19,3 +19,5 @@ pylibfdt = py.extension_module( dependencies: [libfdt_dep, py.dependency()], install: true, ) + +py.install_sources('libpydt.py', pure: false)
tests/libpydt_tests.py new file +106 -0
106 lines not on this page · raw message
tests/meson.build +1 -1
@@ -119,7 +119,7 @@ if not pylibfdt_enabled else env += [ 'PYTHON=' + py.full_path(), - 'PYTHONPATH=' + meson.project_build_root() / 'pylibfdt', + 'PYTHONPATH=' + meson.project_build_root() / 'pylibfdt' + ':' + meson.project_source_root() / 'pylibfdt', 'NO_PYTHON=0', ] endif
tests/run_tests.sh +9 -4
@@ -1149,17 +1149,16 @@ fdtoverlay_tests() { run_wrap_test test "$bd" = "$pd" } -pylibfdt_tests () { - run_dtc_test -I dts -O dtb -o test_props.dtb "$SRCDIR/test_props.dts" +run_python_tests () { TMP=/tmp/tests.stderr.$$ - $PYTHON "$SRCDIR/pylibfdt_tests.py" -v 2> $TMP + $PYTHON "$1" -v 2> $TMP # Use the 'ok' message meaning the test passed, 'ERROR' meaning it failed # and the summary line for total tests (e.g. 'Ran 17 tests in 0.002s'). # We could add pass + fail to get total tests, but this provides a useful # sanity check. pass_count=$(grep "ok$" $TMP | wc -l) - fail_count=$(grep "^ERROR: " $TMP | wc -l) + fail_count=$(grep "^ERROR: \|^FAIL: " $TMP | wc -l) total_tests=$(sed -n 's/^Ran \([0-9]*\) tests.*$/\1/p' $TMP) cat $TMP rm $TMP
@@ -1170,6 +1169,12 @@ pylibfdt_tests () { tot_tests=$((tot_tests + $total_tests)) } +pylibfdt_tests () { + run_dtc_test -I dts -O dtb -o test_props.dtb "$SRCDIR/test_props.dts" + run_python_tests "$SRCDIR/pylibfdt_tests.py" + run_python_tests "$SRCDIR/libpydt_tests.py" +} + while getopts "vt:me" ARG ; do case $ARG in "v")
Signature · 1 line
2.56.0.679.gc527c65306-goog
Re: [PATCH v4 07/14] libpydt: Add DeviceTree live tree representation
Quoted 23 lines · Douglas Anderson
libpydt: Add DeviceTree live tree representation
pylibfdt'sFdtandFdtRoclasses operate directly on flattened device tree blobs, where inserting or deleting nodes and properties shifts subsequent node offsets. That works well for in-place queries and localized edits, but makes multi-tree comparison, structural diffing, and bottom-up tree construction (as needed by the upcomingfdtfactortool) awkward and error-prone.Add
pylibfdt/libpydt.pyprovidingDeviceTree, an in-memory live tree representation where each node holdsprops(a dict mapping property name tolibfdt.Property) andchildren(a dict mapping child node name to childDeviceTree), along withunflatten()andflatten()to convert betweenFdtRo/Fdtblobs and live trees, and helpers for path lookup, node creation, and pre-order traversal.Add unit tests in
tests/libpydt_tests.pycoveringDeviceTreeround-tripping, subtree unflattening, duplicate-name and corrupt-tree rejection, and navigation helpers.Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>
Quoted 6 lines
pylibfdt/libpydt.py | 184 +++++++++++++++++++++++++++++++++++++++++++++++++ pylibfdt/meson.build | 2 + tests/libpydt_tests.py | 106 ++++++++++++++++++++++++++++ tests/meson.build | 2 +- tests/run_tests.sh | 13 ++-- 5 files changed, 302 insertions(+), 5 deletions(-)
PATCH v4 8/14 libfdt: Speed up fdt_find_string_len_() with memchr()
In reply to Douglas Andersonfdt_find_string_len_() currently calls memcmp() at every byte offset across the string table (for (p = strtab; p <= last; p++)). When building or modifying trees with large string tables (such as DTBs and overlays with hundreds of /__symbols__ or /__fixups__ labels via fdt_sw or fdt_rw), scanning multi-kilobyte string tables byte by byte dominates serialization time.
Advance p between candidate first-byte matches using memchr() (with an explicit slen == 0 check for empty property names and a tabsize < slen + 1 bounds check before computing last), preserving identical suffix-sharing behavior.
On one stress test (running the fdtfactor tool across 438 arm64 Qualcomm DTBs) this reduced fdt_property() time by ~5.6x.
---
Found this speedup while benchmarking fdtfactor. It's not critical to functionality, but seems like a nice win.
Changes in v4:
- New patch speeding up fdt_find_string_len_() with memchr()
libfdt/fdt.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-)
libfdt/fdt.c +11 -3
@@ -348,12 +348,20 @@ int fdt_next_subnode(const void *fdt, int offset)const char *fdt_find_string_len_ (const char *strtab,int tabsize,const char *s,int slen) { -const char *last = strtab + tabsize - (slen +1 ); -const char *p; +const char *last; +const char *p = strtab; -for (p = strtab; p <= last; p++) +if (tabsize < slen +1 ) +return NULL ; +if (slen ==0 ) +return memchr (strtab,'\0' , tabsize); + + last = strtab + tabsize - (slen +1 ); +while (p <= last && (p =memchr (p, s[0 ], last - p +1 )) !=NULL ) {if (memcmp (p, s, slen) ==0 && p[slen] =='\0' )return p; + p++; + }return NULL ; }
Signature · 1 line
2.56.0.679.gc527c65306-goog
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Quoted 7 lines · Douglas Anderson
fdt_find_string_len_()currently callsmemcmp()at every byte offset across the string table (for (p = strtab; p <= last; p++)). When building or modifying trees with large string tables (such as DTBs and overlays with hundreds of/__symbols__or/__fixups__labels viafdt_sworfdt_rw), scanning multi-kilobyte string tables byte by byte dominates serialization time.
Quoted 7 lines
Advance
pbetween candidate first-byte matches usingmemchr()(with an explicitslen == 0check for empty property names and atabsize < slen + 1bounds check before computinglast), preserving identical suffix-sharing behavior.On one stress test (running the fdtfactor tool across 438 arm64 Qualcomm DTBs) this reduced
fdt_property()time by ~5.6x.
What we really want is memmem(), which would presumably have a similar optimization (and likely more) built in. However, we avoid that to make this easier to environments which lack it.
Complexity isn't too great, so this looks reasonable to me
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
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Quoted 13 lines · David Gibson
Quoted 12 lines · Douglas Anderson
fdt_find_string_len_()currently callsmemcmp()at every byte offset across the string table (for (p = strtab; p <= last; p++)). When building or modifying trees with large string tables (such as DTBs and overlays with hundreds of/__symbols__or/__fixups__labels viafdt_sworfdt_rw), scanning multi-kilobyte string tables byte by byte dominates serialization time.Advance
pbetween candidate first-byte matches usingmemchr()(with an explicitslen == 0check for empty property names and atabsize < slen + 1bounds check before computinglast), preserving identical suffix-sharing behavior.
Quoted 8 lines
Quoted 2 lines
On one stress test (running the fdtfactor tool across 438 arm64 Qualcomm DTBs) this reduced
fdt_property()time by ~5.6x.What we really want is
memmem(), which would presumably have a similar optimization (and likely more) built in. However, we avoid that to make this easier to environments which lack it.Complexity isn't too great, so this looks reasonable to me
Hmm... actually, thinking about this again, I'm kind of baffled that the speedup is so large. In the old version, if p is at a character that doesn't match the start of the string we're looking for, memcmp() should return almost immediately (after a single byte comparison), so I'd expect both versions to be - roughly speaking - a single scan through each byte of the strings block. At least with gcc builtin and inlined mem*() implementations, I'd expect the performance difference to be pretty modest between that and the new version.
What was the environment (host CPU, libc, compiler options) you used for the benchmark?
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
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Hi David,
Quoted 19 lines · David Gibson
Quoted 9 lines
Quoted 3 lines
On one stress test (running the fdtfactor tool across 438 arm64 Qualcomm DTBs) this reduced
fdt_property()time by ~5.6x.What we really want is
memmem(), which would presumably have a similar optimization (and likely more) built in. However, we avoid that to make this easier to environments which lack it.Complexity isn't too great, so this looks reasonable to me
Hmm... actually, thinking about this again, I'm kind of baffled that the speedup is so large. In the old version, if p is at a character that doesn't match the start of the string we're looking for,
memcmp()should return almost immediately (after a single byte comparison), so I'd expect both versions to be - roughly speaking - a single scan through each byte of the strings block. At least with gcc builtin and inlined mem*() implementations, I'd expect the performance difference to be pretty modest between that and the new version.
Quoted 2 lines
What was the environment (host CPU, libc, compiler options) you used for the benchmark?
Environment details:
* CPU: AMD Ryzen Threadripper PRO 5995WX (x86_64, AVX2)
* libc: Debian glibc 2.43
* Compiler: gcc (Debian 15.2.0-14) 15.2.0
* Flags: default meson setup build (buildtype=debug, so -O0 -g -fPIC), though testing at -Os, -O2, and -O3 gives the same ~16-17x speedup on the string-table scan itself.
There are two things going on even at -O2 / -O3:
1. **GCC can't inline memcmp(p, s, slen) when slen isn't a compile-time constant**: Because slen is a runtime variable (and GCC also can't synthesize a *p == *s pre-check on its own since slen could be 0), GCC at -O2 / -O3 emits a full PLT call to memcmp() on every single byte p of strtab:
.L10:
movq %rbx, %rdx
movq %rbp, %rsi
movq %r15, %rdi
call memcmp@PLT
...
addq $1, %r15
cmpq %r15, %r12
jnb .L10 Even though glibc's __memcmp_avx2_movbe returns quickly on a first-byte mismatch, paying a PLT call/return and function prologue on every byte of a ~14 KB /__symbols__ string table (~5.8M memcmp() calls per 800-symbol DTB) dominates runtime. Just adding a scalar *p == *s guard ahead of memcmp() already speeds up the test below by ~8x at -O2.
2. **SIMD scanning inside memchr() (~2x faster than a scalar byte loop at -O2)**: Instead of stepping one byte per scalar loop iteration, glibc's memchr() (__memchr_avx2 on x86_64) broadcasts s[0] across a 32-byte YMM register (vpbroadcastb + vpcmpeqb) and scans 32 bytes per iteration inside a single call, only returning on the ~4-6% of offsets where p[0] == s[0].
(In the commit message, overall fdt_property() time dropped by ~5.6x rather than ~16x because ordinary repeated property names like compatible, reg, and phandle hit near the beginning of strtab right away, and fdt_property() also includes copying the property value and header bookkeeping.)
Here is a small standalone C program (bench_find_string.c) that models building an 800-symbol string table 200 times (~4.2s -> ~0.25s at -O2 on my machine):
---8<---
// SPDX-License-Identifier: GPL-2.0-or-later OR BSD-2-Clause /*
* Build & run:
* cc -O2 bench_find_string.c -o bench_find_string
* ./bench_find_string
*/
#include <stdio.h>
#include <string.h>
#include <time.h>
typedef const char *(*find_fn)(const char *, int, const char *, int);
__attribute__((noinline))
static const char *old_find_string_len(const char *strtab, int tabsize,
const char *s, int slen)
{
const char *last = strtab + tabsize - (slen + 1);
const char *p;
for (p = strtab; p <= last; p++)
if (memcmp(p, s, slen) == 0 && p[slen] == '\0')
return p;
return NULL;
}__attribute__((noinline))
static const char *new_find_string_len(const char *strtab, int tabsize,
const char *s, int slen)
{
const char *last;
const char *p = strtab;
if (tabsize < slen + 1)
return NULL;
if (slen == 0)
return memchr(strtab, '\0', tabsize);
last = strtab + tabsize - (slen + 1);
while (p <= last && (p = memchr(p, s[0], last - p + 1)) != NULL) {
if (memcmp(p, s, slen) == 0 && p[slen] == '\0')
return p;
p++;
}
return NULL;
}static double bench(find_fn fn, char names[][32], int nsyms, int iters,
int *out_tabsize)
{
struct timespec t0, t1;
char strtab[32768];
clock_gettime(CLOCK_MONOTONIC, &t0);
for (int it = 0; it < iters; it++) {
int tabsize = 0;
for (int i = 0; i < nsyms; i++) {
int slen = strlen(names[i]);
if (fn(strtab, tabsize, names[i], slen))
continue;
memcpy(strtab + tabsize, names[i], slen + 1);
tabsize += slen + 1;
}
*out_tabsize = tabsize;
}
clock_gettime(CLOCK_MONOTONIC, &t1);
return (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec) * 1e-9;
}int main(void)
{
static const char * const prefixes[] = {
"clk_gcc", "reg_vdd", "pinctrl", "i2c_bus",
"usb_phy", "pcie_ep", "mmc_sdhc", "gpu_opp",
};
enum { NUM_SYMS = 800, ITERS = 200 };
char names[NUM_SYMS][32];
int tabsize = 0;
double dt_old, dt_new;
for (int i = 0; i < NUM_SYMS; i++)
snprintf(names[i], sizeof(names[i]), "%s_node_%04d",
prefixes[i % 8], i);
dt_old = bench(old_find_string_len, names, NUM_SYMS, ITERS,
&tabsize);
dt_new = bench(new_find_string_len, names, NUM_SYMS, ITERS,
&tabsize);
printf("%d trees x %d symbols (final strtab = %d B):\n",
ITERS, NUM_SYMS, tabsize);
printf(" old (per-byte memcmp): %.4f s\n", dt_old);
printf(" new (memchr + memcmp): %.4f s (%.1fx faster)\n",
dt_new, dt_old / dt_new);
return 0;
}--->8---
-Doug
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Quoted 59 lines · Doug Anderson
Hi David,
Quoted 19 lines · David Gibson
Quoted 9 lines
Quoted 3 lines
On one stress test (running the fdtfactor tool across 438 arm64 Qualcomm DTBs) this reduced
fdt_property()time by ~5.6x.What we really want is
memmem(), which would presumably have a similar optimization (and likely more) built in. However, we avoid that to make this easier to environments which lack it.Complexity isn't too great, so this looks reasonable to me
Hmm... actually, thinking about this again, I'm kind of baffled that the speedup is so large. In the old version, if p is at a character that doesn't match the start of the string we're looking for,
memcmp()should return almost immediately (after a single byte comparison), so I'd expect both versions to be - roughly speaking - a single scan through each byte of the strings block. At least with gcc builtin and inlined mem*() implementations, I'd expect the performance difference to be pretty modest between that and the new version.Quoted 2 lines
What was the environment (host CPU, libc, compiler options) you used for the benchmark?
Environment details:
* CPU: AMD Ryzen Threadripper PRO 5995WX (x86_64, AVX2)
* libc: Debian glibc 2.43
* Compiler: gcc (Debian 15.2.0-14) 15.2.0
* Flags: defaultmeson setup build(buildtype=debug, so-O0 -g -fPIC), though testing at-Os,-O2, and-O3gives the same ~16-17x speedup on the string-table scan itself.There are two things going on even at
-O2/-O3:1. **GCC can't inline
memcmp(p, s, slen)whenslenisn't a compile-time constant**: Becauseslenis a runtime variable (and GCC also can't synthesize a*p == *spre-check on its own sinceslencould be0), GCC at-O2/-O3emits a full PLT call tomemcmp()on every single bytepofstrtab:.L10: movq %rbx, %rdx movq %rbp, %rsi movq %r15, %rdi call memcmp@PLT ... addq $1, %r15 cmpq %r15, %r12 jnb .L10Even though glibc's
__memcmp_avx2_movbereturns quickly on a first-byte mismatch, paying a PLT call/return and function prologue on every byte of a ~14 KB/__symbols__string table (~5.8Mmemcmp()calls per 800-symbol DTB) dominates runtime. Just adding a scalar*p == *sguard ahead ofmemcmp()already speeds up the test below by ~8x at-O2.
Quoted 6 lines
2. **SIMD scanning inside
memchr()(~2x faster than a scalar byte loop at-O2)**: Instead of stepping one byte per scalar loop iteration, glibc'smemchr()(__memchr_avx2onx86_64) broadcastss[0]across a 32-byte YMM register (vpbroadcastb+vpcmpeqb) and scans 32 bytes per iteration inside a single call, only returning on the ~4-6% of offsets wherep[0] == s[0].
Ah, right, thanks for the analysis.
Quoted 9 lines
(In the commit message, overall
fdt_property()time dropped by ~5.6x rather than ~16x because ordinary repeated property names likecompatible,reg, andphandlehit near the beginning ofstrtabright away, andfdt_property()also includes copying the property value and header bookkeeping.)Here is a small standalone C program (
bench_find_string.c) that models building an 800-symbol string table 200 times (~4.2s -> ~0.25s at-O2on my machine):
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
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
In reply to Douglas AndersonQuoted 6 lines · On Mon, 16 Nov 2026 12:53:05 -0800 Douglas Anderson <[email protected]>…
fdt_find_string_len_()currently callsmemcmp()at every byte offset across the string table (for (p = strtab; p <= last; p++)). When building or modifying trees with large string tables (such as DTBs and overlays with hundreds of/__symbols__or/__fixups__labels viafdt_sworfdt_rw), scanning multi-kilobyte string tables byte by byte dominates serialization time.
Are those symbols just in a linear list with embedded '\0' ? That doesn't scale well at all :-)
Quoted 5 lines
Advance
pbetween candidate first-byte matches usingmemchr()(with an explicitslen == 0check for empty property names and atabsize < slen + 1bounds check before computinglast), preserving identical suffix-sharing behavior.
Might it be better to scan for the '\0' that terminated/separates the strings? Then you do one memcmp() for each string/symbol rather than for each time the first character appears in any string.
Even with the code below you want to do the !p[slen] check before the memcmp().
David
Quoted 44 lines
On one stress test (running the fdtfactor tool across 438 arm64 Qualcomm DTBs) this reduced
fdt_property()time by ~5.6x.Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>---
Found this speedup while benchmarking fdtfactor. It's not critical to functionality, but seems like a nice win.Changes in v4:
- New patch speeding upfdt_find_string_len_()withmemchr()libfdt/fdt.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-)libfdt/fdt.c +11
-3@@ -348,12 +348,20 @@ int fdt_next_subnode(const void *fdt, int offset)const char *fdt_find_string_len_ (const char *strtab,int tabsize,const char *s,int slen) { -const char *last = strtab + tabsize - (slen +1 ); -const char *p; +const char *last; +const char *p = strtab; -for (p = strtab; p <= last; p++) +if (tabsize < slen +1 ) +return NULL ; +if (slen ==0 ) +return memchr (strtab,'\0' , tabsize); + + last = strtab + tabsize - (slen +1 ); +while (p <= last && (p =memchr (p, s[0 ], last - p +1 )) !=NULL ) {if (memcmp (p, s, slen) ==0 && p[slen] =='\0' )return p; + p++; + }return NULL ; }
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Hi David,
Quoted 11 lines · David Laight
Quoted 6 lines · On Mon, 16 Nov 2026 12:53:05 -0800 Douglas Anderson <[email protected]>…
fdt_find_string_len_()currently callsmemcmp()at every byte offset across the string table (for (p = strtab; p <= last; p++)). When building or modifying trees with large string tables (such as DTBs and overlays with hundreds of/__symbols__or/__fixups__labels viafdt_sworfdt_rw), scanning multi-kilobyte string tables byte by byte dominates serialization time.
Quoted 2 lines
Are those symbols just in a linear list with embedded '\0' ? That doesn't scale well at all :-)
I'm assuming from your :-) that your "That doesn't scale well at all" was intended to be wrapped in <sarcasm> tags? :-P
Quoted 8 lines
Quoted 4 lines
Advance
pbetween candidate first-byte matches usingmemchr()(with an explicitslen == 0check for empty property names and atabsize < slen + 1bounds check before computinglast), preserving identical suffix-sharing behavior.Might it be better to scan for the '\0' that terminated/separates the strings? Then you do one
memcmp()for each string/symbol rather than for each time the first character appears in any string.
Two things work against scanning for '\0' here:
1. fdt_find_string_len_() intentionally supports suffix sharing (e.g. "controller" matching the tail of "interrupt-controller\0"), so scanning for '\0' can't check nul + 1 (the start of the next string) -- it has to start at strtab + slen and test p = nul - slen before each '\0'.
2. Every stored string ends with '\0', whereas s[0] only appears in a smaller fraction of bytes. On a real upstream Qualcomm base DTB's dt_strings block (855 strings in 11,259 bytes, average 13.2 bytes per string), '\0' occurs on 7.6% of bytes while s[0] averages 3.9%. Replaying those 855 insertions makes 362k memchr() calls when scanning for '\0' vs. 187k memchr() calls when scanning for s[0].
Quoted 1 line
Even with the code below you want to do the !p[slen] check before the
memcmp().
Agreed. Since p <= last (strtab + tabsize - (slen + 1)), p[slen] is always in bounds, and checking !p[slen] (i.e. p[slen] == '\0') before memcmp(p, s, slen) == 0 cuts the memcmp() call count across that 855-string replay from 187k down to 14.3k (the exact same 14.3k memcmp() calls you'd get from scanning for '\0' with a *p == *s pre-check, just with half as many memchr() stops).
Timing 200 replays of that 855-string (11,259-byte) Qualcomm dt_strings block with gcc 15.2 -O2 on x86_64:
* Original (per-byte memcmp): 3.45 s
* Scan for '\0', memcmp(nul - slen, s, slen): 0.45 s
* Scan for '\0', *p == *s then memcmp: 0.36 s
* Scan for s[0], memcmp then !p[slen] (merged c954f9dd8357):
0.27 s
* Scan for s[0], !p[slen] then memcmp: 0.21 s (~20% faster)
Since you already applied this patch to main (c954f9dd8357), so I'll include a 1-line follow-up patch swapping the check order (with Suggested-by: you) in v5.
-Doug
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Quoted 15 lines · On Wed, 18 Nov 2026 09:24:38 -0800 Doug Anderson <[email protected]> wrote:
Hi David,
Quoted 11 lines · David Laight
Quoted 6 lines · On Mon, 16 Nov 2026 12:53:05 -0800 Douglas Anderson <[email protected]>…
fdt_find_string_len_()currently callsmemcmp()at every byte offset across the string table (for (p = strtab; p <= last; p++)). When building or modifying trees with large string tables (such as DTBs and overlays with hundreds of/__symbols__or/__fixups__labels viafdt_sworfdt_rw), scanning multi-kilobyte string tables byte by byte dominates serialization time.
Quoted 5 lines
Quoted 2 lines
Are those symbols just in a linear list with embedded '\0' ? That doesn't scale well at all :-)
I'm assuming from your :-) that your "That doesn't scale well at all" was intended to be wrapped in <sarcasm> tags? :-P
Something like that...
Quoted 9 lines
Quoted 8 lines
Quoted 4 lines
Advance
pbetween candidate first-byte matches usingmemchr()(with an explicitslen == 0check for empty property names and atabsize < slen + 1bounds check before computinglast), preserving identical suffix-sharing behavior.Might it be better to scan for the '\0' that terminated/separates the strings? Then you do one
memcmp()for each string/symbol rather than for each time the first character appears in any string.
Quoted 7 lines
Two things work against scanning for
'\0'here:1.
fdt_find_string_len_()intentionally supports suffix sharing (e.g."controller"matching the tail of"interrupt-controller\0"), so scanning for'\0'can't checknul + 1(the start of the next string) -- it has to start atstrtab + slenand testp = nul - slenbefore each'\0'.
That isn't a real problem and doesn't make much difference.
Quoted 7 lines
2. Every stored string ends with
'\0', whereass[0]only appears in a smaller fraction of bytes. On a real upstream Qualcomm base DTB'sdt_stringsblock (855 strings in 11,259 bytes, average 13.2 bytes per string),'\0'occurs on 7.6% of bytes whiles[0]averages 3.9%. Replaying those 855 insertions makes 362kmemchr()calls when scanning for'\0'vs. 187kmemchr()calls when scanning fors[0].
You need to count the number of times that a letter that is the first character of a string you are going to lookup appears in the entire buffer. There might only be one 'j' in the entire buffer - but you never look for it. (But I might still be wrong)
Quoted 19 lines
Quoted 2 lines
Even with the code below you want to do the !p[slen] check before the
memcmp().Agreed. Since
p <= last(strtab + tabsize - (slen + 1)),p[slen]is always in bounds, and checking!p[slen](i.e.p[slen] == '\0') beforememcmp(p, s, slen) == 0cuts thememcmp()call count across that 855-string replay from 187k down to 14.3k (the exact same 14.3kmemcmp()calls you'd get from scanning for'\0'with a*p == *spre-check, just with half as manymemchr()stops).Timing 200 replays of that 855-string (11,259-byte) Qualcomm
dt_stringsblock withgcc 15.2 -O2onx86_64:
* Original (per-bytememcmp): 3.45 s
* Scan for'\0',memcmp(nul - slen, s, slen): 0.45 s
* Scan for'\0',*p == *sthenmemcmp: 0.36 s
* Scan fors[0],memcmpthen!p[slen](mergedc954f9dd8357):
0.27 s
* Scan fors[0],!p[slen]thenmemcmp: 0.21 s (~20% faster)
Quoted 3 lines
Since you already applied this patch to
main(c954f9dd8357), so I'll include a 1-line follow-up patch swapping the check order (withSuggested-by:you) in v5.
Have you tried an open coded scans instead of calling memchr() and memcmp()? With an average of 13 bytes per string (26 for your memchr()) the code loop might be faster.
But beware, gcc is likely to convert the code back to a call to memcmp()
- it certainly does for strlen and memcpy.
Oh - and if this code runs in kernel the timings will be significantly different to glibc - it uses some magic avx instructions for strlen() and memchr() is effectively the same.
The kernel functions are likely to be out of line byte loops.
David
Quoted 2 lines
-Doug
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Hi David,
Quoted 9 lines · David Laight
Quoted 8 lines
2. Every stored string ends with
'\0', whereass[0]only appears in a smaller fraction of bytes. On a real upstream Qualcomm base DTB'sdt_stringsblock (855 strings in 11,259 bytes, average 13.2 bytes per string),'\0'occurs on 7.6% of bytes whiles[0]averages 3.9%. Replaying those 855 insertions makes 362kmemchr()calls when scanning for'\0'vs. 187kmemchr()calls when scanning fors[0].
Quoted 4 lines
You need to count the number of times that a letter that is the first character of a string you are going to lookup appears in the entire buffer. There might only be one 'j' in the entire buffer - but you never look for it. (But I might still be wrong)
That 3.9% (187,315 memchr() calls across ~4.77M scanned bytes) was actually measured directly by replaying those 855 real lookups (s[0] of each string being inserted), not an unweighted 1/26 average across the alphabet. Even though common prefixes like 'p', 'u', 'q', and 's' get looked up a lot, 26.6% of the dt_strings block (2,139 bytes of '_', '-', '0'-'9', and '#', plus 855 NUL bytes) are characters that almost never appear as s[0], which pulls the lookup-weighted hit rate back down to 3.9%.
Intuitively, '\0' hits once per string (1 / L), so s[0] wins as long as average string length L stays below the ~22-26 byte crossover -- and even on plain non--@ DTBs without /__symbols__, property names average ~12-14 bytes ('\0' still made 1.6x-2.2x more memchr() calls than s[0] across plain DTB fdt_sw builds, /chosen fixups, and .dtbo overlay application).
Quoted 10 lines
Have you tried an open coded scans instead of calling
memchr()andmemcmp()? With an average of 13 bytes per string (26 for yourmemchr()) the code loop might be faster.
But beware, gcc is likely to convert the code back to a call tomemcmp()
- it certainly does for strlen and memcpy.Oh - and if this code runs in kernel the timings will be significantly different to glibc - it uses some magic avx instructions for
strlen()andmemchr()is effectively the same.
The kernel functions are likely to be out of line byte loops.
Out of curiosity I timed all of those across 200 replays of the same 855-string (11,259-byte) Qualcomm dt_strings block with gcc 15.2 on x86_64 (gcc -O2 kept the open-coded loops inline and didn't turn them back into memcmp()):
* glibc memchr + !p[slen] + glibc memcmp:
0.25 s (-O0), 0.23 s (-Os), 0.22 s (-O2)
* glibc memchr + !p[slen] + open-coded inner compare:
0.23 s (-O0), 0.21 s (-Os), 0.21 s (-O2)
* Fully open-coded (p[0] == s[0] && !p[slen] + inner byte loop):
0.91 s (-O0), 0.62 s (-Os), 0.40 s (-O2)
* Out-of-line byte-loop memchr + !p[slen] + byte-loop memcmp:
0.86 s (-O0), 0.90 s (-Os), 0.50 s (-O2)
* Original per-byte out-of-line byte-loop memcmp:
3.31 s (-O0), 1.87 s (-Os), 1.86 s (-O2)
Even with a ~25-byte average stride, glibc's AVX2 memchr() handles almost an entire stride in a single 32-byte vector load + compare, so it beats the open-coded scalar loop by ~1.9x at -O2 (and ~2.7x at -Os). Open-coding just the inner compare barely moves the needle since !p[slen] already cut memcmp() down to 14.3k calls across the 855 insertions.
On the kernel / bootloader side, fdt_find_string_len_() is only called by fdt_sw and fdt_rw when adding new property names to dt_strings -- normal read-only DTB parsing (fdt_ro.c) never calls it. And even with a naive out-of-line byte-loop memchr(), memchr() + !p[slen] + memcmp() is still 3.7x faster at -O2 (1.86 s -> 0.50 s) and 2.1x faster at -Os (1.87 s -> 0.90 s) than the old code, so keeping the simpler memchr() + !p[slen] + memcmp() seems like the right tradeoff.
-Doug
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Quoted 45 lines · On Wed, 18 Nov 2026 12:39:59 -0800 Doug Anderson <[email protected]> wrote:
Hi David,
Quoted 9 lines · David Laight
Quoted 8 lines
2. Every stored string ends with
'\0', whereass[0]only appears in a smaller fraction of bytes. On a real upstream Qualcomm base DTB'sdt_stringsblock (855 strings in 11,259 bytes, average 13.2 bytes per string),'\0'occurs on 7.6% of bytes whiles[0]averages 3.9%. Replaying those 855 insertions makes 362kmemchr()calls when scanning for'\0'vs. 187kmemchr()calls when scanning fors[0].Quoted 4 lines
You need to count the number of times that a letter that is the first character of a string you are going to lookup appears in the entire buffer. There might only be one 'j' in the entire buffer - but you never look for it. (But I might still be wrong)
That 3.9% (
187,315memchr()calls across ~4.77M scanned bytes) was actually measured directly by replaying those 855 real lookups (s[0]of each string being inserted), not an unweighted 1/26 average across the alphabet. Even though common prefixes like'p','u','q', and's'get looked up a lot, 26.6% of thedt_stringsblock (2,139bytes of'_','-','0'-'9', and'#', plus855NUL bytes) are characters that almost never appear ass[0], which pulls the lookup-weighted hit rate back down to 3.9%.Intuitively,
'\0'hits once per string (1 / L), sos[0]wins as long as average string lengthLstays below the ~22-26 byte crossover -- and even on plain non--@DTBs without/__symbols__, property names average ~12-14 bytes ('\0'still made 1.6x-2.2x morememchr()calls thans[0]across plain DTBfdt_swbuilds,/chosenfixups, and.dtbooverlay application).Quoted 10 lines
Have you tried an open coded scans instead of calling
memchr()andmemcmp()? With an average of 13 bytes per string (26 for yourmemchr()) the code loop might be faster.
But beware, gcc is likely to convert the code back to a call tomemcmp()
- it certainly does for strlen and memcpy.Oh - and if this code runs in kernel the timings will be significantly different to glibc - it uses some magic avx instructions for
strlen()andmemchr()is effectively the same.
The kernel functions are likely to be out of line byte loops.
Quoted 4 lines
Out of curiosity I timed all of those across 200 replays of the same 855-string (11,259-byte) Qualcomm
dt_stringsblock withgcc 15.2onx86_64(gcc -O2kept the open-coded loops inline and didn't turn them back intomemcmp()):
Once you are doing timings, adding a few more doesn't take long.
Quoted 4 lines
* glibc
memchr+!p[slen]+ glibcmemcmp:
0.25 s (-O0), 0.23 s (-Os), 0.22 s (-O2)
* glibcmemchr+!p[slen]+ open-coded inner compare:
0.23 s (-O0), 0.21 s (-Os), 0.21 s (-O2)
So that one is a marginal win.
Quoted 10 lines
* Fully open-coded (
p[0] == s[0] && !p[slen]+ inner byte loop):
0.91 s (-O0), 0.62 s (-Os), 0.40 s (-O2)
* Out-of-line byte-loopmemchr+!p[slen]+ byte-loopmemcmp:
0.86 s (-O0), 0.90 s (-Os), 0.50 s (-O2)
* Original per-byte out-of-line byte-loopmemcmp:
3.31 s (-O0), 1.87 s (-Os), 1.86 s (-O2)Even with a ~25-byte average stride, glibc's AVX2
memchr()handles almost an entire stride in a single 32-byte vector load + compare, so it beats the open-coded scalar loop by ~1.9x at-O2(and ~2.7x at-Os).
Using avx2 is 'cheating' ...
Someone at Intel realised that strlen() does matter and threw some silicon at it. They finally did the same for integer divide (but I think AMD did it first) and did a divide that generates move than one bit per clock.
Quoted 4 lines
Open-coding just the inner compare barely moves the needle since
!p[slen]already cutmemcmp()down to 14.3k calls across the 855 insertions.
Quoted 8 lines
On the kernel / bootloader side,
fdt_find_string_len_()is only called byfdt_swandfdt_rwwhen adding new property names todt_strings-- normal read-only DTB parsing (fdt_ro.c) never calls it. And even with a naive out-of-line byte-loopmemchr(),memchr()+!p[slen]+memcmp()is still 3.7x faster at-O2(1.86 s -> 0.50 s) and 2.1x faster at-Os(1.87 s -> 0.90 s) than the old code, so keeping the simplermemchr()+!p[slen]+memcmp()seems like the right tradeoff.
Seems reasonable.
David
Quoted 2 lines
-Doug
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Quoted 91 lines · David Laight
Quoted 45 lines · On Wed, 18 Nov 2026 12:39:59 -0800 Doug Anderson <[email protected]> wrote:
Hi David,
Quoted 9 lines · David Laight
Quoted 8 lines
2. Every stored string ends with
'\0', whereass[0]only appears in a smaller fraction of bytes. On a real upstream Qualcomm base DTB'sdt_stringsblock (855 strings in 11,259 bytes, average 13.2 bytes per string),'\0'occurs on 7.6% of bytes whiles[0]averages 3.9%. Replaying those 855 insertions makes 362kmemchr()calls when scanning for'\0'vs. 187kmemchr()calls when scanning fors[0].Quoted 4 lines
You need to count the number of times that a letter that is the first character of a string you are going to lookup appears in the entire buffer. There might only be one 'j' in the entire buffer - but you never look for it. (But I might still be wrong)
That 3.9% (
187,315memchr()calls across ~4.77M scanned bytes) was actually measured directly by replaying those 855 real lookups (s[0]of each string being inserted), not an unweighted 1/26 average across the alphabet. Even though common prefixes like'p','u','q', and's'get looked up a lot, 26.6% of thedt_stringsblock (2,139bytes of'_','-','0'-'9', and'#', plus855NUL bytes) are characters that almost never appear ass[0], which pulls the lookup-weighted hit rate back down to 3.9%.Intuitively,
'\0'hits once per string (1 / L), sos[0]wins as long as average string lengthLstays below the ~22-26 byte crossover -- and even on plain non--@DTBs without/__symbols__, property names average ~12-14 bytes ('\0'still made 1.6x-2.2x morememchr()calls thans[0]across plain DTBfdt_swbuilds,/chosenfixups, and.dtbooverlay application).Quoted 10 lines
Have you tried an open coded scans instead of calling
memchr()andmemcmp()? With an average of 13 bytes per string (26 for yourmemchr()) the code loop might be faster.
But beware, gcc is likely to convert the code back to a call tomemcmp()
- it certainly does for strlen and memcpy.Oh - and if this code runs in kernel the timings will be significantly different to glibc - it uses some magic avx instructions for
strlen()andmemchr()is effectively the same.
The kernel functions are likely to be out of line byte loops.Quoted 4 lines
Out of curiosity I timed all of those across 200 replays of the same 855-string (11,259-byte) Qualcomm
dt_stringsblock withgcc 15.2onx86_64(gcc -O2kept the open-coded loops inline and didn't turn them back intomemcmp()):Once you are doing timings, adding a few more doesn't take long.
Quoted 4 lines
* glibc
memchr+!p[slen]+ glibcmemcmp:
0.25 s (-O0), 0.23 s (-Os), 0.22 s (-O2)
* glibcmemchr+!p[slen]+ open-coded inner compare:
0.23 s (-O0), 0.21 s (-Os), 0.21 s (-O2)So that one is a marginal win.
Quoted 10 lines
* Fully open-coded (
p[0] == s[0] && !p[slen]+ inner byte loop):
0.91 s (-O0), 0.62 s (-Os), 0.40 s (-O2)
* Out-of-line byte-loopmemchr+!p[slen]+ byte-loopmemcmp:
0.86 s (-O0), 0.90 s (-Os), 0.50 s (-O2)
* Original per-byte out-of-line byte-loopmemcmp:
3.31 s (-O0), 1.87 s (-Os), 1.86 s (-O2)Even with a ~25-byte average stride, glibc's AVX2
memchr()handles almost an entire stride in a single 32-byte vector load + compare, so it beats the open-coded scalar loop by ~1.9x at-O2(and ~2.7x at-Os).Using avx2 is 'cheating' ...
Someone at Intel realised thatstrlen()does matter and threw some silicon at it. They finally did the same for integer divide (but I think AMD did it first) and did a divide that generates move than one bit per clock.Quoted 4 lines
Open-coding just the inner compare barely moves the needle since
!p[slen]already cutmemcmp()down to 14.3k calls across the 855 insertions.Quoted 8 lines
On the kernel / bootloader side,
fdt_find_string_len_()is only called byfdt_swandfdt_rwwhen adding new property names todt_strings-- normal read-only DTB parsing (fdt_ro.c) never calls it. And even with a naive out-of-line byte-loopmemchr(),memchr()+!p[slen]+memcmp()is still 3.7x faster at-O2(1.86 s -> 0.50 s) and 2.1x faster at-Os(1.87 s -> 0.90 s) than the old code, so keeping the simplermemchr()+!p[slen]+memcmp()seems like the right tradeoff.
Quoted 1 line
Seems reasonable.
Uh, calm down folks. I'm happy to take easy performance wins, but this really isn't worth getting deep into the weeds on.
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
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
In reply to Doug AndersonQuoted 65 lines · Doug Anderson
Hi David,
Quoted 11 lines · David Laight
Quoted 6 lines · On Mon, 16 Nov 2026 12:53:05 -0800 Douglas Anderson <[email protected]>…
fdt_find_string_len_()currently callsmemcmp()at every byte offset across the string table (for (p = strtab; p <= last; p++)). When building or modifying trees with large string tables (such as DTBs and overlays with hundreds of/__symbols__or/__fixups__labels viafdt_sworfdt_rw), scanning multi-kilobyte string tables byte by byte dominates serialization time.Quoted 2 lines
Are those symbols just in a linear list with embedded '\0' ? That doesn't scale well at all :-)
I'm assuming from your :-) that your "That doesn't scale well at all" was intended to be wrapped in <sarcasm> tags? :-P
Quoted 8 lines
Quoted 4 lines
Advance
pbetween candidate first-byte matches usingmemchr()(with an explicitslen == 0check for empty property names and atabsize < slen + 1bounds check before computinglast), preserving identical suffix-sharing behavior.Might it be better to scan for the '\0' that terminated/separates the strings? Then you do one
memcmp()for each string/symbol rather than for each time the first character appears in any string.Two things work against scanning for
'\0'here:1.
fdt_find_string_len_()intentionally supports suffix sharing (e.g."controller"matching the tail of"interrupt-controller\0"), so scanning for'\0'can't checknul + 1(the start of the next string) -- it has to start atstrtab + slenand testp = nul - slenbefore each'\0'.2. Every stored string ends with
'\0', whereass[0]only appears in a smaller fraction of bytes. On a real upstream Qualcomm base DTB'sdt_stringsblock (855 strings in 11,259 bytes, average 13.2 bytes per string),'\0'occurs on 7.6% of bytes whiles[0]averages 3.9%. Replaying those 855 insertions makes 362kmemchr()calls when scanning for'\0'vs. 187kmemchr()calls when scanning fors[0].Quoted 1 line
Even with the code below you want to do the !p[slen] check before the
memcmp().Agreed. Since
p <= last(strtab + tabsize - (slen + 1)),p[slen]is always in bounds, and checking!p[slen](i.e.p[slen] == '\0') beforememcmp(p, s, slen) == 0cuts thememcmp()call count across that 855-string replay from 187k down to 14.3k (the exact same 14.3kmemcmp()calls you'd get from scanning for'\0'with a*p == *spre-check, just with half as manymemchr()stops).Timing 200 replays of that 855-string (11,259-byte) Qualcomm
dt_stringsblock withgcc 15.2 -O2onx86_64:
* Original (per-bytememcmp): 3.45 s
* Scan for'\0',memcmp(nul - slen, s, slen): 0.45 s
* Scan for'\0',*p == *sthenmemcmp: 0.36 s
* Scan fors[0],memcmpthen!p[slen](mergedc954f9dd8357):
0.27 s
* Scan fors[0],!p[slen]thenmemcmp: 0.21 s (~20% faster)
Quoted 3 lines
Since you already applied this patch to
main(c954f9dd8357), so I'll include a 1-line follow-up patch swapping the check order (withSuggested-by:you) in v5.
Uh.. "you" seems to be referring to two different people here. I applied the patch, David Laight suggested the optimization.
Fwiw, since this further optimization is essentially free in terms of code complexity, I'm certainly happy to apply it. I am absolutely not keen on further micro-optimization of this.
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
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Hi,
Quoted 17 lines · David Gibson
Quoted 17 lines
Agreed. Since
p <= last(strtab + tabsize - (slen + 1)),p[slen]is always in bounds, and checking!p[slen](i.e.p[slen] == '\0') beforememcmp(p, s, slen) == 0cuts thememcmp()call count across that 855-string replay from 187k down to 14.3k (the exact same 14.3kmemcmp()calls you'd get from scanning for'\0'with a*p == *spre-check, just with half as manymemchr()stops).Timing 200 replays of that 855-string (11,259-byte) Qualcomm
dt_stringsblock withgcc 15.2 -O2onx86_64:
* Original (per-bytememcmp): 3.45 s
* Scan for'\0',memcmp(nul - slen, s, slen): 0.45 s
* Scan for'\0',*p == *sthenmemcmp: 0.36 s
* Scan fors[0],memcmpthen!p[slen](mergedc954f9dd8357):
0.27 s
* Scan fors[0],!p[slen]thenmemcmp: 0.21 s (~20% faster)
Quoted 6 lines
Quoted 3 lines
Since you already applied this patch to
main(c954f9dd8357), so I'll include a 1-line follow-up patch swapping the check order (withSuggested-by:you) in v5.Uh.. "you" seems to be referring to two different people here. I applied the patch, David Laight suggested the optimization.
Whoops, that's embarassing. I definitely glazed over the last names. Who could have expected two people named David?!? I will read more carefully.
Quoted 3 lines
Fwiw, since this further optimization is essentially free in terms of code complexity, I'm certainly happy to apply it. I am absolutely not keen on further micro-optimization of this.
OK, fair. Do you want me to drop the 1-line patch from my v5 draft then? It's basically this:
- if (memcmp(p, s, slen) == 0 && p[slen] == '\0')
+ if (p[slen] == '\0' && memcmp(p, s, slen) == 0)
While it is a micro-optimization, the code is no harder to read so it feels like a nice free speedup. ...but fine to drop it, too. ;-)
-Doug
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Quoted 25 lines · Doug Anderson
Hi,
Quoted 21 lines · David Gibson
Quoted 20 lines
Agreed. Since
p <= last(strtab + tabsize - (slen + 1)),p[slen]is always in bounds, and checking!p[slen](i.e.p[slen] == '\0') beforememcmp(p, s, slen) == 0cuts thememcmp()call count across that 855-string replay from 187k down to 14.3k (the exact same 14.3kmemcmp()calls you'd get from scanning for'\0'with a*p == *spre-check, just with half as manymemchr()stops).Timing 200 replays of that 855-string (11,259-byte) Qualcomm
dt_stringsblock withgcc 15.2 -O2onx86_64:
* Original (per-bytememcmp): 3.45 s
* Scan for'\0',memcmp(nul - slen, s, slen): 0.45 s
* Scan for'\0',*p == *sthenmemcmp: 0.36 s
* Scan fors[0],memcmpthen!p[slen](mergedc954f9dd8357):
0.27 s
* Scan fors[0],!p[slen]thenmemcmp: 0.21 s (~20% faster)Since you already applied this patch to
main(c954f9dd8357), so I'll include a 1-line follow-up patch swapping the check order (withSuggested-by:you) in v5.
Quoted 6 lines
Quoted 2 lines
Uh.. "you" seems to be referring to two different people here. I applied the patch, David Laight suggested the optimization.
Whoops, that's embarassing. I definitely glazed over the last names. Who could have expected two people named David?!? I will read more carefully.
Heh. In the past I've had a dtc query from another David Gibson. And I've received phone calls from the boss of a different David Gibson in the same large company I was working for. And I've received a reprint request intended for David Gibson the (former) parasitic worms researcher at Imperial College. It rather comes with having two fairly common names.
Quoted 10 lines
Quoted 3 lines
Fwiw, since this further optimization is essentially free in terms of code complexity, I'm certainly happy to apply it. I am absolutely not keen on further micro-optimization of this.
OK, fair. Do you want me to drop the 1-line patch from my v5 draft then? It's basically this:
(quoted diff) +1
-1- if (memcmp(p, s, slen) == 0 && p[slen] == '\0') + if (p[slen] == '\0' && memcmp(p, s, slen) == 0)
Quoted 2 lines
While it is a micro-optimization, the code is no harder to read so it feels like a nice free speedup. ...but fine to drop it, too. ;-)
Sorry, I was a bit unclear. Keep that change (though fold rather than a separate patch, I'd suggest). As you say it doesn't hurt readability at all. It was some of David Laight's more complex suggestions that I think are overkill.
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
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
David,
Quoted 11 lines · David Gibson
Quoted 11 lines
Quoted 4 lines
Fwiw, since this further optimization is essentially free in terms of code complexity, I'm certainly happy to apply it. I am absolutely not keen on further micro-optimization of this.
OK, fair. Do you want me to drop the 1-line patch from my v5 draft then? It's basically this:
(quoted diff) +1
-1- if (memcmp(p, s, slen) == 0 && p[slen] == '\0') + if (p[slen] == '\0' && memcmp(p, s, slen) == 0)
Quoted 6 lines
Quoted 2 lines
While it is a micro-optimization, the code is no harder to read so it feels like a nice free speedup. ...but fine to drop it, too. ;-)
Sorry, I was a bit unclear. Keep that change (though fold rather than a separate patch, I'd suggest). As you say it doesn't hurt readability at all.
I don't think I can "fold" because you (the correct "you" this time!) already applied the patch I'd fold it into. I think it has to be a separate patch at this point, doesn't it?
-Doug
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
Quoted 18 lines · Doug Anderson
David,
Quoted 14 lines · David Gibson
Quoted 13 lines
Quoted 4 lines
Fwiw, since this further optimization is essentially free in terms of code complexity, I'm certainly happy to apply it. I am absolutely not keen on further micro-optimization of this.
OK, fair. Do you want me to drop the 1-line patch from my v5 draft then? It's basically this:
(quoted diff) +1
-1- if (memcmp(p, s, slen) == 0 && p[slen] == '\0') + if (p[slen] == '\0' && memcmp(p, s, slen) == 0)While it is a micro-optimization, the code is no harder to read so it feels like a nice free speedup. ...but fine to drop it, too. ;-)
Quoted 7 lines
Quoted 3 lines
Sorry, I was a bit unclear. Keep that change (though fold rather than a separate patch, I'd suggest). As you say it doesn't hurt readability at all.
I don't think I can "fold" because you (the correct "you" this time!) already applied the patch I'd fold it into. I think it has to be a separate patch at this point, doesn't it?
Oh, yes, of course. Sorry.
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
Re: [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr()
In reply to David LaightQuoted 10 lines · David Laight
Quoted 6 lines · On Mon, 16 Nov 2026 12:53:05 -0800 Douglas Anderson <[email protected]>…
fdt_find_string_len_()currently callsmemcmp()at every byte offset across the string table (for (p = strtab; p <= last; p++)). When building or modifying trees with large string tables (such as DTBs and overlays with hundreds of/__symbols__or/__fixups__labels viafdt_sworfdt_rw), scanning multi-kilobyte string tables byte by byte dominates serialization time.
Quoted 2 lines
Are those symbols just in a linear list with embedded '\0' ? That doesn't scale well at all :-)
It's not supposed to scale, it's supposed to be simple. Device trees just aren't that large.
Quoted 8 lines
Quoted 4 lines
Advance
pbetween candidate first-byte matches usingmemchr()(with an explicitslen == 0check for empty property names and atabsize < slen + 1bounds check before computinglast), preserving identical suffix-sharing behavior.Might it be better to scan for the '\0' that terminated/separates the strings? Then you do one
memcmp()for each string/symbol rather than for each time the first character appears in any string.
Doesn't work; as Doug says, suffix sharing is supported.
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
PATCH v4 9/14 libfdt: overlay: Update base /__local_fixups__ on apply
In reply to Douglas AndersonWhen a base device tree is compiled with dtc -L (--local-fixups), it contains a root /__local_fixups__ node recording the byte offsets of all phandle references in its properties (for example, so an OS kernel can identify phandle cells at runtime, so a composite .dtb built by fdtoverlay such as Linux's foo-dtbs := base.dtb bar.dtbo retains complete phandle metadata for tools like fdtfactor, or so a merged tree matches what dtc -L produces).
fdt_overlay_apply() updates the base tree's /__symbols__ via overlay_symbol_update(), but leaves the base tree's /__local_fixups__ untouched. As a result, applying an overlay to a base tree with /__local_fixups__ leaves /__local_fixups__ missing the phandle references introduced by the overlay (both from the overlay's /__local_fixups__ and from its resolved /__fixups__), and leaves stale offsets if the overlay overwrites a base property that previously had phandle references.
Add overlay_local_fixups_update(), controlled by a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS setting in libfdt/libfdt_internal.h:
- 0 (FDT_OVERLAY_LOCAL_FIXUPS_IGNORE): Leave /__local_fixups__ untouched. This is the #ifndef fallback in libfdt_internal.h so that size-sensitive embedded environments (such as U-Boot SPL) that vendor libfdt directly get zero code-size increase and no behavior change unless they opt in.
- 1 (FDT_OVERLAY_LOCAL_FIXUPS_STRIP): Delete /__local_fixups__ from the base tree if present (~50 bytes of code), avoiding leaving a stale/incomplete /__local_fixups__ node in the merged tree.
- 2 (FDT_OVERLAY_LOCAL_FIXUPS_UPDATE): Fully update the base tree's /__local_fixups__ node when present (clearing entries for overwritten properties, merging offsets from the overlay's /__local_fixups__ and /__fixups__ in sorted ascending order, and pruning any subnodes that become empty). This is enabled by default in dtc's Meson (-Doverlay-local-fixups=2) and Make (OVERLAY_LOCAL_FIXUPS=2) builds for desktop tools and tests.
---
Changes in v4:
- Split out internal helper fdt_add_empty_subnode_() so overlay_fragment_local_fixups() avoids passing an in-blob pointer to fdt_add_subnode_namelen() or casting fdt_get_name() (Simon Glass)
- Add test cases in tests/overlay.c where the overlay target has no existing subnode under /__local_fixups__, with /__local_fixups__ both before and after the target in the blob (Simon Glass)
- Pass OVERLAY_LOCAL_FIXUPS to tests/run_tests.sh, adjust fdtoverlay_tests for all three modes, and use 4-space indentation (Simon Glass, David Gibson)
Changes in v3:
- Move constifying fdto in overlay_apply_node() into a standalone preparatory patch (David Gibson)
- Gate /__local_fixups__ handling behind a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS flag (0=ignore, 1=strip, 2=update), defaulting to 0 (IGNORE) in libfdt_internal.h for embedded builds and 2 (UPDATE) in Meson/Make desktop builds (Simon Glass, David Gibson)
- Rewrite commit message in the present tense with motivation up front, and update fdt_overlay_apply() documentation in libfdt/libfdt.h (Simon Glass)
- Require a strict relative path in overlay_create_path() and return -FDT_ERR_BADOVERLAY on empty path components or trailing '/' (David Gibson)
- Eliminate the 256-byte namebuf limit in overlay_fragment_local_fixups() by re-reading the node name from the shifted ancestor offset after fdt_add_subnode_namelen() (David Gibson, Simon Glass)
- Return -FDT_ERR_BADVALUE instead of -FDT_ERR_BADSTRUCTURE in overlay_add_local_fixup_offset() when an existing /__local_fixups__ property length is not a multiple of 4 (David Gibson, Simon Glass)
- Drop redundant overlay_validate_local_fixups() pre-pass and inline single-use helpers (Simon Glass)
Changes in v2:
- New patch updating base /__local_fixups__ in libfdt fdt_overlay_apply() instead of stripping /__local_fixups__ by default (David Gibson)
Makefile | 6 +- libfdt/fdt_overlay.c | 525 ++++++++++++++++++++++++++++++++++++++- libfdt/fdt_rw.c | 37 ++- libfdt/libfdt.h | 7 + libfdt/libfdt_internal.h | 23 ++ meson.build | 5 + meson_options.txt | 2 + tests/Makefile.tests | 6 +- tests/meson.build | 1 + tests/overlay.c | 154 ++++++++++++ tests/run_tests.sh | 32 +++ 11 files changed, 780 insertions(+), 18 deletions(-)
Makefile +5 -1
@@ -21,7 +21,11 @@ CONFIG_LOCALVERSION = # See libfdt_internal.h for details ASSUME_MASK ?= 0 -CPPFLAGS = -I libfdt -I . -DFDT_ASSUME_MASK=$(ASSUME_MASK) +# Control how fdt_overlay_apply() handles base /__local_fixups__ (0=ignore, 1=strip, 2=update) +# See libfdt_internal.h for details +OVERLAY_LOCAL_FIXUPS ?= 2 + +CPPFLAGS = -I libfdt -I . -DFDT_ASSUME_MASK=$(ASSUME_MASK) -DFDT_OVERLAY_LOCAL_FIXUPS=$(OVERLAY_LOCAL_FIXUPS) WARNINGS = -Wall -Wpointer-arith -Wcast-qual -Wnested-externs -Wsign-compare \ -Wstrict-prototypes -Wmissing-prototypes -Wredundant-decls -Wshadow \ -Wwrite-strings
libfdt/fdt_overlay.c +522 -3
543 lines not on this page · raw message
libfdt/fdt_rw.c +26 -11
@@ -365,8 +365,8 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)return fdt_splice_struct_ (fdt, prop, proplen,0 ); } -int fdt_add_subnode_namelen (void *fdt,int parentoffset, -const char *name,int namelen) +int fdt_add_empty_subnode_ (void *fdt,int parentoffset,int namelen, +char **namep) {struct fdt_node_header *nh;int offset, nextoffset;
@@ -375,14 +375,6 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,uint32_t tag;fdt32_t *endtag; -FDT_RW_PROBE (fdt); - - offset =fdt_subnode_offset_namelen (fdt, parentoffset, name, namelen); -if (offset >=0 ) -return -FDT_ERR_EXISTS ; -else if (offset != -FDT_ERR_NOTFOUND ) -return offset; -/* Try to place the new node after the parent's properties */ tag =fdt_next_tag (fdt, parentoffset, &nextoffset);/* the fdt_subnode_offset_namelen() should ensure this never hits */
@@ -402,9 +394,32 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset, nh->tag =cpu_to_fdt32 (FDT_BEGIN_NODE );memset (nh->name,0 ,FDT_TAGALIGN (namelen+1 )); -memcpy (nh->name, name, namelen); endtag = (fdt32_t *)((char *)nh + nodelen -FDT_TAGSIZE ); *endtag =cpu_to_fdt32 (FDT_END_NODE ); + *namep = nh->name; + +return offset; +} + +int fdt_add_subnode_namelen (void *fdt,int parentoffset, +const char *name,int namelen) +{ +char *namep; +int offset; + +FDT_RW_PROBE (fdt); + + offset =fdt_subnode_offset_namelen (fdt, parentoffset, name, namelen); +if (offset >=0 ) +return -FDT_ERR_EXISTS ; +else if (offset != -FDT_ERR_NOTFOUND ) +return offset; + + offset =fdt_add_empty_subnode_ (fdt, parentoffset, namelen, &namep); +if (offset <0 ) +return offset; + +memcpy (namep, name, namelen);return offset; }
libfdt/libfdt.h +7 -0
@@ -2472,6 +2472,13 @@ int fdt_del_node(void *fdt, int nodeoffset);* fdt_overlay_apply() will apply the given device tree overlay on the * given base device tree. * +* If the base device tree contains a /__symbols__ node, it is updated with +* any symbols from the overlay. If the base device tree contains a +* /__local_fixups__ node, how it is handled depends on the build-time +* FDT_OVERLAY_LOCAL_FIXUPS setting (see libfdt_internal.h): left untouched +* (IGNORE), deleted (STRIP), or updated to reflect phandle references in the +* merged tree (UPDATE, the default when built via dtc's build system). +* * Expect the base device tree to be modified, even if the function * returns an error. *
libfdt/libfdt_internal.h +23 -0
@@ -32,6 +32,8 @@ static inline const char *fdt_find_string_(const char *strtab, int tabsize, }int fdt_node_end_offset_ (void *fdt,int nodeoffset); +int fdt_add_empty_subnode_ (void *fdt,int parentoffset,int namelen, +char **namep);static inline const void *fdt_offset_ptr_ (const void *fdt,int offset) {
@@ -99,6 +101,27 @@ static inline uint64_t fdt64_ld_(const fdt64_t *p)#define FDT_PARENT_MAX_DEPTH 32#endif +/* +* Controls how fdt_overlay_apply() handles a /__local_fixups__ node in the +* base device tree: +* 0 (FDT_OVERLAY_LOCAL_FIXUPS_IGNORE): Leave /__local_fixups__ untouched +* (zero extra code size and preserves historical behavior; default when +* building libfdt standalone without dtc's build system). +* 1 (FDT_OVERLAY_LOCAL_FIXUPS_STRIP): Delete /__local_fixups__ from the +* base device tree so a stale/incomplete /__local_fixups__ node is not +* left behind (~50 bytes of code). +* 2 (FDT_OVERLAY_LOCAL_FIXUPS_UPDATE): Fully update /__local_fixups__ in +* the base device tree with the overlay's local and resolved external +* phandle fixups (default when building via dtc's Meson/Make build). +*/ +#define FDT_OVERLAY_LOCAL_FIXUPS_IGNORE 0 +#define FDT_OVERLAY_LOCAL_FIXUPS_STRIP 1 +#define FDT_OVERLAY_LOCAL_FIXUPS_UPDATE 2 + +#ifndef FDT_OVERLAY_LOCAL_FIXUPS +#define FDT_OVERLAY_LOCAL_FIXUPS FDT_OVERLAY_LOCAL_FIXUPS_IGNORE +#endif +/* * Defines assumptions which can be enabled. Each of these can be enabled * individually. For maximum safety, don't enable any assumptions!
meson.build +5 -0
@@ -28,6 +28,11 @@ add_project_arguments( language: 'c' ) +add_project_arguments( + '-DFDT_OVERLAY_LOCAL_FIXUPS=' + get_option('overlay-local-fixups').to_string(), + language: 'c' +) + yamltree = 'yamltree.c' yaml = dependency('yaml-0.1', version: '>=0.2.3', required: get_option('yaml')) if not yaml.found()
meson_options.txt +2 -0
@@ -2,6 +2,8 @@ option('tools', type: 'boolean', value: true, description: 'Build tools') option('assume-mask', type: 'integer', value: 0, description: 'Control the assumptions made (e.g. risking security issues) in the code.') +option('overlay-local-fixups', type: 'integer', value: 2, + description: 'Control how fdt_overlay_apply() handles base /__local_fixups__ (0=ignore, 1=strip, 2=update)') option('yaml', type: 'feature', value: 'auto', description: 'YAML support') option('valgrind', type: 'feature', value: 'auto',
tests/Makefile.tests +3 -3
@@ -81,18 +81,18 @@ tests_clean: rm -rf $(TESTS_CLEANDIRS) check: tests ${TESTS_BIN} $(TESTS_PYLIBFDT) - cd $(TESTS_PREFIX); ./run_tests.sh + cd $(TESTS_PREFIX); OVERLAY_LOCAL_FIXUPS=$(OVERLAY_LOCAL_FIXUPS) ./run_tests.sh ifeq ($(NO_VALGRIND),1) checkm: @echo "make checkm requires valgrind, but NO_VALGRIND=1" else checkm: tests ${TESTS_BIN} $(TESTS_PYLIBFDT) - cd $(TESTS_PREFIX); ./run_tests.sh -m + cd $(TESTS_PREFIX); OVERLAY_LOCAL_FIXUPS=$(OVERLAY_LOCAL_FIXUPS) ./run_tests.sh -m endif checkv: tests ${TESTS_BIN} $(TESTS_PYLIBFDT) - cd $(TESTS_PREFIX); ./run_tests.sh -v + cd $(TESTS_PREFIX); OVERLAY_LOCAL_FIXUPS=$(OVERLAY_LOCAL_FIXUPS) ./run_tests.sh -v ifneq ($(DEPTARGETS),) -include $(TESTS_DEPFILES)
tests/meson.build +1 -0
@@ -128,6 +128,7 @@ if not yaml.found() else env += 'NO_YAML=0' endif +env += 'OVERLAY_LOCAL_FIXUPS=' + get_option('overlay-local-fixups').to_string() run_test_types = [ 'libfdt',
tests/overlay.c +154 -0
172 lines not on this page · raw message
tests/run_tests.sh +32 -0
@@ -11,6 +11,10 @@ if [ -z "$PYTHON" ]; then PYTHON=python3 fi +if [ -z "$OVERLAY_LOCAL_FIXUPS" ]; then + OVERLAY_LOCAL_FIXUPS=2 +fi + if [ -n "$NO_PYTHON" ]; then if [ "$NO_PYTHON" != "0" ]; then no_python=true
@@ -1147,6 +1151,34 @@ fdtoverlay_tests() { shorten_echo "check phandle to noda d wasn't overwritten: " run_wrap_test test "$bd" = "$pd" + + # verify how /__local_fixups__ in a -L base blob is handled when applying an overlay + run_dtc_test -@ -L -I dts -O dtb -o overlay_base_phandle_lf.test.dtb "$SRCDIR/overlay_base_phandle.dts" + run_wrap_test $FDTOVERLAY -i overlay_base_phandle_lf.test.dtb -o overlay_base_phandle_lfO.test.dtb overlay_overlay_phandle.test.dtb + run_dtc_test -@ -L -I dts -O dtb -o overlay_base_lf.test.dtb "$SRCDIR/overlay_base.dts" + run_wrap_test $DTPUT overlay_base_lf.test.dtb -cp /__local_fixups__/test-node/sub-test-node + run_wrap_test $DTPUT overlay_base_lf.test.dtb /__local_fixups__/test-node/sub-test-node new-sub-test-property -tu 0 + run_dtc_test -@ -I dts -O dtb -o overlay_overlay.fdtoverlay.test.dtb "$SRCDIR/overlay_overlay.dts" + run_wrap_test $FDTOVERLAY -i overlay_base_lf.test.dtb -o overlay_base_lfO.test.dtb overlay_overlay.fdtoverlay.test.dtb + if [ "$OVERLAY_LOCAL_FIXUPS" -eq 2 ]; then + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/b a + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/b d + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/c b + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/d a + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/d b + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/d c + + run_fdtget_test "0 4" overlay_base_lfO.test.dtb /__local_fixups__/test-node test-phandle + run_fdtget_test "0 4" overlay_base_lfO.test.dtb /__local_fixups__/test-node test-several-phandle + run_test check_path overlay_base_lfO.test.dtb not-exists "/__local_fixups__/test-node/sub-test-node" + elif [ "$OVERLAY_LOCAL_FIXUPS" -eq 1 ]; then + run_test check_path overlay_base_phandle_lfO.test.dtb not-exists "/__local_fixups__" + run_test check_path overlay_base_lfO.test.dtb not-exists "/__local_fixups__" + else + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/b a + run_wrap_error_test $DTGET overlay_base_phandle_lfO.test.dtb /__local_fixups__/b d + run_fdtget_test 0 overlay_base_lfO.test.dtb /__local_fixups__/test-node/sub-test-node new-sub-test-property + fi } run_python_tests () {
Signature · 1 line
2.56.0.679.gc527c65306-goog
Re: [PATCH v4 09/14] libfdt: overlay: Update base /__local_fixups__ on apply
Hi Doug,
Quoted 23 lines · Douglas Anderson
libfdt: overlay: Update base /__local_fixups__ on apply
When a base device tree is compiled with
dtc -L(--local-fixups), it contains a root/__local_fixups__node recording the byte offsets of all phandle references in its properties (for example, so an OS kernel can identify phandle cells at runtime, so a composite.dtbbuilt byfdtoverlaysuch as Linux'sfoo-dtbs := base.dtb bar.dtboretains complete phandle metadata for tools likefdtfactor, or so a merged tree matches whatdtc -Lproduces).
fdt_overlay_apply()updates the base tree's/__symbols__viaoverlay_symbol_update(), but leaves the base tree's/__local_fixups__untouched. As a result, applying an overlay to a base tree with/__local_fixups__leaves/__local_fixups__missing the phandle references introduced by the overlay (both from the overlay's/__local_fixups__and from its resolved/__fixups__), and leaves stale offsets if the overlay overwrites a base property that previously had phandle references.Add
overlay_local_fixups_update(), controlled by a 3-state compile-timeFDT_OVERLAY_LOCAL_FIXUPSsetting inlibfdt/libfdt_internal.h:
Quoted 5 lines
-
0(FDT_OVERLAY_LOCAL_FIXUPS_IGNORE): Leave/__local_fixups__untouched. This is the#ifndeffallback inlibfdt_internal.hso that size-sensitive embedded environments (such as U-Boot SPL) that vendorlibfdtdirectly get zero code-size increase and no behavior change unless they opt in.
The test suite passes for me with -Doverlay-local-fixups set to 0, 1 and 2.
One thing I'd like to check is the 'zero code-size increase' claim, which no longer holds now that fdt_add_subnode_namelen() is split (see below).
Quoted 22 lines
[...]
Makefile | 6 +- libfdt/fdt_overlay.c | 525 ++++++++++++++++++++++++++++++++++++++++++++++- libfdt/fdt_rw.c | 37 +++- libfdt/libfdt.h | 7 + libfdt/libfdt_internal.h | 23 +++ meson.build | 5 + meson_options.txt | 2 + tests/Makefile.tests | 6 +- tests/meson.build | 1 + tests/overlay.c | 154 ++++++++++++++ tests/run_tests.sh | 32 +++ 11 files changed, 780 insertions(+), 18 deletions(-)libfdt/fdt_rw.c +5
-0@@ -405,9 +397,32 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset, +int fdt_add_subnode_namelen (void *fdt,int parentoffset, +const char *name,int namelen) +{ +char *namep; +int offset;
libfdt/fdt_rw.c int fdt_add_subnode_namelen(void *fdt, int parentoffset, · line 411
Quoted 10 lines
libfdt/fdt_rw.c +10
-0+ +FDT_RW_PROBE (fdt); + + offset =fdt_subnode_offset_namelen (fdt, parentoffset, name, namelen); +if (offset >=0 ) +return -FDT_ERR_EXISTS ; +else if (offset != -FDT_ERR_NOTFOUND ) +return offset; + + offset =fdt_add_empty_subnode_ (fdt, parentoffset, namelen, &namep);
Since fdt_add_empty_subnode_() is not static, every build pays for the split, including IGNORE ones. With gcc -Os on x86-64 the text size of fdt_rw.o goes from 4610 to 4743 bytes for me (I have not tried other compilers or architectures).
Please can you either avoid the growth when FDT_OVERLAY_LOCAL_FIXUPS is not UPDATE, or update the commit message and the comment in libfdt_internal.h to give the real cost?
Regards,
Simon
Re: [PATCH v4 09/14] libfdt: overlay: Update base /__local_fixups__ on apply
Hi Simon,
Quoted 32 lines · Simon Glass
The test suite passes for me with -Doverlay-local-fixups set to 0, 1 and 2.
One thing I'd like to check is the 'zero code-size increase' claim, which no longer holds now that
fdt_add_empty_subnode_()is split (see below).[...]
Quoted 7 lines
libfdt/fdt_rw.c +5
-0@@ -405,9 +397,32 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset, +int fdt_add_subnode_namelen (void *fdt,int parentoffset, +const char *name,int namelen) +{ +char *namep; +int offset;libfdt/fdt_rw.c int fdt_add_subnode_namelen(void *fdt, int parentoffset, · line 411
Quoted 10 lines
libfdt/fdt_rw.c +10
-0+ +FDT_RW_PROBE (fdt); + + offset =fdt_subnode_offset_namelen (fdt, parentoffset, name, namelen); +if (offset >=0 ) +return -FDT_ERR_EXISTS ; +else if (offset != -FDT_ERR_NOTFOUND ) +return offset; + + offset =fdt_add_empty_subnode_ (fdt, parentoffset, namelen, &namep);Since
fdt_add_empty_subnode_()is not static, every build pays for the split, including IGNORE ones. With gcc -Os on x86-64 the text size of fdt_rw.o goes from 4610 to 4743 bytes for me (I have not tried other compilers or architectures).
Quoted 3 lines
Please can you either avoid the growth when
FDT_OVERLAY_LOCAL_FIXUPSis not UPDATE, or update the commit message and the comment inlibfdt_internal.hto give the real cost?
Ah, right -- .text itself grew by ~37 bytes from the out-of-line split, and size also counts the second function's .eh_frame unwind entry (plus endbr64 with -fcf-protection).
For v5 I added a small VISIBLE_IF_LOCAL_FIXUPS_UPDATE macro in libfdt_internal.h (modeled on Linux's VISIBLE_IF_KUNIT) so fdt_add_empty_subnode_() is static when FDT_OVERLAY_LOCAL_FIXUPS != FDT_OVERLAY_LOCAL_FIXUPS_UPDATE and inlines back into fdt_add_subnode_namelen() (+12 bytes of .text from register scheduling on x86-64 gcc -Os, zero .eh_frame growth). I also tempered the wording in libfdt_internal.h and the commit message from "zero" to "negligible code-size impact".
-Doug
PATCH v4 10/14 fdtfactor: Add tool to split DTBs into a base DTB and overlays
In reply to Douglas AndersonWhen shipping a single firmware or kernel image that supports many closely related board variants or SKUs, bundling a full compiled .dtb for every variant results in substantial duplication.
Add fdtfactor, a Python tool built on pylibfdt and libpydt that takes a set of compiled device tree blobs (.dtb) compiled with -@ -L (/__symbols__ and /__local_fixups__) and splits them into a single common base.dtb and per-board .dtbo overlays:
- Common nodes present across all input DTBs are placed in base.dtb, with each common property assigned the value shared by at least two boards that maximizes byte savings across overlays.
- Using /__local_fixups__, phandle references inside property values are normalized to target node paths so common properties referencing common nodes match even when numeric phandles differ across input DTBs.
- Any common node that carries a phandle in any input DTB receives its phandle in base.dtb so overlays only emit phandle properties on newly added subnodes, matching the requirements of libfdt, Linux's drivers/of/overlay.c, and coreboot's dt_apply_overlay().
Add a fdtfactor test suite in tests/run_tests.sh verifying that applying each generated .dtbo to base.dtb with fdtoverlay reconstructs the original DTB (verified via dtbs_equal_unordered, including across input DTBs with shifted phandle numbers).
---
Changes in v4:
- Rename -o/--outdir to -o/--output so standalone DTB mode and FIT mode share the same output option, and use 4-space indentation in tests/run_tests.sh (David Gibson)
- Update for libpydt rename, use Property.as_*(), Property.from_*(), and DeviceTree.set_prop() instead of DeviceTree get_*/set_* wrapper methods, and drop redundant bytes() copies on Property instances (David Gibson, Simon Glass)
- Replace ParsedDtb.raw_bytes with uncompressed_size, use early continue to reduce loop nesting, drop redundant set() before sorted() on local fixup offsets, and clarify pre-order walk and phandle comments (David Gibson)
- Allow dtc -@ -L inputs with no phandles (where dtc omits /__symbols__ and /__local_fixups__)
- Check _is_dtbo_overlay() on the unflattened DeviceTree, index ParsedDtb.nodes and base_nodes by path, and skip unchanged base nodes in _build_board_dtbo() to avoid repeated O(depth) traversals and per-property comparisons
- Handle OVERLAY_LOCAL_FIXUPS != 2 in fdtfactor_tests (Simon Glass)
Changes in v3:
- Update fdtfactor to use devicetree.DeviceTree and a FactoredTree subclass initializing self.phandle and self.fixups in __init__() (David Gibson, Simon Glass)
- Rename -b/--base-dtb to --output-base-dtb to avoid confusion with an input base DTB (David Gibson)
- Move the test rejecting input DTBs lacking /__local_fixups__ from the -S patch into this base patch (Simon Glass)
Changes in v2:
- Preserve /__local_fixups__ on base.dtb by default (David Gibson)
- Store parsed trees directly in NodeTree with node.phandle and node.fixups attributes instead of parallel dicts (David Gibson)
- Extract phandles in a separate pass after unflattening and reject legacy linux,phandle properties (David Gibson)
- Exclude non-root common phandle nodes lacking a common symbol from base.dtb instead of synthesizing __fdtfactor_ph_* symbols (David Gibson)
- Drop -q/--quiet, rename -v/--verbose to -s/--stats, and move tests to a dedicated fdtfactor test suite (David Gibson)
Makefile | 2 +- README.md | 43 ++ fdtfactor | 881 +++++++++++++++++++++++++++++ meson.build | 1 + tests/Makefile.tests | 4 +- tests/fdtfactor_board1.dts | 72 +++ tests/fdtfactor_board2.dts | 70 +++ tests/fdtfactor_board3.dts | 68 +++ tests/fdtfactor_board3_shifted.dts | 68 +++ tests/meson.build | 2 +- tests/run_tests.sh | 110 +++- tests/testutils.sh | 1 + 12 files changed, 1315 insertions(+), 7 deletions(-) create mode 100755 fdtfactor create mode 100644 tests/fdtfactor_board1.dts create mode 100644 tests/fdtfactor_board2.dts create mode 100644 tests/fdtfactor_board3.dts create mode 100644 tests/fdtfactor_board3_shifted.dts
Makefile +1 -1
@@ -169,7 +169,7 @@ BIN += fdtget BIN += fdtput BIN += fdtoverlay -SCRIPTS = dtdiff +SCRIPTS = dtdiff fdtfactor all: $(BIN) libfdt
README.md +43 -0
49 lines not on this page · raw message
fdtfactor new file +881 -0
881 lines not on this page · raw message
meson.build +1 -0
@@ -119,6 +119,7 @@ if get_option('tools') and not wheel_only install_data( 'dtdiff', + 'fdtfactor', install_dir: get_option('bindir'), install_mode: 'rwxr-xr-x', )
tests/Makefile.tests +2 -2
@@ -53,10 +53,10 @@ TESTS_DEPFILES = $(TESTS:%=%.d) \ $(addprefix $(TESTS_PREFIX),testutils.d) TESTS_CLEANFILES_L = $(STD_CLEANFILES) \ - *.dtb *.test.dts *.test.dt.yaml *.dtsv1 tmp.* *.bak \ + *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 tmp.* *.bak \ treegen TESTS_CLEANFILES = $(TESTS) $(TESTS_CLEANFILES_L:%=$(TESTS_PREFIX)%) -TESTS_CLEANDIRS_L = fs +TESTS_CLEANDIRS_L = fs *.test.dir TESTS_CLEANDIRS = $(TESTS_CLEANDIRS_L:%=$(TESTS_PREFIX)%) .PHONY: tests
tests/fdtfactor_board1.dts new file +72 -0
72 lines not on this page · raw message
tests/fdtfactor_board2.dts new file +70 -0
70 lines not on this page · raw message
tests/fdtfactor_board3.dts new file +68 -0
68 lines not on this page · raw message
tests/fdtfactor_board3_shifted.dts new file +68 -0
68 lines not on this page · raw message
tests/meson.build +1 -1
@@ -144,7 +144,7 @@ run_test_deps = [ dtc_tools, treegen_dtb, tests_exe, ] if pylibfdt_enabled - run_test_types += 'pylibfdt' + run_test_types += ['pylibfdt', 'fdtfactor'] run_test_deps += pylibfdt endif foreach test_type : run_test_types
tests/run_tests.sh +107 -3
133 lines not on this page · raw message
tests/testutils.sh +1 -0
@@ -27,6 +27,7 @@ DTGET=${TEST_BINDIR}/fdtget DTPUT=${TEST_BINDIR}/fdtput FDTDUMP=${TEST_BINDIR}/fdtdump FDTOVERLAY=${TEST_BINDIR}/fdtoverlay +FDTFACTOR=${SRCDIR}/../fdtfactor verbose_run () { if [ -z "$QUIET_TEST" ]; then
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 11/14 fdtfactor: Add -S/--strip-local-fixups option
In reply to Douglas AndersonBy default, fdtfactor preserves /__local_fixups__ on base.dtb so that when fdt_overlay_apply() merges a .dtbo overlay, the reconstructed device tree retains full /__local_fixups__ information (for instance, if an OS kernel wants to know which property cells contain phandles at runtime).
When -L was passed to dtc solely to help fdtfactor locate phandle cells at build time and /__local_fixups__ is not needed at runtime, retaining /__local_fixups__ in base.dtb wastes space.
Add -S / --strip-local-fixups to omit /__local_fixups__ from base.dtb (and therefore from the merged device trees produced by fdt_overlay_apply()). On a set of 47 Qualcomm SC7180 Trogdor Chromebook board DTBs, fdtfactor without -S reduces total uncompressed size from 7.69 MB to 932 KB (88.2% savings), while fdtfactor -S reduces it to 634 KB (91.8% savings, saving an additional 298 KB by omitting /__local_fixups__ from base.dtb).
Add a test case in tests/run_tests.sh verifying that fdtfactor -S followed by fdtoverlay reproduces DTBs compiled with -@ (without -L) via dtbs_equal_unordered.
---
Changes in v4:
- Use 4-space indentation instead of mixed tabs and spaces in tests/run_tests.sh, and update context for -o/--output (David Gibson)
Changes in v3:
- Include both non--S (932 KB) and -S (634 KB) Trogdor size numbers in the commit message to show the savings of -S itself (Simon Glass)
- Pass -S to the negative test verifying that inputs lacking /__local_fixups__ are still rejected when -S is used, and move the non--S rejection test to the base fdtfactor patch (Simon Glass)
Changes in v2:
- Split -S/--strip-local-fixups into a separate opt-in patch (David Gibson)
README.md | 9 +++++++++ fdtfactor | 21 ++++++++++++++++++--- tests/run_tests.sh | 19 +++++++++++++++++++ 3 files changed, 46 insertions(+), 3 deletions(-)
README.md +9 -0
@@ -228,6 +228,15 @@ Options: * `-o`, `--output`: Output directory for generated `.dtbo` files and `--output-base-dtb` (default: alongside each input `.dtb` for `.dtbo` files, current directory for `--output-base-dtb`). +* `-S`, `--strip-local-fixups`: Omit `/__local_fixups__` from the generated + `base.dtb` and final reconstructed device trees. By default, `fdtfactor` + preserves `/__local_fixups__` on `base.dtb` so that when `fdt_overlay_apply()` + merges a `.dtbo` overlay, the reconstructed device tree retains full + `/__local_fixups__` information (e.g., for an OS kernel that wants to + know which property cells contain phandles at runtime). When `-L` was + passed to `dtc` solely to help `fdtfactor` locate phandles at build time + and `/__local_fixups__` is not needed at runtime, passing `-S` strips it + from `base.dtb` to save space. * `-s`, `--stats`: Print size savings summary. ### TODO
fdtfactor +18 -3
@@ -675,11 +675,13 @@ def _build_board_dtbo(dtb, base_nodes, base_dtb_symbols, return bytes(dtbo_root.flatten().as_bytearray()) -def create_base_dtb_and_overlays(dtbs): +def create_base_dtb_and_overlays(dtbs, strip_local_fixups=False): """Compute the base DTB and per-board DTBO blobs from parsed DTBs. Args: dtbs: Sequence of `ParsedDtb` instances (at least two). + strip_local_fixups: If True, omit `/__local_fixups__` from the + generated `base.dtb`. Returns: Tuple of `(base_dtb_blob, dtbo_blobs)` where `base_dtb_blob` is the
@@ -694,7 +696,9 @@ def create_base_dtb_and_overlays(dtbs): base_dtb_blob = _serialize_base_dtb( base_nodes, base_dtb_symbols, dtbs[0].mem_rsv, dtbs[0].boot_cpuid_phys, - emit_local_fixups=any(d.has_local_fixups for d in dtbs), + emit_local_fixups=( + not strip_local_fixups and any(d.has_local_fixups for d in dtbs) + ), ) dtbo_blobs = [ _build_board_dtbo(
@@ -757,6 +761,14 @@ def parse_args(argv=None): 'current directory for --output-base-dtb)' ), ) + parser.add_argument( + '-S', '--strip-local-fixups', + action='store_true', + help=( + 'Omit /__local_fixups__ from the generated base .dtb and ' + 'reconstructed device trees' + ), + ) parser.add_argument( '-s', '--stats', action='store_true',
@@ -841,7 +853,10 @@ def factor_dtb_files(args): seen_paths.add(abs_out) dtbo_paths.append(out_path) - base_dtb_blob, dtbo_blobs = create_base_dtb_and_overlays(dtbs) + base_dtb_blob, dtbo_blobs = create_base_dtb_and_overlays( + dtbs, + strip_local_fixups=args.strip_local_fixups, + ) if args.output: os.makedirs(args.output, exist_ok=True)
tests/run_tests.sh +19 -0
@@ -1305,6 +1305,25 @@ fdtfactor_tests () { done run_wrap_error_test $PYTHON $FDTFACTOR -o fdtfactor_legacy.test.dir \ fdtfactor_board1.nolf.test.dtb fdtfactor_board2.test.dtb + + # Strip local fixups (-S): verify that merged DTBs match DTBs compiled + # with -@ (without -L), and that inputs lacking /__local_fixups__ are + # still rejected even when -S is passed. + run_wrap_error_test $PYTHON $FDTFACTOR -S -o fdtfactor_strip.test.dir \ + fdtfactor_board1.nolf.test.dtb fdtfactor_board2.test.dtb + rm -rf fdtfactor_strip.test.dir + run_wrap_test $PYTHON $FDTFACTOR -S --output-base-dtb base_strip.test.dtb \ + -o fdtfactor_strip.test.dir \ + fdtfactor_board1.test.dtb fdtfactor_board2.test.dtb \ + fdtfactor_board3.test.dtb + for i in 1 2 3; do + run_wrap_test $FDTOVERLAY \ + -i fdtfactor_strip.test.dir/base_strip.test.dtb \ + -o fdtfactor_strip.test.dir/merged${i}.test.dtb \ + fdtfactor_strip.test.dir/fdtfactor_board${i}.test.dtbo + run_test dtbs_equal_unordered fdtfactor_board${i}.nolf.test.dtb \ + fdtfactor_strip.test.dir/merged${i}.test.dtb + done } while getopts "vt:me" ARG ; do
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 12/14 fdtfactor: Support compressed DTB inputs and outputs
In reply to Douglas AndersonFirmware and FIT build pipelines frequently store device tree blobs compressed with LZ4, LZMA/XZ, or gzip (e.g., .dtb.lz4).
Add -C / --compression (none, lz4, lz4_legacy, lzma, xz, gzip; default none) to fdtfactor to decompress compressed input DTBs before factoring and compress the resulting base.dtb and .dtbo outputs with the same algorithm:
- Support lz4 and lz4_legacy (via the lz4 CLI), lzma and xz (via Python's lzma module, using CHECK_CRC32 for XZ compatibility with kernel/bootloader decompressors), and gzip (via Python's gzip module).
- Default --output-base-dtb to base.dtb.<ext> matching -C / --compression (e.g., base.dtb.lz4 when -C lz4 is passed), and emit .dtbo.<ext> overlays.
- Report compressed size savings alongside uncompressed savings when -s / --stats is specified with compression enabled.
On the 47 Qualcomm SC7180 Trogdor Chromebook .dtb.lz4 files, fdtfactor -S -C lz4 reduces total LZ4-compressed size from 1.08 MB (built without -@ -L) to 214 KB (80.2% savings).
---
Changes in v4:
- Replace magic-byte/extension auto-detection and --base-compression with a single explicit -C/--compression option controlling both input and output compression (David Gibson)
- Drop unnecessary --stats documentation/help changes and use 4-space indentation in tests/run_tests.sh (David Gibson)
- Use check_factored_dtb in fdtfactor_tests so tests pass when OVERLAY_LOCAL_FIXUPS != 2 (Simon Glass)
Changes in v3:
- Update for -b/--base-dtb rename to --output-base-dtb (David Gibson)
Changes in v2:
- Add --base-compression to explicitly control base.dtb compression while documenting auto-detection from --base-dtb's filename suffix (David Gibson)
- Support legacy LZ4 frames (lz4 -l) and use CRC32 check for XZ outputs (Simon Glass)
README.md | 11 ++- fdtfactor | 208 ++++++++++++++++++++++++++++++++++++++----- tests/Makefile.tests | 5 +- tests/run_tests.sh | 51 ++++++++++- 4 files changed, 248 insertions(+), 27 deletions(-)
README.md +8 -3
@@ -204,7 +204,8 @@ $ fdtoverlay -i base.dtb -o merged.dtb overlay1.dtbo overlay2.dtbo ## fdtfactor `fdtfactor` is a Python tool built on `pylibfdt` that takes a set of -compiled device tree blobs (`.dtb`) and splits them into a single common +compiled device tree blobs (`.dtb`, or compressed `.dtb.lz4`, `.dtb.xz`, +`.dtb.lzma`, `.dtb.gz` with `-C`) and splits them into a single common `base.dtb` and per-board `.dtbo` overlays so that applying a board's `.dtbo` to `base.dtb` recreates the original board device tree while reducing total storage size.
@@ -223,8 +224,12 @@ $ fdtfactor -o out_dir board1.dtb board2.dtb board3.dtb Options: * `--output-base-dtb`: Output filename for the common base `.dtb` - (default: `base.dtb`; placed in `--output` if specified, or the current - directory otherwise). + (default: `base.dtb`, or `base.dtb.<ext>` when `-C` / `--compression` is + used; placed in `--output` if specified, or the current directory + otherwise). +* `-C`, `--compression`: Compression format for both input `.dtb` files and + generated `base.dtb` / `.dtbo` outputs: `none`, `lz4`, `lz4_legacy`, `lzma`, + `xz`, or `gzip` (default: `none`). * `-o`, `--output`: Output directory for generated `.dtbo` files and `--output-base-dtb` (default: alongside each input `.dtb` for `.dtbo` files, current directory for `--output-base-dtb`).
fdtfactor +186 -22
323 lines not on this page · raw message
tests/Makefile.tests +4 -1
@@ -53,7 +53,10 @@ TESTS_DEPFILES = $(TESTS:%=%.d) \ $(addprefix $(TESTS_PREFIX),testutils.d) TESTS_CLEANFILES_L = $(STD_CLEANFILES) \ - *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 tmp.* *.bak \ + *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 \ + *.test.dtb.gz *.test.dtbo.gz *.test.dtb.xz *.test.dtbo.xz \ + *.test.dtb.lzma *.test.dtbo.lzma *.test.dtb.lz4 *.test.dtbo.lz4 \ + tmp.* *.bak \ treegen TESTS_CLEANFILES = $(TESTS) $(TESTS_CLEANFILES_L:%=$(TESTS_PREFIX)%) TESTS_CLEANDIRS_L = fs *.test.dir
tests/run_tests.sh +50 -1
63 lines not on this page · raw message
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 13/14 fdtfactor: Add compiled FIT factoring support
In reply to Douglas AndersonBootloaders such as depthcharge on Chromebooks and U-Boot use Flattened Image Trees (FITs) to bundle a kernel image with multiple board FDT blobs (fdt-1, fdt-2, ...) and per-board configuration nodes.
Add -F/--fit, --min-overlap, and --single-base-dtb options to fdtfactor (writing the factored FIT to -o/--output, or updating --fit in place by default):
- Parse non-overlay type = "flat_dt" nodes under /images, decompressing their data blobs according to their compression property (none, lz4, lzma, xz, gzip).
- Reject FITs containing signature* subnodes under /images/* or /configurations/*, as modifying FDT blobs and configurations would invalidate cryptographic signatures.
- Partition the flat_dt blobs into factor groups by compatible FDT headers / FIT arch and load properties and shared normalized property byte overlap (>= --min-overlap%, default 50%, reusing select_best_candidate()'s _prop_byte_cost() model) so a single FIT containing multiple board/SoC families produces a separate fdt-base-1, fdt-base-2, etc. for each family.
- Support --single-base-dtb to force all flat_dt blobs into a single base DTB regardless of property overlap, failing only if their FDT headers, arch, or load properties differ.
- Insert each fdt-base-N node into /images (picking the next unused fdt-base-N name), replace each factored fdt-* node's data with its .dtbo overlay (preserving each node's compression setting, and stripping /__local_fixups__ from any unfactored single-board flat_dt nodes too when -S is passed), recompute any hash* subnode digests, and prepend fdt-base-N to each matching configuration's fdt string list while preserving all other configuration properties (description, compatible, etc., populating compatible from the board DTB's root node when omitted) and any pre-existing overlay entries.
Add uncompressed, LZ4-compressed multi-family, --min-overlap, unfactored-singleton -S, pre-existing fdt-base-* / multi-pass, signed-FIT rejection, and --single-base-dtb FIT test cases to the fdtfactor test suite.
---
Changes in v4:
- Unify --outfile into -o/--output, and split standalone DTB vs. FIT options into separate README.md subsections and --help groups (David Gibson)
- Check _is_dtbo_overlay() directly in _extract_fit_fdt_entries() instead of adding OverlayBlobError to ParsedDtb (David Gibson)
- Map standard FIT hash algorithm names explicitly via FIT_HASH_ALGOS instead of passing raw names to hashlib.new() (David Gibson)
- Remove compression and entry from FIT grouping, document load, expose --min-overlap, and compute FIT group overlap using normalized property byte costs via _prop_byte_cost() instead of unweighted node paths (David Gibson)
- Strip /__local_fixups__ from unfactored single-board FIT flat_dt entries when -S/--strip-local-fixups is passed, and pick the next unused fdt-base-N node name instead of rejecting FITs that already contain fdt-base-* nodes
- Pass already-unflattened FactoredTree into ParsedDtb and intern normalized properties to integer IDs in group_fit_dtbs() to speed up multi-SoC FIT factoring
- Preserve whether input FIT FDT descriptions include a compression extension instead of unconditionally appending one
- Update for libpydt rename, use Property.as_*(), Property.from_*(), and DeviceTree.set_prop() instead of DeviceTree get_*/set_* wrapper methods, and drop redundant bytes() copies on Property instances (David Gibson, Simon Glass)
- Use check_factored_dtb and 4-space indentation in tests/run_tests.sh (Simon Glass, David Gibson)
Changes in v3:
- Use "FIT" instead of "FIT image" in documentation, comments, and commit messages (Simon Glass)
- Update for DeviceTree and --output-base-dtb (Simon Glass, David Gibson)
Changes in v2:
- Rename -f/--fit and -F/--fit-out to -F/--fit and --outfile and clarify FIT mode in the --help description (David Gibson, Simon Glass)
- Reject signed FIT images with signature* subnodes (Simon Glass)
- Use '<base-node-name>.dtb' for FIT base FDT descriptions instead of common-prefix heuristics (Simon Glass)
- Compare FIT group node overlap against the group's common node set instead of only the first entry (Simon Glass)
- Document in README.md that U-Boot's boot_get_fdt_fit() currently requires FIT overlays to be uncompressed (Simon Glass)
README.md | 89 +++- fdtfactor | 850 +++++++++++++++++++++++++++++++++---- tests/Makefile.tests | 2 +- tests/fdtfactor_lz4.its | 109 +++++ tests/fdtfactor_other1.dts | 67 +++ tests/fdtfactor_other2.dts | 67 +++ tests/fdtfactor_test.its | 109 +++++ tests/run_tests.sh | 225 +++++++++- 8 files changed, 1421 insertions(+), 97 deletions(-) create mode 100644 tests/fdtfactor_lz4.its create mode 100644 tests/fdtfactor_other1.dts create mode 100644 tests/fdtfactor_other2.dts create mode 100644 tests/fdtfactor_test.its
README.md +66 -23
@@ -203,14 +203,14 @@ $ fdtoverlay -i base.dtb -o merged.dtb overlay1.dtbo overlay2.dtbo ## fdtfactor -`fdtfactor` is a Python tool built on `pylibfdt` that takes a set of -compiled device tree blobs (`.dtb`, or compressed `.dtb.lz4`, `.dtb.xz`, -`.dtb.lzma`, `.dtb.gz` with `-C`) and splits them into a single common -`base.dtb` and per-board `.dtbo` overlays so that applying a board's -`.dtbo` to `base.dtb` recreates the original board device tree while -reducing total storage size. - -Input `.dtb` files must be compiled with `dtc -@ -L` so that both +`fdtfactor` is a Python tool built on `pylibfdt` that factors a set of +compiled device tree blobs — either standalone `.dtb` files or +`/images/fdt-*` nodes inside a compiled FIT — into a common base `.dtb` +and per-board `.dtbo` overlays so that applying a board's `.dtbo` to the +base `.dtb` recreates the original board device tree while reducing +total storage size. + +Input `.dtb` blobs must be compiled with `dtc -@ -L` so that both `/__symbols__` (used to resolve overlay `/__fixups__` against `base.dtb`) and `/__local_fixups__` (used to identify phandle references inside property values) are present.
@@ -219,30 +219,73 @@ Basic usage: ``` $ fdtfactor -o out_dir board1.dtb board2.dtb board3.dtb +$ fdtfactor -F image.fit -o image.factored.fit ``` -Options: +Common options: +* `-S`, `--strip-local-fixups`: Omit `/__local_fixups__` from the generated + base `.dtb` and final reconstructed device trees. By default, `fdtfactor` + preserves `/__local_fixups__` on the base `.dtb` so that when + `fdt_overlay_apply()` merges a `.dtbo` overlay, the reconstructed device + tree retains full `/__local_fixups__` information (e.g., for an OS kernel + that wants to know which property cells contain phandles at runtime). When + `-L` was passed to `dtc` solely to help `fdtfactor` locate phandles at + build time and `/__local_fixups__` is not needed at runtime, passing `-S` + strips it from the base `.dtb` (and any unfactored FIT FDTs) to save space. +* `-s`, `--stats`: Print size savings summary. + +### Standalone DTB Factoring + +When `-F` / `--fit` is not passed, `fdtfactor` takes two or more positional +`.dtb` files (or compressed `.dtb.lz4`, `.dtb.xz`, `.dtb.lzma`, `.dtb.gz` +files with `-C`) and writes a common base `.dtb` plus one `.dtbo` overlay per +input file: + +* `-o`, `--output`: Output directory for generated `.dtbo` files and + `--output-base-dtb` (default: alongside each input `.dtb` for `.dtbo` + files, current directory for `--output-base-dtb`). * `--output-base-dtb`: Output filename for the common base `.dtb` (default: `base.dtb`, or `base.dtb.<ext>` when `-C` / `--compression` is - used; placed in `--output` if specified, or the current directory + used; placed in `-o` / `--output` if specified, or the current directory otherwise). * `-C`, `--compression`: Compression format for both input `.dtb` files and generated `base.dtb` / `.dtbo` outputs: `none`, `lz4`, `lz4_legacy`, `lzma`, `xz`, or `gzip` (default: `none`). -* `-o`, `--output`: Output directory for generated `.dtbo` files and - `--output-base-dtb` (default: alongside each input `.dtb` for `.dtbo` files, - current directory for `--output-base-dtb`). -* `-S`, `--strip-local-fixups`: Omit `/__local_fixups__` from the generated - `base.dtb` and final reconstructed device trees. By default, `fdtfactor` - preserves `/__local_fixups__` on `base.dtb` so that when `fdt_overlay_apply()` - merges a `.dtbo` overlay, the reconstructed device tree retains full - `/__local_fixups__` information (e.g., for an OS kernel that wants to - know which property cells contain phandles at runtime). When `-L` was - passed to `dtc` solely to help `fdtfactor` locate phandles at build time - and `/__local_fixups__` is not needed at runtime, passing `-S` strips it - from `base.dtb` to save space. -* `-s`, `--stats`: Print size savings summary. + +### FIT Factoring + +When `-F` / `--fit` is passed, `fdtfactor` updates a compiled Flattened Image +Tree: + +* `-F`, `--fit`: Input compiled FIT (`.fit` / `.itb`) to factor. +* `-o`, `--output`: Output FIT path (default: overwrite `--fit` in place). +* `--min-overlap`: Minimum percentage (`0`–`100`, default: `50`) of normalized + property bytes shared with a group's common properties required to place a + `flat_dt` node into that group. +* `--single-base-dtb`: Force a single `/images/fdt-base-1` across all FDTs in + the FIT regardless of property overlap. + +FIT behavior and constraints: + +* Non-overlay `type = "flat_dt"` subnodes under `/images` are decompressed + according to their FIT `compression` property (`none`, `lz4`, `lzma`, `xz`, + `gzip`) and partitioned into factor groups that share compatible FDT headers, + `arch`, and `load` properties and at least `--min-overlap`% of normalized + property bytes (or forced into a single group when `--single-base-dtb` is + passed). +* For each group, `fdtfactor` inserts `/images/fdt-base-N`, converts each + member `/images/fdt-*` node into a `.dtbo` overlay (preserving each node's + `compression` setting and stripping any `load` address), prepends + `fdt-base-N` to matching `/configurations/conf-*` `fdt` string lists + (populating `compatible` from the board DTB's root node when omitted), and + recomputes `/images/*/hash*` digests. +* Note that while bootloaders such as depthcharge decompress compressed FIT + overlays, U-Boot's `boot_get_fdt_fit()` currently only decompresses the base + DTB and requires FIT overlays to be uncompressed. +* Signed FITs containing `signature*` subnodes are rejected because modifying + FDT blobs and configurations would invalidate cryptographic signatures; sign + the FIT after factoring. ### TODO
fdtfactor +778 -72
996 lines not on this page · raw message
tests/Makefile.tests +1 -1
@@ -53,7 +53,7 @@ TESTS_DEPFILES = $(TESTS:%=%.d) \ $(addprefix $(TESTS_PREFIX),testutils.d) TESTS_CLEANFILES_L = $(STD_CLEANFILES) \ - *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 \ + *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 *.test.fit \ *.test.dtb.gz *.test.dtbo.gz *.test.dtb.xz *.test.dtbo.xz \ *.test.dtb.lzma *.test.dtbo.lzma *.test.dtb.lz4 *.test.dtbo.lz4 \ tmp.* *.bak \
tests/fdtfactor_lz4.its new file +109 -0
109 lines not on this page · raw message
tests/fdtfactor_other1.dts new file +67 -0
67 lines not on this page · raw message
tests/fdtfactor_other2.dts new file +67 -0
67 lines not on this page · raw message
tests/fdtfactor_test.its new file +109 -0
109 lines not on this page · raw message
tests/run_tests.sh +224 -1
237 lines not on this page · raw message
Signature · 1 line
2.56.0.679.gc527c65306-goog
PATCH v4 14/14 fdtfactor: Parallelize blob compression and decompression
In reply to Douglas AndersonWhen factoring dozens or hundreds of compressed DTBs (either standalone with -C or inside a compiled FIT with -F), running gzip, lzma, xz, or external lz4 processes sequentially spends several seconds compressing and decompressing blobs one at a time.
Because Python's zlib and _lzma C extensions and subprocess.run() for lz4 all release the GIL, add a small _map_blobs() helper using concurrent.futures.ThreadPoolExecutor to decompress input blobs and compress output base/overlay blobs across worker threads in deterministic input order whenever multiple compressed blobs are processed.
---
Found this speedup while benchmarking fdtfactor. It's not critical to functionality, but seems like a nice win.
Changes in v4:
- New patch parallelizing blob compression and decompression across worker threads
fdtfactor | 190 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 138 insertions(+), 52 deletions(-)
fdtfactor +138 -52
@@ -18,6 +18,7 @@ its embedded `/images/fdt-*` blobs into base DTBs (`fdt-base-1`, `fdt-base-2`, import argparse from collections import Counter +import concurrent.futures import copy import gzip import hashlib
@@ -140,6 +141,32 @@ def compress_blob(raw_bytes, comp, filename=''): raise ValueError(f'{prefix}Unsupported compression type: {comp}') +def _map_blobs(func, tasks, pool=None): + """Apply `func(blob, comp, filename)` across `tasks`, parallelizing if compressed. + + Python's `zlib` and `_lzma` C extensions and external `lz4` subprocesses + release the GIL, so running multiple compressed tasks across a + `ThreadPoolExecutor` overlaps compression and decompression across CPU + cores while preserving deterministic input order. + + Args: + func: `decompress_blob` or `compress_blob`. + tasks: Sequence of `(blob_bytes, comp, filename)` tuples. + pool: Optional shared `ThreadPoolExecutor` instance. + + Returns: + List of processed `bytes` in the same order as `tasks`. + """ + if len(tasks) < 2 or not any( + comp not in ('none', '', None) for _, comp, _ in tasks + ): + return [func(*t) for t in tasks] + if pool is not None: + return list(pool.map(lambda t: func(*t), tasks)) + with concurrent.futures.ThreadPoolExecutor() as new_pool: + return list(new_pool.map(lambda t: func(*t), tasks)) + + def _is_dtbo_overlay(root): """Return True if `root` is a `.dtbo` overlay tree rather than a base DTB.
@@ -1061,13 +1088,14 @@ def group_fit_dtbs(fdt_entries, min_overlap=50.0): return [grp['entries'] for grp in groups] -def _extract_fit_fdt_entries(fit_in_path, images_node, configs_node): +def _extract_fit_fdt_entries(fit_in_path, images_node, configs_node, pool=None): """Extract and parse non-overlay `flat_dt` entries from `/images`. Args: fit_in_path: Input FIT path (for error reporting). images_node: `DeviceTree` for the FIT `/images` node. configs_node: `DeviceTree` for the FIT `/configurations` node. + pool: Optional shared `ThreadPoolExecutor` for decompression. Returns: List of dicts (`{'name', 'node', 'dtb', 'fdt'}`) for all non-overlay
@@ -1081,7 +1109,7 @@ def _extract_fit_fdt_entries(fit_in_path, images_node, configs_node): f'is not supported; sign the FIT after factoring' ) - fdt_entries = [] + candidates = [] for img_name, img_node in images_node.children.items(): if ('data-offset' in img_node.props or 'data-position' in img_node.props):
@@ -1112,7 +1140,19 @@ def _extract_fit_fdt_entries(fit_in_path, images_node, configs_node): ) if comp == 'lz4' and raw_data.startswith(LZ4_LEGACY_MAGIC): comp = 'lz4_legacy' - raw_bytes = decompress_blob(raw_data, comp, filename=node_label) + candidates.append((img_name, img_node, node_label, comp, raw_data)) + + raw_blobs = _map_blobs( + decompress_blob, + [(raw_data, comp, node_label) + for _, _, node_label, comp, raw_data in candidates], + pool=pool, + ) + + fdt_entries = [] + for (img_name, img_node, node_label, comp, raw_data), raw_bytes in zip( + candidates, raw_blobs + ): fdt = _open_fdt(raw_bytes, node_label) root = FactoredTree.unflatten(fdt) if _is_dtbo_overlay(root):
@@ -1194,13 +1234,15 @@ def _partition_fit_fdt_entries(fdt_entries, single_base_dtb, min_overlap=50.0): return factorable_groups, unfactored_entries -def _strip_fit_unfactored_local_fixups(unfactored_entries): +def _strip_fit_unfactored_local_fixups(unfactored_entries, pool=None): """Strip `/__local_fixups__` from unfactored FIT `flat_dt` entries. Args: unfactored_entries: List of single-board FIT `flat_dt` entry dicts left unfactored by `_partition_fit_fdt_entries()`. + pool: Optional shared `ThreadPoolExecutor` for compression. """ + to_recompress = [] for entry in unfactored_entries: fdt = entry.pop('fdt') tree = libpydt.DeviceTree.unflatten(fdt)
@@ -1210,17 +1252,26 @@ def _strip_fit_unfactored_local_fixups(unfactored_entries): mem_rsv=entry['dtb'].mem_rsv, boot_cpuid_phys=entry['dtb'].boot_cpuid_phys, ) - comp_bytes = compress_blob( - bytes(stripped_fdt.as_bytearray()), + stripped_bytes = bytes(stripped_fdt.as_bytearray()) + to_recompress.append(( + entry['node'], + stripped_bytes, entry['dtb'].compression, - filename=f'/images/{entry["name"]}', - ) - img_node = entry['node'] + f'/images/{entry["name"]}', + )) + + comp_blobs = _map_blobs( + compress_blob, + [(blob, comp, label) for _, blob, comp, label in to_recompress], + pool=pool, + ) + for (img_node, _, _, _), comp_bytes in zip(to_recompress, comp_blobs): img_node.set_prop(libfdt.Property('data', comp_bytes)) _update_fit_hashes(img_node) -def _factor_fit_group(entries, base_dtb_node_name, strip_local_fixups): +def _factor_fit_group(entries, base_dtb_node_name, strip_local_fixups, + pool=None): """Factor one group of FIT `flat_dt` entries into a base node and overlays. Args:
@@ -1229,6 +1280,7 @@ def _factor_fit_group(entries, base_dtb_node_name, strip_local_fixups): node (e.g., `'fdt-base-1'`). strip_local_fixups: If True, omit `/__local_fixups__` from the generated base DTB. + pool: Optional shared `ThreadPoolExecutor` for compression. Returns: Tuple of `(base_dtb_node, stat_args)` where `base_dtb_node` is the
@@ -1241,9 +1293,20 @@ def _factor_fit_group(entries, base_dtb_node_name, strip_local_fixups): ) base_comp = group_dtbs[0].compression - base_dtb_comp_bytes = compress_blob( - base_dtb_blob, base_comp, filename=f'/images/{base_dtb_node_name}' + comp_blobs = _map_blobs( + compress_blob, + [ + (base_dtb_blob, base_comp, f'/images/{base_dtb_node_name}'), + *( + (dtbo_blob, entry['dtb'].compression, f'/images/{entry["name"]}') + for entry, dtbo_blob in zip(entries, dtbo_blobs) + ), + ], + pool=pool, ) + base_dtb_comp_bytes = comp_blobs[0] + dtbo_comp_blobs = comp_blobs[1:] + base_dtb_node = copy.deepcopy(entries[0]['node']) for prop in ('phandle', 'compatible'): base_dtb_node.props.pop(prop, None)
@@ -1272,12 +1335,9 @@ def _factor_fit_group(entries, base_dtb_node_name, strip_local_fixups): _update_fit_hashes(base_dtb_node) dtbo_comp_sizes = [] - for entry, dtbo_blob in zip(entries, dtbo_blobs): + for entry, dtbo_comp_bytes in zip(entries, dtbo_comp_blobs): img_node = entry['node'] entry_comp = entry['dtb'].compression - dtbo_comp_bytes = compress_blob( - dtbo_blob, entry_comp, filename=f'/images/{entry["name"]}' - ) dtbo_comp_sizes.append(len(dtbo_comp_bytes)) if 'description' in img_node.props:
@@ -1386,39 +1446,42 @@ def factor_fit(fit_in_path, fit_out_path, strip_local_fixups=False, f'/configurations nodes' ) - fdt_entries = _extract_fit_fdt_entries( - fit_in_path, images_node, configs_node - ) - factorable_groups, unfactored_entries = _partition_fit_fdt_entries( - fdt_entries, single_base_dtb, min_overlap=min_overlap - ) - if strip_local_fixups and unfactored_entries: - _strip_fit_unfactored_local_fixups(unfactored_entries) - else: - for entry in unfactored_entries: - entry.pop('fdt', None) - - fdt_to_base_dtb = {} - insert_before_first = {} - group_stats = [] - used_image_names = set(images_node.children) - next_base_idx = 1 - - for entries in factorable_groups: - while f'fdt-base-{next_base_idx}' in used_image_names: - next_base_idx += 1 - base_dtb_node_name = f'fdt-base-{next_base_idx}' - used_image_names.add(base_dtb_node_name) - next_base_idx += 1 - base_dtb_node, stat_args = _factor_fit_group( - entries, base_dtb_node_name, strip_local_fixups + with concurrent.futures.ThreadPoolExecutor() as pool: + fdt_entries = _extract_fit_fdt_entries( + fit_in_path, images_node, configs_node, pool=pool ) - insert_before_first[entries[0]['name']] = ( - base_dtb_node_name, base_dtb_node + factorable_groups, unfactored_entries = _partition_fit_fdt_entries( + fdt_entries, single_base_dtb, min_overlap=min_overlap ) - for entry in entries: - fdt_to_base_dtb[entry['name']] = (base_dtb_node_name, entry['dtb']) - group_stats.append(stat_args) + if strip_local_fixups and unfactored_entries: + _strip_fit_unfactored_local_fixups(unfactored_entries, pool=pool) + else: + for entry in unfactored_entries: + entry.pop('fdt', None) + + fdt_to_base_dtb = {} + insert_before_first = {} + group_stats = [] + used_image_names = set(images_node.children) + next_base_idx = 1 + + for entries in factorable_groups: + while f'fdt-base-{next_base_idx}' in used_image_names: + next_base_idx += 1 + base_dtb_node_name = f'fdt-base-{next_base_idx}' + used_image_names.add(base_dtb_node_name) + next_base_idx += 1 + base_dtb_node, stat_args = _factor_fit_group( + entries, base_dtb_node_name, strip_local_fixups, pool=pool + ) + insert_before_first[entries[0]['name']] = ( + base_dtb_node_name, base_dtb_node + ) + for entry in entries: + fdt_to_base_dtb[entry['name']] = ( + base_dtb_node_name, entry['dtb'] + ) + group_stats.append(stat_args) _update_fit_images_and_configs( images_node, configs_node, insert_before_first, fdt_to_base_dtb
@@ -1668,7 +1731,24 @@ def factor_dtb_files(args): """ comp = args.compression input_dtb_paths = args.dtbs - dtbs = [ParsedDtb(p, comp=comp) for p in input_dtb_paths] + file_blobs = [] + for p in input_dtb_paths: + with open(p, 'rb') as f: + file_blobs.append(f.read()) + raw_blobs = _map_blobs( + decompress_blob, + [(b, comp, p) for p, b in zip(input_dtb_paths, file_blobs)], + ) + dtbs = [ + ParsedDtb( + p, + comp=comp, + fdt=_open_fdt(raw, p), + uncompressed_size=len(raw), + compressed_size=len(fblob), + ) + for p, fblob, raw in zip(input_dtb_paths, file_blobs, raw_blobs) + ] base_dtb_path = ( os.path.join(args.output, args.output_base_dtb)
@@ -1706,20 +1786,26 @@ def factor_dtb_files(args): strip_local_fixups=args.strip_local_fixups, ) - base_dtb_file_bytes = compress_blob( - base_dtb_blob, comp, filename=base_dtb_path + comp_blobs = _map_blobs( + compress_blob, + [ + (base_dtb_blob, comp, base_dtb_path), + *((b, comp, p) for p, b in zip(dtbo_paths, dtbo_blobs)), + ], ) + base_dtb_file_bytes = comp_blobs[0] + dtbo_comp_blobs = comp_blobs[1:] + if args.output: os.makedirs(args.output, exist_ok=True) with open(base_dtb_path, 'wb') as f: f.write(base_dtb_file_bytes) dtbo_file_sizes = [] - for out_path, dtbo_blob in zip(dtbo_paths, dtbo_blobs): + for out_path, out_bytes in zip(dtbo_paths, dtbo_comp_blobs): out_dir = os.path.dirname(out_path) if out_dir: os.makedirs(out_dir, exist_ok=True) - out_bytes = compress_blob(dtbo_blob, comp, filename=out_path) dtbo_file_sizes.append(len(out_bytes)) with open(out_path, 'wb') as f: f.write(out_bytes)
Signature · 1 line
2.56.0.679.gc527c65306-goog
Re: [PATCH v4 14/14] fdtfactor: Parallelize blob compression and decompression
Hi Douglas,
Quoted 16 lines · Douglas Anderson
Because Python's
zliband_lzmaC extensions andsubprocess.run()forlz4all release the GIL, add a small_map_blobs()helper usingconcurrent.futures.ThreadPoolExecutorto decompress input blobs and compress output base/overlay blobs across worker threads in deterministic input order whenever multiple compressed blobs are processed.Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>fdtfactor | 190 +++++++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 138 insertions(+), 52 deletions(-)
fdtfactor def compress_blob(raw_bytes, comp, filename=''): · line 144
Quoted 4 lines
fdtfactor +4
-0@@ -140,6 +141,32 @@ def compress_blob(raw_bytes, comp, filename=''): + if pool is not None: + return list(pool.map(lambda t: func(*t), tasks)) + with concurrent.futures.ThreadPoolExecutor() as new_pool: + return list(new_pool.map(lambda t: func(*t), tasks))
Is the shared pool worth it? Creating a ThreadPoolExecutor is cheap next to compressing even one blob, and factor_dtb_files() already relies on the pool being created here. If _map_blobs() always creates its own, the 'pool' argument can be dropped from _extract_fit_fdt_entries(), _strip_fit_unfactored_local_fixups() and _factor_fit_group(), and factor_fit() doesn't need to be re-indented. What do you think?
BTW the default is up to 32 workers, so with lz4 this can start up to 32 processes at once, regardless of any -j limit in the build that calls the tool. It would be worth a -j/--jobs option, perhaps as a follow-up.
fdtfactor def factor_dtb_files(args): · line 1740
Quoted 12 lines
fdtfactor +10
-0@@ -1668,7 +1731,24 @@ def factor_dtb_files(args): + dtbs = [ + ParsedDtb( + p, + comp=comp, + fdt=_open_fdt(raw, p), + uncompressed_size=len(raw), + compressed_size=len(fblob), + ) + for p, fblob, raw in zip(input_dtb_paths, file_blobs, raw_blobs) + ]
This was the last caller which relied on ParsedDtb reading and decompressing the file itself, so the 'if fdt is None' path in ParsedDtb.__init__() is now dead code. Please can you drop it, make 'fdt' a required argument and update the docstring?
Regards,
Simon
Re: [PATCH v4 14/14] fdtfactor: Parallelize blob compression and decompression
Hi Simon,
Quoted 15 lines · Simon Glass
fdtfactor def compress_blob(raw_bytes, comp, filename=''): · line 144
Quoted 7 lines
fdtfactor +4
-0@@ -140,6 +141,32 @@ def compress_blob(raw_bytes, comp, filename=''): + if pool is not None: + return list(pool.map(lambda t: func(*t), tasks)) + with concurrent.futures.ThreadPoolExecutor() as new_pool: + return list(new_pool.map(lambda t: func(*t), tasks))Is the shared pool worth it? Creating a ThreadPoolExecutor is cheap next to compressing even one blob, and
factor_dtb_files()already relies on the pool being created here. If_map_blobs()always creates its own, the 'pool' argument can be dropped from_extract_fit_fdt_entries(),_strip_fit_unfactored_local_fixups()and_factor_fit_group(), andfactor_fit()doesn't need to be re-indented. What do you think?
Makes sense. Creating a ThreadPoolExecutor inside _map_blobs() is in the noise next to blob compression, and dropping pool keeps factor_fit() and its helpers much cleaner. Done for v5.
Quoted 4 lines
BTW the default is up to 32 workers, so with lz4 this can start up to 32 processes at once, regardless of any -j limit in the build that calls the tool. It would be worth a -j/--jobs option, perhaps as a follow-up.
Agreed, adding -j/--jobs (or jobserver integration) as a follow-up sounds worthwhile.
Quoted 9 lines
Quoted 9 lines
fdtfactor +7
-0@@ -1668,7 +1731,24 @@ def factor_dtb_files(args): + dtbs = [ + ParsedDtb( + p, + comp=comp, + fdt=_open_fdt(raw, p), + uncompressed_size=len(raw), + compressed_size=len(fblob),
Quoted 8 lines
fdtfactor def factor_dtb_files(args): · line 1751
Quoted 3 lines
fdtfactor +3
-0+ ) + for p, fblob, raw in zip(input_dtb_paths, file_blobs, raw_blobs) + ]This was the last caller which relied on ParsedDtb reading and decompressing the file itself, so the 'if fdt is None' path in
ParsedDtb.__init__()is now dead code. Please can you drop it, make 'fdt' a required argument and update the docstring?
Done for v5.
-Doug
Quoted 4 lines · Douglas Anderson
Devicetree overlays exist at both the source level (via
/include/and.dtsifiles) and the binary level (where a compiled.dtbooverlay is applied to a "base".dtbat runtime to add or modify nodes).
Patches 1..4 are all nice cleanups regardless of the rest of the series, so I've merged them. Still looking at the remainder.
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
Quoted 8 lines · David Gibson
Quoted 4 lines · Douglas Anderson
Devicetree overlays exist at both the source level (via
/include/and.dtsifiles) and the binary level (where a compiled.dtbooverlay is applied to a "base".dtbat runtime to add or modify nodes).Patches 1..4 are all nice cleanups regardless of the rest of the series, so I've merged them. Still looking at the remainder.
Sorry, meant to say 1..5. I've now applied 8 as well.
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