From: Douglas Anderson <dianders@chromium.org>
To: Devicetree-compiler@vger.kernel.org,
David Gibson <david@gibson.dropbear.id.au>,
Simon Glass <sjg@chromium.org>
Cc: "Conor Dooley" <conor+dt@kernel.org>,
Devicetree@vger.kernel.org,
"Konrad Dybcio" <konradybcio@kernel.org>,
"Peter Griffin" <peter.griffin@linaro.org>,
"Brian Norris" <briannorris@chromium.org>,
"David Laight" <david.laight.linux@gmail.com>,
"Julius Werner" <jwerner@chromium.org>,
"Krzysztof Kozlowski" <krzk+dt@kernel.org>,
"André Draszik" <andre.draszik@linaro.org>,
"Rob Herring" <robh@kernel.org>,
"Saravana Kannan" <saravanak@kernel.org>,
"Tudor Ambarus" <tudor.ambarus@linaro.org>,
"Chen-Yu Tsai" <wenst@chromium.org>,
linux-kernel@vger.kernel.org,
"Douglas Anderson" <dianders@chromium.org>
Subject: [PATCH v5 8/8] fdtfactor: Parallelize blob compression and decompression
Date: Fri, 4 Dec 2026 07:36:45 -0800 [thread overview]
Message-ID: <20261204153756.1926794-9-dianders@chromium.org> (raw)
In-Reply-To: <20261204153756.1926794-1-dianders@chromium.org>
When 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. Now that `factor_dtb_files()` also reads and decompresses
input blobs up front, drop the unused `fdt is None` path from
`ParsedDtb.__init__()` and make `fdt` a required argument.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
---
Found this speedup while benchmarking fdtfactor. It's not critical to
functionality, but seems like a nice win.
Changes in v5:
- Always create the ThreadPoolExecutor inside _map_blobs() instead of
threading a shared pool argument through factor_fit() and its helpers
(Simon Glass)
- Drop the dead 'if fdt is None' path in ParsedDtb.__init__(), make
'fdt' a required argument, and update its docstring (Simon Glass)
Changes in v4:
- New patch parallelizing blob compression and decompression across
worker threads
fdtfactor | 149 +++++++++++++++++++++++++++++++++++++++---------------
1 file changed, 107 insertions(+), 42 deletions(-)
diff --git a/fdtfactor b/fdtfactor
index ebf40cdeaf92..74b376b9731a 100755
--- a/fdtfactor
+++ b/fdtfactor
@@ -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,29 @@ def compress_blob(raw_bytes, comp, filename=''):
raise ValueError(f'{prefix}Unsupported compression type: {comp}')
+def _map_blobs(func, tasks):
+ """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.
+
+ 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]
+ with concurrent.futures.ThreadPoolExecutor() as pool:
+ return list(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.
@@ -213,37 +237,29 @@ class ParsedDtb:
independent of numeric phandle numbering.
"""
- def __init__(self, filename, comp='none', fdt=None, root=None,
+ def __init__(self, filename, fdt, comp='none', root=None,
uncompressed_size=None, compressed_size=None):
- """Parse an input FDT file or opened `FdtRo` into a `FactoredTree`.
+ """Parse an opened `FdtRo` into a normalized `FactoredTree`.
Args:
- filename: File path (or display name when `fdt` is provided).
+ filename: File path or display name for error reporting and stats.
+ fdt: Already-validated `libfdt.FdtRo` instance.
comp: Compression format string (default: `'none'`).
- fdt: Optional already-validated `libfdt.FdtRo` instance; if None,
- read and decompressed from `filename`.
root: Optional already-unflattened `FactoredTree` for `fdt`.
- uncompressed_size: Uncompressed byte length when `fdt` is provided.
- compressed_size: Raw/compressed byte length when `fdt` is provided.
+ uncompressed_size: Uncompressed byte length (defaults to
+ `fdt.totalsize()`).
+ compressed_size: Raw/compressed byte length (defaults to
+ `self.uncompressed_size`).
"""
self.filename = filename
self.compression = comp
- if fdt is None:
- with open(filename, 'rb') as f:
- file_bytes = f.read()
- self.compressed_size = len(file_bytes)
- raw_bytes = decompress_blob(file_bytes, comp, filename=filename)
- self.uncompressed_size = len(raw_bytes)
- fdt = _open_fdt(raw_bytes, filename)
- else:
- self.uncompressed_size = (
- fdt.totalsize() if uncompressed_size is None
- else uncompressed_size
- )
- self.compressed_size = (
- self.uncompressed_size if compressed_size is None
- else compressed_size
- )
+ self.uncompressed_size = (
+ fdt.totalsize() if uncompressed_size is None else uncompressed_size
+ )
+ self.compressed_size = (
+ self.uncompressed_size if compressed_size is None
+ else compressed_size
+ )
self.boot_cpuid_phys = fdt.boot_cpuid_phys()
self.mem_rsv = tuple(fdt.get_mem_rsv_list())
@@ -1081,7 +1097,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 +1128,18 @@ 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],
+ )
+
+ 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):
@@ -1120,8 +1147,8 @@ def _extract_fit_fdt_entries(fit_in_path, images_node, configs_node):
parsed_dtb = ParsedDtb(
node_label,
+ fdt,
comp=comp,
- fdt=fdt,
root=root,
uncompressed_size=len(raw_bytes),
compressed_size=len(raw_data),
@@ -1201,6 +1228,7 @@ def _strip_fit_unfactored_local_fixups(unfactored_entries):
unfactored_entries: List of single-board FIT `flat_dt` entry dicts left
unfactored by `_partition_fit_fdt_entries()`.
"""
+ to_recompress = []
for entry in unfactored_entries:
fdt = entry.pop('fdt')
tree = libpydt.DeviceTree.unflatten(fdt)
@@ -1210,12 +1238,19 @@ 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],
+ )
+ 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)
@@ -1241,9 +1276,19 @@ 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)
+ ),
+ ],
)
+ 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 +1317,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:
@@ -1668,7 +1710,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,
+ _open_fdt(raw, p),
+ comp=comp,
+ 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 +1765,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)
--
2.56.1.987.g2ec0ab4260-goog
prev parent reply other threads:[~2026-12-04 15:38 UTC|newest]
Thread overview: 9+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-04 15:36 [PATCH v5 0/8] fdtfactor: Introduce fdtfactor to auto-factor overlays Douglas Anderson
2026-12-04 15:36 ` [PATCH v5 1/8] libfdt: Check NUL byte before memcmp() in fdt_find_string_len_() Douglas Anderson
2026-12-04 15:36 ` [PATCH v5 2/8] libpydt: Add DeviceTree live tree representation Douglas Anderson
2026-12-04 15:36 ` [PATCH v5 3/8] libfdt: overlay: Update base /__local_fixups__ on apply Douglas Anderson
2026-12-04 15:36 ` [PATCH v5 4/8] fdtfactor: Add tool to split DTBs into a base DTB and overlays Douglas Anderson
2026-12-04 15:36 ` [PATCH v5 5/8] fdtfactor: Add -S/--strip-local-fixups option Douglas Anderson
2026-12-04 15:36 ` [PATCH v5 6/8] fdtfactor: Support compressed DTB inputs and outputs Douglas Anderson
2026-12-04 15:36 ` [PATCH v5 7/8] fdtfactor: Add compiled FIT factoring support Douglas Anderson
2026-12-04 15:36 ` Douglas Anderson [this message]
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261204153756.1926794-9-dianders@chromium.org \
--to=dianders@chromium.org \
--cc=Devicetree-compiler@vger.kernel.org \
--cc=Devicetree@vger.kernel.org \
--cc=andre.draszik@linaro.org \
--cc=briannorris@chromium.org \
--cc=conor+dt@kernel.org \
--cc=david.laight.linux@gmail.com \
--cc=david@gibson.dropbear.id.au \
--cc=jwerner@chromium.org \
--cc=konradybcio@kernel.org \
--cc=krzk+dt@kernel.org \
--cc=linux-kernel@vger.kernel.org \
--cc=peter.griffin@linaro.org \
--cc=robh@kernel.org \
--cc=saravanak@kernel.org \
--cc=sjg@chromium.org \
--cc=tudor.ambarus@linaro.org \
--cc=wenst@chromium.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox