Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.82.176 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796398726; b=N/O0Il/z7SST+OMT4myPb5Y2TtsmRZPlqPI9MzccdyQ7XSNkBV6aNwRkgE1sFSwq3LF5 j8p6EdChUjkKhL902IJDFT2tzKuE3D5H1oV9Wb4sA074nuIwREaLmM52mGbV/ddZ5R2f8 8HO/YLuOomL1gMA3QWhlwk4qRQfrtUskiqaYNnQltcUZvnXwn/aI3by13YbZFll5du+H0 lRNq8h3e8iEsVAWdbZNUM44w4BAvQVEzs1iydn+D2HAwaykPrN2vFK8FuglG5213c084z Q2noH4HASvdZ5EnVJ3I8R80AjCPIvnD5TrezOxSuOfcTzFzsiuC8qYbpvUd/+bzAvcQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796398726; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Gm-Message-State:X-Gm-Gg:X-Received:Received:From:To:Cc:Subject: Date:Message-ID:X-Mailer:In-Reply-To:References:MIME-Version: Content-Type:Content-Transfer-Encoding; bh=Gq9t4vqotgFBmwqw1z/pgeGo/y3xT5yQO/EAWq0gy+k=; b=LIIJ5Y7LEqq+Pf0Dr/bVIwQbRdw7HZZBgaiUcpybbU9Og88Hxo14uOGURkikCirQo5Sq yn8clQV8vsqojag2fxUi5zYHvq7ihEYn8Hd4o/oKg2T3w2Yytx2vgWd+J9BByPeDfl1t/ kNT3FNgtay22ZIYbuytBvljfkbM0W9ix56hPbvZDKb9fWkeEA5nAs3ur0aR1Rfb6C4PeM Ke8HXnAvNDyfEQkL92mXcekFxAXGj203HZTUORBMJZJkeR8mvwlD2RJUZMRI1k9JoBOG0 HdnXeLcBd/uKBhI3YDUw19Lg9iilPsZOiWHiFEFFRbaQ1AIqqw7MiB6lOPuCGga/jZQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=chromium.org; spf=pass smtp.mailfrom=chromium.org; dkim=pass header.d=chromium.org header.i=@chromium.org header.a=rsa-sha256 header.s=google header.b=eewPHHXt; arc=none smtp.remote-ip=74.125.82.176 Received: from mail-dy1-f176.google.com (mail-dy1-f176.google.com [74.125.82.176]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id F02BF606A681 for ; Fri, 4 Dec 2026 15:38:45 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org F02BF606A681 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=chromium.org Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=chromium.org Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=chromium.org header.i=@chromium.org header.a=rsa-sha256 header.s=google header.b=eewPHHXt Received: by mail-dy1-f176.google.com with SMTP id 5a478bee46e88-386c71feeeaso1341925eec.0 for ; Fri, 04 Dec 2026 07:38:45 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=chromium.org; s=google; t=1796398725; x=1797003525; darn=vger.kernel.org; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:from:to:cc:subject :date:message-id:reply-to:content-type; bh=Gq9t4vqotgFBmwqw1z/pgeGo/y3xT5yQO/EAWq0gy+k=; b=eewPHHXtmFpnKuGa+181YzIZvLYIUKcaDlaJakLL2z16BDKLDXSUvzy5iQ11E5LUfc BvdoX1SKdx3JMVO7uSMwVn8t6wFm2Fksxg9FHBnQM7CEOYtxnncnBHJln81Vrl4FZcXO RNCDXLoyC21lKXR++YAwPypEdGjwZGRhyQkBE= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796398725; x=1797003525; h=content-transfer-encoding:content-type:mime-version:references :in-reply-to:message-id:date:subject:cc:to:from:x-gm-gg :x-gm-message-state:from:to:cc:subject:date:message-id:reply-to :content-type; bh=Gq9t4vqotgFBmwqw1z/pgeGo/y3xT5yQO/EAWq0gy+k=; b=DFHninBpUTiwjC8XKSXLgoORi4Utsd73l3ozXIKBuixzOaMYI7J/Q/8HlYJbPQEFt4 LHNYKhbpLPi04UxJ0e8I/O2kRcUulHFXtURnmlBLJdgTOJ6Mw0qFBlRJZnUM4Il63nSf aYlJyk3n/CTSVAWZtlNzSwsFM322A4e28qm/oujlTIM3jlOiec2MDTTkNAVZMUzQ5CLK 49Go0u7sKDYxP7bGjgCU3+VBmUfE31Xr9kK3AE8fm/w8lud03ow/6gy7OkdGETiur/s1 kTDUtQWvQr024n/0Obe0VXZ6qYD0q0Ql5fxirYYhvbjgNhWjgsXmdfntWNEZDwp5ytMV munw== X-Gm-Message-State: AB4q+uEU9cP2Ab4RfVNSApn9zLdIHfEeUKPabZl+NOcE8cn3ZIOiSqsz YG1s7O+/V7nx/WcNMg8CnwwhNzRl9ND6Uy03FJWml0OdYrv8mCFweXwruZ0n4AFMcxm7PAr5wFK k3Mw= X-Gm-Gg: AZFdTZcRe/7lSdQELo0+bGJUsOqYymc/cejqVvCF5h1pQmm4gm9lrsohKzSVgvDFgO0 4TWiOSKZNobDZTJtguYmUIAVwd/PABaOWUS4iPZxKIjP0KNljOCBz0TJd5G3aUvrDfiLX4NMXNs gnD9vpxSirh+bfV5l6WMhvrtSZp92wERRdcZ8IRhTo2sUl6jdtvlVwHKgBZfnQGHClErTU8rvoD mcqRtBpUYZRPjHi/vvii+DEjuD9cX4X29qqwuD/sz13NG7fSQDsvl+g90+0qltar7VIiycKj70g 5TE1bpIoOTz1X3dc7M0I9zOmBoeqAwCfjgZAX8TFEjrZrc7oWdiPJGdUvk0ToAytotrbGBuomw+ ZD8OeBaSjvlfSjF9NiMQePaQQrnsgLWkSVDsA+Oa3GuJm18Y2/ic6v3k8oGd9UYdtUp/kL1R54t RF+rFZNVVHvuGrerM+SSa3uKZuKTT4VpTtouTA2vm55Il6+YC5xM2v7tLKBRU5qOl2VVUp2XfAQ NhRjs6sZnUgQ+QfHNNVG4PN2VlWB1yzWdUrac3YzwQtZkPFHoIlMxNeRu5vSM2d/Er5TqPGvCk9 jbd4IIyQm9fQbtNcTngnwv+bdW3PqgVUUnW+nMhnV+9mRsXqrQBOatiMRkG/9+jfFEBK3/C6A6b Tvv+7NACRJDQi X-Received: by 2002:a05:7300:f797:b0:376:b957:c08 with SMTP id 5a478bee46e88-387521559d6mr2260146eec.9.1796398724895; Fri, 04 Dec 2026 07:38:44 -0800 (PST) Received: from dianders.sjc.corp.google.com ([2a00:79e0:2e7c:8:fba:375a:d40:ff68]) by smtp.gmail.com with ESMTPSA id 5a478bee46e88-3875218bd23sm9518875eec.8.2026.12.04.07.38.43 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 04 Dec 2026 07:38:44 -0800 (PST) From: Douglas Anderson To: Devicetree-compiler@vger.kernel.org, David Gibson , Simon Glass Cc: Conor Dooley , Devicetree@vger.kernel.org, Konrad Dybcio , Peter Griffin , Brian Norris , David Laight , Julius Werner , Krzysztof Kozlowski , =?UTF-8?q?Andr=C3=A9=20Draszik?= , Rob Herring , Saravana Kannan , Tudor Ambarus , Chen-Yu Tsai , linux-kernel@vger.kernel.org, Douglas Anderson Subject: [PATCH v5 8/8] fdtfactor: Parallelize blob compression and decompression Date: Fri, 4 Dec 2026 07:36:45 -0800 Message-ID: <20261204153756.1926794-9-dianders@chromium.org> X-Mailer: git-send-email 2.56.1.987.g2ec0ab4260-goog In-Reply-To: <20261204153756.1926794-1-dianders@chromium.org> References: <20261204153756.1926794-1-dianders@chromium.org> X-Mailing-List: devicetree-compiler@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- 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