source
large_stringclasses
2 values
subject
large_stringclasses
112 values
code
large_stringclasses
112 values
critique
large_stringlengths
61
3.04M
metadata
dict
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Add hardcoded dependencies and .incbin directive parsing to discover dependencies not tracked by .cmd files. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 24 +++++- .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++++++++++++++++++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++++++++++ tools/sbom/sbom/environment.py | 14 ++++ 4 files changed, 162 insertions(+), 1 deletion(-) create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/environment.py diff --git a/tools/sbom/sbom/cmd_graph/cmd_graph_node.py b/tools/sbom/sbom/cmd_graph/cmd_graph_node.py index fdaed0f0ccba..feacdbf76955 100644 --- a/tools/sbom/sbom/cmd_graph/cmd_graph_node.py +++ b/tools/sbom/sbom/cmd_graph/cmd_graph_node.py @@ -9,6 +9,8 @@ from typing import Iterator, Protocol from sbom import sbom_logging from sbom.cmd_graph.cmd_file import CmdFile +from sbom.cmd_graph.hardcoded_dependencies import get_hardcoded_dependencies +from sbom.cmd_graph.incbin_parser import parse_incbin_statements from sbom.path_utils import PathStr, is_relative_to @@ -104,14 +106,34 @@ class CmdGraphNode: ) return node + # Search for dependencies to add to the graph as child nodes. Child paths are always relative to the output tree. + def _build_child_node(child_path: PathStr) -> "CmdGraphNode": + return CmdGraphNode.create(child_path, config, cache, depth + 1) + + node.hardcoded_dependencies = [ + _build_child_node(hardcoded_dependency_path) + for hardcoded_dependency_path in get_hardcoded_dependencies( + target_path_absolute, config.obj_tree, config.src_tree + ) + ] + if cmd_file is not None: node.cmd_file_dependencies = [ - CmdGraphNode.create(cmd_file_dependency_path, config, cache, depth + 1) + _build_child_node(cmd_file_dependency_path) for cmd_file_dependency_path in cmd_file.get_dependencies( target_path, config.obj_tree, config.fail_on_unknown_build_command ) ] + if node.absolute_path.endswith(".S"): + node.incbin_dependencies = [ + IncbinDependency( + node=_build_child_node(incbin_statement.path), + full_statement=incbin_statement.full_statement, + ) + for incbin_statement in parse_incbin_statements(node.absolute_path) + ] + return node diff --git a/tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py b/tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py new file mode 100644 index 000000000000..a5977f14ae49 --- /dev/null +++ b/tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py @@ -0,0 +1,83 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import os +from typing import Callable +import sbom.sbom_logging as sbom_logging +from sbom.path_utils import PathStr, is_relative_to +from sbom.environment import Environment + +HARDCODED_DEPENDENCIES: dict[str, list[str]] = { + # defined in linux/Kbuild + "include/generated/rq-offsets.h": ["kernel/sched/rq-offsets.s"], + "kernel/sched/rq-offsets.s": ["include/generated/asm-offsets.h"], + "include/generated/bounds.h": ["kernel/bounds.s"], + "include/generated/asm-offsets.h": ["arch/{arch}/kernel/asm-offsets.s"], +} + + +def get_hardcoded_dependencies(path: PathStr, obj_tree: PathStr, src_tree: PathStr) -> list[PathStr]: + """ + Some files in the kernel build process are not tracked by the .cmd dependency mechanism. + Parsing these dependencies programmatically is too complex for the scope of this project. + Therefore, this function provides manually defined dependencies to be added to the build graph. + + Args: + path: absolute path to a file within the src tree or object tree. + obj_tree: absolute Path to the base directory of the object tree. + src_tree: absolute Path to the `linux` source directory. + + Returns: + list[PathStr]: A list of dependency file paths (relative to the object tree) required to build the file at the given path. + """ + if is_relative_to(path, obj_tree): + path = os.path.relpath(path, obj_tree) + elif is_relative_to(path, src_tree): + path = os.path.relpath(path, src_tree) + + if path not in HARDCODED_DEPENDENCIES: + return [] + + template_variables: dict[str, Callable[[], str | None]] = { + "arch": lambda: _get_arch(path), + } + + dependencies: list[PathStr] = [] + for dependency_template in HARDCODED_DEPENDENCIES[path]: + dependency = _evaluate_template(dependency_template, template_variables) + if dependency is None: + continue + if os.path.exists(os.path.join(obj_tree, dependency)): + dependencies.append(dependency) + elif os.path.exists(os.path.join(src_tree, dependency)): + dependencies.append(os.path.relpath(dependency, obj_tree)) + else: + sbom_logging.error( + "Skip hardcoded dependency '{dependency}' for '{path}' because the dependency lies neither in the src tree nor the object tree.", + dependency=dependency, + path=path, + ) + + return dependencies + + +def _evaluate_template(template: str, variables: dict[str, Callable[[], str | None]]) -> str | None: + for key, value_function in variables.items(): + template_key = "{" + key + "}" + if template_key in template: + value = value_function() + if value is None: + return None + template = template.replace(template_key, value) + return template + + +def _get_arch(path: PathStr): + srcarch = Environment.SRCARCH() + if srcarch is None: + sbom_logging.error( + "Skipped architecture specific hardcoded dependency for '{path}' because the SRCARCH environment variable was not set.", + path=path, + ) + return None + return srcarch diff --git a/tools/sbom/sbom/cmd_graph/incbin_parser.py b/tools/sbom/sbom/cmd_graph/incbin_parser.py new file mode 100644 index 000000000000..130f9520837d --- /dev/null +++ b/tools/sbom/sbom/cmd_graph/incbin_parser.py @@ -0,0 +1,42 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass +import re + +from sbom.path_utils import PathStr + +INCBIN_PATTERN = re.compile(r'\s*\.incbin\s+"(?P<path>[^"]+)"') +"""Regex pattern for matching `.incbin "<path>"` statements.""" + + +@dataclass +class IncbinStatement: + """A parsed `.incbin "<path>"` directive.""" + + path: PathStr + """path to the file referenced by the `.incbin` directive.""" + + full_statement: str + """Full `.incbin "<path>"` statement as it originally appeared in the file.""" + + +def parse_incbin_statements(absolute_path: PathStr) -> list[IncbinStatement]: + """ + Parses `.incbin` directives from an `.S` assembly file. + + Args: + absolute_path: Absolute path to the `.S` assembly file. + + Returns: + list[IncbinStatement]: Parsed `.incbin` statements. + """ + with open(absolute_path, "rt") as f: + content = f.read() + return [ + IncbinStatement( + path=match.group("path"), + full_statement=match.group(0).strip(), + ) + for match in INCBIN_PATTERN.finditer(content) + ] diff --git a/tools/sbom/sbom/environment.py b/tools/sbom/sbom/environment.py new file mode 100644 index 000000000000..b3fb2f0ba61d --- /dev/null +++ b/tools/sbom/sbom/environment.py @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import os + + +class Environment: + """ + Read-only accessor for kernel build environment variables. + """ + + @classmethod + def SRCARCH(cls) -> str | None: + return os.getenv("SRCARCH") -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:43 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Implement savedcmd_parser module for extracting input files from kernel build commands. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 +++++++++++++++++++ 1 file changed, 664 insertions(+) create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py diff --git a/tools/sbom/sbom/cmd_graph/savedcmd_parser.py b/tools/sbom/sbom/cmd_graph/savedcmd_parser.py new file mode 100644 index 000000000000..d72f781b4498 --- /dev/null +++ b/tools/sbom/sbom/cmd_graph/savedcmd_parser.py @@ -0,0 +1,664 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import re +import shlex +from dataclasses import dataclass +from typing import Any, Callable, Union +import sbom.sbom_logging as sbom_logging +from sbom.path_utils import PathStr + + +class CmdParsingError(Exception): + def __init__(self, message: str): + super().__init__(message) + self.message = message + + +@dataclass +class Option: + name: str + value: str | None = None + + +@dataclass +class Positional: + value: str + + +_SUBCOMMAND_PATTERN = re.compile(r"\$\$\(([^()]*)\)") +"""Pattern to match $$(...) blocks""" + + +def _tokenize_single_command(command: str, flag_options: list[str] | None = None) -> list[Union[Option, Positional]]: + """ + Parse a shell command into a list of Options and Positionals. + - Positional: the command and any positional arguments. + - Options: handles flags and options with values provided as space-separated, or equals-sign + (e.g., '--opt val', '--opt=val', '--flag'). + + Args: + command: Command line string. + flag_options: Options that are flags without values (e.g., '--verbose'). + + Returns: + List of `Option` and `Positional` objects in command order. + """ + + # Wrap all $$(...) blocks in double quotes to prevent shlex from splitting them. + command_with_protected_subcommands = _SUBCOMMAND_PATTERN.sub(lambda m: f'"$$({m.group(1)})"', command) + tokens = shlex.split(command_with_protected_subcommands) + + parsed: list[Option | Positional] = [] + i = 0 + while i < len(tokens): + token = tokens[i] + + # Positional + if not token.startswith("-"): + parsed.append(Positional(token)) + i += 1 + continue + + # Option without value (--flag) + if (token.startswith("-") and i + 1 < len(tokens) and tokens[i + 1].startswith("-")) or ( + flag_options and token in flag_options + ): + parsed.append(Option(name=token)) + i += 1 + continue + + # Option with equals sign (--opt=val) + if "=" in token: + name, value = token.split("=", 1) + parsed.append(Option(name=name, value=value)) + i += 1 + continue + + # Option with space-separated value (--opt val) + if i + 1 < len(tokens) and not tokens[i + 1].startswith("-"): + parsed.append(Option(name=token, value=tokens[i + 1])) + i += 2 + continue + + raise CmdParsingError(f"Unrecognized token: {token} in command {command}") + + return parsed + + +def _tokenize_single_command_positionals_only(command: str) -> list[str]: + command_parts = _tokenize_single_command(command) + positionals = [p.value for p in command_parts if isinstance(p, Positional)] + if len(positionals) != len(command_parts): + raise CmdParsingError( + f"Invalid command format: expected positional arguments only but got options in command {command}." + ) + return positionals + + +def _parse_dd_command(command: str) -> list[PathStr]: + match = re.match(r"dd.*?if=(\S+)", command) + if match: + return [match.group(1)] + return [] + + +def _parse_cat_command(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command) + # expect positionals to be ["cat", input1, input2, ...] + return [p for p in positionals[1:]] + + +def _parse_compound_command(command: str) -> list[PathStr]: + compound_command_parsers: list[tuple[re.Pattern[str], Callable[[str], list[PathStr]]]] = [ + (re.compile(r"dd\b"), _parse_dd_command), + (re.compile(r"cat.*?\|"), lambda c: _parse_cat_command(c.split("|")[0])), + (re.compile(r"cat\b[^|>]*$"), _parse_cat_command), + (re.compile(r"echo\b"), _parse_noop), + (re.compile(r"\S+="), _parse_noop), + (re.compile(r"printf\b"), _parse_noop), + (re.compile(r"sed\b"), _parse_sed_command), + ( + re.compile(r"(.*/)scripts/bin2c\s*<"), + lambda c: [input] if (input := c.split("<")[1].strip()) != "/dev/null" else [], + ), + (re.compile(r"^:$"), _parse_noop), + ] + + match = re.match(r"\s*[\(\{](.*)[\)\}]\s*>", command, re.DOTALL) + if match is None: + raise CmdParsingError("No inner commands found for compound command") + input_files: list[PathStr] = [] + inner_commands = _split_commands(match.group(1)) + for inner_command in inner_commands: + if isinstance(inner_command, IfBlock): + sbom_logging.error( + "Skip parsing inner command {inner_command} of compound command because IfBlock is not supported", + inner_command=inner_command, + ) + continue + + parser = next((parser for pattern, parser in compound_command_parsers if pattern.match(inner_command)), None) + if parser is None: + sbom_logging.error( + "Skip parsing inner command {inner_command} of compound command because no matching parser was found", + inner_command=inner_command, + ) + continue + try: + input_files += parser(inner_command) + except CmdParsingError as e: + sbom_logging.error( + "Skip parsing inner command {inner_command} of compound command because of command parsing error: {error_message}", + inner_command=inner_command, + error_message=e.message, + ) + return input_files + + +def _parse_objcopy_command(command: str) -> list[PathStr]: + command_parts = _tokenize_single_command(command, flag_options=["-S", "-w"]) + positionals = [part.value for part in command_parts if isinstance(part, Positional)] + # expect positionals to be ['objcopy', input_file] or ['objcopy', input_file, output_file] + if not (len(positionals) == 2 or len(positionals) == 3): + raise CmdParsingError( + f"Invalid objcopy command format: expected 2 or 3 positional arguments, got {len(positionals)} ({positionals})" + ) + return [positionals[1]] + + +def _parse_link_vmlinux_command(command: str) -> list[PathStr]: + """ + For simplicity we do not parse the `scripts/link-vmlinux.sh` script. + Instead the `vmlinux.a` dependency is just hardcoded for now. + """ + return ["vmlinux.a"] + + +def _parse_noop(command: str) -> list[PathStr]: + """ + No-op parser for commands with no input files (e.g., 'rm', 'true'). + Returns an empty list. + """ + return [] + + +def _parse_ar_command(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command) + # expect positionals to be ['ar', flags, output, input1, input2, ...] + flags = positionals[1] + if "r" not in flags: + # 'r' option indicates that new files are added to the archive. + # If this option is missing we won't find any relevant input files. + return [] + return positionals[3:] + + +def _parse_ar_piped_xargs_command(command: str) -> list[PathStr]: + printf_command, _ = command.split("|", 1) + positionals = _tokenize_single_command_positionals_only(printf_command.strip()) + # expect positionals to be ['printf', '{prefix_path}%s ', input1, input2, ...] + prefix_path = positionals[1].rstrip("%s ") + return [f"{prefix_path}{filename}" for filename in positionals[2:]] + + +def _parse_gcc_or_clang_command(command: str) -> list[PathStr]: + parts = shlex.split(command) + # compile mode: expect last positional argument ending in `.c` or `.S` to be the input file + for part in reversed(parts): + if not part.startswith("-") and any(part.endswith(suffix) for suffix in [".c", ".S"]): + return [part] + + # linking mode: expect all .o files to be the inputs + return [p for p in parts if p.endswith(".o")] + + +def _parse_rustc_command(command: str) -> list[PathStr]: + parts = shlex.split(command) + # expect last positional argument ending in `.rs` to be the input file + for part in reversed(parts): + if not part.startswith("-") and part.endswith(".rs"): + return [part] + raise CmdParsingError("Could not find .rs input source file") + + +def _parse_rustdoc_command(command: str) -> list[PathStr]: + parts = shlex.split(command) + # expect last positional argument ending in `.rs` to be the input file + for part in reversed(parts): + if not part.startswith("-") and part.endswith(".rs"): + return [part] + raise CmdParsingError("Could not find .rs input source file") + + +def _parse_syscallhdr_command(command: str) -> list[PathStr]: + command_parts = _tokenize_single_command(command.strip(), flag_options=["--emit-nr"]) + positionals = [p.value for p in command_parts if isinstance(p, Positional)] + # expect positionals to be ["sh", path/to/syscallhdr.sh, input, output] + return [positionals[2]] + + +def _parse_syscalltbl_command(command: str) -> list[PathStr]: + command_parts = _tokenize_single_command(command.strip()) + positionals = [p.value for p in command_parts if isinstance(p, Positional)] + # expect positionals to be ["sh", path/to/syscalltbl.sh, input, output] + return [positionals[2]] + + +def _parse_mkcapflags_command(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command) + # expect positionals to be ["sh", path/to/mkcapflags.sh, output, input1, input2] + return [positionals[3], positionals[4]] + + +def _parse_orc_hash_command(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command) + # expect positionals to be ["sh", path/to/orc_hash.sh, '<', input, '>', output] + return [positionals[3]] + + +def _parse_xen_hypercalls_command(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command) + # expect positionals to be ["sh", path/to/xen-hypercalls.sh, output, input1, input2, ...] + return positionals[3:] + + +def _parse_gen_initramfs_command(command: str) -> list[PathStr]: + command_parts = _tokenize_single_command(command) + positionals = [p.value for p in command_parts if isinstance(p, Positional)] + # expect positionals to be ["sh", path/to/gen_initramfs.sh, input1, input2, ...] + return positionals[2:] + + +def _parse_vdso2c_command(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command) + # expect positionals to be ['vdso2c', raw_input, stripped_input, output] + return [positionals[1], positionals[2]] + + +def _parse_ld_command(command: str) -> list[PathStr]: + command_parts = _tokenize_single_command( + command=command.strip(), + flag_options=[ + "-shared", + "--no-undefined", + "--eh-frame-hdr", + "-Bsymbolic", + "-r", + "--no-ld-generated-unwind-info", + "--no-dynamic-linker", + "-pie", + "--no-dynamic-linker--whole-archive", + "--whole-archive", + "--no-whole-archive", + "--start-group", + "--end-group", + ], + ) + positionals = [p.value for p in command_parts if isinstance(p, Positional)] + # expect positionals to be ["ld", input1, input2, ...] + return positionals[1:] + + +def _parse_sed_command(command: str) -> list[PathStr]: + command_parts = shlex.split(command) + # expect command parts to be ["sed", *, input] + input = command_parts[-1] + if input == "/dev/null": + return [] + return [input] + + +def _parse_awk(command: str) -> list[PathStr]: + command_parts = _tokenize_single_command(command) + positionals = [p.value for p in command_parts if isinstance(p, Positional)] + # expect positionals to be ["awk", input1, input2, ...] + return positionals[1:] + + +def _parse_nm_piped_command(command: str) -> list[PathStr]: + nm_command, _ = command.split("|", 1) + command_parts = _tokenize_single_command( + command=nm_command.strip(), + flag_options=["p", "--defined-only"], + ) + positionals = [p.value for p in command_parts if isinstance(p, Positional)] + # expect positionals to be ["nm", input1, input2, ...] + return [p for p in positionals[1:]] + + +def _parse_pnm_to_logo_command(command: str) -> list[PathStr]: + command_parts = shlex.split(command) + # expect command parts to be ["pnmtologo", <options>, input] + return [command_parts[-1]] + + +def _parse_relacheck(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command) + # expect positionals to be ["relachek", input, log_reference] + return [positionals[1]] + + +def _parse_perl_command(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command.strip()) + # expect positionals to be ["perl", input] + return [positionals[1]] + + +def _parse_strip_command(command: str) -> list[PathStr]: + command_parts = _tokenize_single_command(command, flag_options=["--strip-debug"]) + positionals = [p.value for p in command_parts if isinstance(p, Positional)] + # expect positionals to be ["strip", input1, input2, ...] + return positionals[1:] + + +def _parse_mkpiggy_command(command: str) -> list[PathStr]: + mkpiggy_command, _ = command.split(">", 1) + positionals = _tokenize_single_command_positionals_only(mkpiggy_command) + # expect positionals to be ["mkpiggy", input] + return [positionals[1]] + + +def _parse_relocs_command(command: str) -> list[PathStr]: + if ">" not in command: + # Only consider relocs commands that redirect output to a file. + # If there's no redirection, we assume it produces no output file and therefore has no input we care about. + return [] + relocs_command, _ = command.split(">", 1) + command_parts = shlex.split(relocs_command) + # expect command_parts to be ["relocs", options, input] + return [command_parts[-1]] + + +def _parse_mk_elfconfig_command(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command) + # expect positionals to be ["mk_elfconfig", "<", input, ">", output] + return [positionals[2]] + + +def _parse_flex_command(command: str) -> list[PathStr]: + parts = shlex.split(command) + # expect last positional argument ending in `.l` to be the input file + for part in reversed(parts): + if not part.startswith("-") and part.endswith(".l"): + return [part] + raise CmdParsingError("Could not find .l input source file in command") + + +def _parse_bison_command(command: str) -> list[PathStr]: + parts = shlex.split(command) + # expect last positional argument ending in `.y` to be the input file + for part in reversed(parts): + if not part.startswith("-") and part.endswith(".y"): + return [part] + raise CmdParsingError("Could not find input .y input source file in command") + + +def _parse_tools_build_command(command: str) -> list[PathStr]: + positionals = _tokenize_single_command_positionals_only(command) + # expect positionals to be ["tools/build", "input1", "input2", "input3", "output"] + return positionals[1:-1] + + +def _parse_extract_cert_command(command: str) -> list[PathStr]: + command_parts = shlex.split(command) + # expect command parts to be [path/to/extract-cert, input, output] + input = command_parts[1] + if not input: + return [] + return [input] + + +def _parse_dtc_command(command: str) -> list[PathStr]: + wno_flags = [command_part for command_part in shlex.split(command) if command_part.startswith("-Wno-")] + command_parts = _tokenize_single_command(command, flag_options=wno_flags) + positionals = [p.value for p in command_parts if isinstance(p, Positional)] + # expect positionals to be [path/to/dtc, input] + return [positionals[1]] + + +def _parse_bindgen_command(command: str) -> list[PathStr]: + command_parts = shlex.split(command) + header_file_input_paths = [part for part in command_parts if part.endswith(".h")] + return header_file_input_paths + + +def _parse_gen_header(command: str) -> list[PathStr]: + command_parts = shlex.split(command) + # expect command parts to be ["python3", path/to/gen_headers.py, ..., "--xml", input] + i = next(i for i, token in enumerate(command_parts) if token == "--xml") + return [command_parts[i + 1]] + + +# Command parser registry +SINGLE_COMMAND_PARSERS: list[tuple[re.Pattern[str], Callable[[str], list[PathStr]]]] = [ + # Compound commands + (re.compile(r"\(.*?\)\s*>", re.DOTALL), _parse_compound_command), + (re.compile(r"\{.*?\}\s*>", re.DOTALL), _parse_compound_command), + # Standard Unix utilities and system tools + (re.compile(r"^rm\b"), _parse_noop), + (re.compile(r"^mkdir\b"), _parse_noop), + (re.compile(r"^touch\b"), _parse_noop), + (re.compile(r"^cat\b.*?[\|>]"), lambda c: _parse_cat_command(c.split("|")[0].split(">")[0])), + (re.compile(r"^echo[^|]*$"), _parse_noop), + (re.compile(r"^sed.*?>"), lambda c: _parse_sed_command(c.split(">")[0])), + (re.compile(r"^sed\b"), _parse_noop), + (re.compile(r"^awk.*?<.*?>"), lambda c: [c.split("<")[1].split(">")[0]]), + (re.compile(r"^awk.*?>"), lambda c: _parse_awk(c.split(">")[0])), + (re.compile(r"^(/bin/)?true\b"), _parse_noop), + (re.compile(r"^(/bin/)?false\b"), _parse_noop), + (re.compile(r"^openssl\s+req.*?-new.*?-keyout"), _parse_noop), + # Compilers and code generators + # (C/LLVM toolchain, Rust, Flex/Bison, Bindgen, Perl, etc.) + (re.compile(r"^([^\s]+-)?(gcc|clang)\b"), _parse_gcc_or_clang_command), + (re.compile(r"^([^\s]+-)?ld(\.bfd)?\b"), _parse_ld_command), + (re.compile(r"^printf\b.*\| xargs ([^\s]+-)?ar\b"), _parse_ar_piped_xargs_command), + (re.compile(r"^([^\s]+-)?ar\b"), _parse_ar_command), + (re.compile(r"^([^\s]+-)?nm\b.*?\|"), _parse_nm_piped_command), + (re.compile(r"^([^\s]+-)?objcopy\b"), _parse_objcopy_command), + (re.compile(r"^([^\s]+-)?strip\b"), _parse_strip_command), + (re.compile(r".*?rustc\b"), _parse_rustc_command), + (re.compile(r".*?rustdoc\b"), _parse_rustdoc_command), + (re.compile(r"^flex\b"), _parse_flex_command), + (re.compile(r"^bison\b"), _parse_bison_command), + (re.compile(r"^bindgen\b"), _parse_bindgen_command), + (re.compile(r"^perl\b"), _parse_perl_command), + # Kernel-specific build scripts and tools + (re.compile(r"^(.*/)?link-vmlinux\.sh\b"), _parse_link_vmlinux_command), + (re.compile(r"sh (.*/)?syscallhdr\.sh\b"), _parse_syscallhdr_command), + (re.compile(r"sh (.*/)?syscalltbl\.sh\b"), _parse_syscalltbl_command), + (re.compile(r"sh (.*/)?mkcapflags\.sh\b"), _parse_mkcapflags_command), + (re.compile(r"sh (.*/)?orc_hash\.sh\b"), _parse_orc_hash_command), + (re.compile(r"sh (.*/)?xen-hypercalls\.sh\b"), _parse_xen_hypercalls_command), + (re.compile(r"sh (.*/)?gen_initramfs\.sh\b"), _parse_gen_initramfs_command), + (re.compile(r"sh (.*/)?checkundef\.sh\b"), _parse_noop), + (re.compile(r"(.*/)?vdso2c\b"), _parse_vdso2c_command), + (re.compile(r"^(.*/)?mkpiggy.*?>"), _parse_mkpiggy_command), + (re.compile(r"^(.*/)?relocs\b"), _parse_relocs_command), + (re.compile(r"^(.*/)?mk_elfconfig.*?<.*?>"), _parse_mk_elfconfig_command), + (re.compile(r"^(.*/)?tools/build\b"), _parse_tools_build_command), + (re.compile(r"^(.*/)?certs/extract-cert"), _parse_extract_cert_command), + (re.compile(r"^(.*/)?scripts/dtc/dtc\b"), _parse_dtc_command), + (re.compile(r"^(.*/)?pnmtologo\b"), _parse_pnm_to_logo_command), + (re.compile(r"^(.*/)?kernel/pi/relacheck"), _parse_relacheck), + (re.compile(r"^drivers/gpu/drm/radeon/mkregtable"), lambda c: [c.split(" ")[1]]), + (re.compile(r"(.*/)?genheaders\b"), _parse_noop), + (re.compile(r"^(.*/)?mkcpustr\s+>"), _parse_noop), + (re.compile(r"^(.*/)polgen\b"), _parse_noop), + (re.compile(r"make -f .*/arch/x86/Makefile\.postlink"), _parse_noop), + (re.compile(r"^(.*/)?raid6/mktables\s+>"), _parse_noop), + (re.compile(r"^(.*/)?objtool\b"), _parse_noop), + (re.compile(r"^(.*/)?module/gen_test_kallsyms.sh"), _parse_noop), + (re.compile(r"^(.*/)?gen_header.py"), _parse_gen_header), + (re.compile(r"^(.*/)?scripts/rustdoc_test_gen"), _parse_noop), +] + + +# If Block pattern to match a simple, single-level if-then-fi block. Nested If blocks are not supported. +IF_BLOCK_PATTERN = re.compile( + r""" + ^if(.*?);\s* # Match 'if <condition>;' (non-greedy) + then(.*?);\s* # Match 'then <body>;' (non-greedy) + fi\b # Match 'fi' + """, + re.VERBOSE, +) + + +@dataclass +class IfBlock: + condition: str + then_statement: str + + +def _unwrap_outer_parentheses(s: str) -> str: + s = s.strip() + if not (s.startswith("(") and s.endswith(")")): + return s + + count = 0 + for i, char in enumerate(s): + if char == "(": + count += 1 + elif char == ")": + count -= 1 + # If count is 0 before the end, outer parentheses don't match + if count == 0 and i != len(s) - 1: + return s + + # outer parentheses do match, unwrap once + return _unwrap_outer_parentheses(s[1:-1]) + + +def _find_first_top_level_command_separator( + commands: str, separators: list[str] = [";", "&&"] +) -> tuple[int | None, int | None]: + in_single_quote = False + in_double_quote = False + in_curly_braces = 0 + in_braces = 0 + for i, char in enumerate(commands): + if char == "'" and not in_double_quote: + # Toggle single quote state (unless inside double quotes) + in_single_quote = not in_single_quote + elif char == '"' and not in_single_quote: + # Toggle double quote state (unless inside single quotes) + in_double_quote = not in_double_quote + + if in_single_quote or in_double_quote: + continue + + # Toggle braces state + if char == "{": + in_curly_braces += 1 + if char == "}": + in_curly_braces -= 1 + + if char == "(": + in_braces += 1 + if char == ")": + in_braces -= 1 + + if in_curly_braces > 0 or in_braces > 0: + continue + + # return found separator position and separator length + for separator in separators: + if commands[i : i + len(separator)] == separator: + return i, len(separator) + + return None, None + + +def _split_commands(commands: str) -> list[str | IfBlock]: + """ + Splits a string of command-line commands into individual parts. + + This function handles: + - Top-level command separators (e.g., `;` and `&&`) to split multiple commands. + - Conditional if-blocks, returning them as `IfBlock` instances. + - Preserves the order of commands and trims whitespace. + + Args: + commands (str): The raw command string. + + Returns: + list[str | IfBlock]: A list of single commands or `IfBlock` objects. + """ + single_commands: list[str | IfBlock] = [] + remaining_commands = _unwrap_outer_parentheses(commands) + while len(remaining_commands) > 0: + remaining_commands = remaining_commands.strip() + + # if block + matched_if = IF_BLOCK_PATTERN.match(remaining_commands) + if matched_if: + condition, then_statement = matched_if.groups() + single_commands.append(IfBlock(condition.strip(), then_statement.strip())) + full_matched = matched_if.group(0) + remaining_commands = remaining_commands.removeprefix(full_matched).lstrip("; \n") + continue + + # command until next separator + separator_position, separator_length = _find_first_top_level_command_separator(remaining_commands) + if separator_position is not None and separator_length is not None: + single_commands.append(remaining_commands[:separator_position].strip()) + remaining_commands = remaining_commands[separator_position + separator_length :].strip() + continue + + # single last command + single_commands.append(remaining_commands) + break + + return single_commands + + +def parse_inputs_from_commands(commands: str, fail_on_unknown_build_command: bool) -> list[PathStr]: + """ + Extract input files referenced in a set of command-line commands. + + Args: + commands (str): Command line expression to parse. + fail_on_unknown_build_command (bool): Whether to fail if an unknown build command is encountered. If False, errors are logged as warnings. + + Returns: + list[PathStr]: List of input file paths required by the commands. + """ + + def log_error_or_warning(message: str, /, **kwargs: Any) -> None: + if fail_on_unknown_build_command: + sbom_logging.error(message, **kwargs) + else: + sbom_logging.warning(message, **kwargs) + + input_files: list[PathStr] = [] + for single_command in _split_commands(commands): + if isinstance(single_command, IfBlock): + inputs = parse_inputs_from_commands(single_command.then_statement, fail_on_unknown_build_command) + if inputs: + log_error_or_warning( + "Skipped parsing command {then_statement} because input files in IfBlock 'then' statement are not supported", + then_statement=single_command.then_statement, + ) + continue + + matched_parser = next( + (parser for pattern, parser in SINGLE_COMMAND_PARSERS if pattern.match(single_command)), None + ) + if matched_parser is None: + log_error_or_warning( + "Skipped parsing command {single_command} because no matching parser was found", + single_command=single_command, + ) + continue + try: + inputs = matched_parser(single_command) + input_files.extend(inputs) + except CmdParsingError as e: + log_error_or_warning( + "Skipped parsing command {single_command} because of command parsing error: {error_message}", + single_command=single_command, + error_message=e.message, + ) + + return [input.strip().rstrip("/") for input in input_files] -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:41 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Implement command graph generation by parsing .cmd files to build a dependency graph. Add CmdGraph, CmdGraphNode, and .cmd file parsing. Supports generating a flat list of used source files via the --generate-used-files cli argument. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- tools/sbom/Makefile | 6 +- tools/sbom/sbom.py | 39 +++++ tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++++++++++++++++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++++++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 120 ++++++++++++++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 +++++++ tools/sbom/sbom/config.py | 147 ++++++++++++++++++- 8 files changed, 563 insertions(+), 3 deletions(-) create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py diff --git a/tools/sbom/Makefile b/tools/sbom/Makefile index 8be7f2f3e631..b4ef72b30960 100644 --- a/tools/sbom/Makefile +++ b/tools/sbom/Makefile @@ -28,7 +28,11 @@ $(SBOM_TARGETS) &: $(SBOM_DEPS) sed 's/\.o$$/.ko/' $(objtree)/modules.order >> $(SBOM_ROOTS_FILE); \ fi - @python3 sbom.py + @python3 sbom.py \ + --src-tree $(srctree) \ + --obj-tree $(objtree) \ + --roots-file $(SBOM_ROOTS_FILE) \ + --output-directory $(objtree) @rm $(SBOM_ROOTS_FILE) diff --git a/tools/sbom/sbom.py b/tools/sbom/sbom.py index c7f23d6eb300..25d912a282de 100644 --- a/tools/sbom/sbom.py +++ b/tools/sbom/sbom.py @@ -7,9 +7,13 @@ Compute software bill of materials in SPDX format describing a kernel build. """ import logging +import os import sys +import time import sbom.sbom_logging as sbom_logging from sbom.config import get_config +from sbom.path_utils import is_relative_to +from sbom.cmd_graph import CmdGraph def main(): @@ -22,6 +26,36 @@ def main(): format="[%(levelname)s] %(message)s", ) + # Build cmd graph + logging.debug("Start building cmd graph") + start_time = time.time() + cmd_graph = CmdGraph.create(config.root_paths, config) + logging.debug(f"Built cmd graph in {time.time() - start_time} seconds") + + # Save used files document + if config.generate_used_files: + if config.src_tree == config.obj_tree: + logging.info( + f"Extracting all files from the cmd graph to {(config.used_files_file_name,)} " + "instead of only source files because source files cannot be " + "reliably classified when the source and object trees are identical.", + ) + used_files = [os.path.relpath(node.absolute_path, config.src_tree) for node in cmd_graph] + logging.debug(f"Found {len(used_files)} files in cmd graph.") + else: + used_files = [ + os.path.relpath(node.absolute_path, config.src_tree) + for node in cmd_graph + if is_relative_to(node.absolute_path, config.src_tree) + and not is_relative_to(node.absolute_path, config.obj_tree) + ] + logging.debug(f"Found {len(used_files)} source files in cmd graph") + if not sbom_logging.has_errors() or config.write_output_on_error: + used_files_path = os.path.join(config.output_directory, config.used_files_file_name) + with open(used_files_path, "w", encoding="utf-8") as f: + f.write("\n".join(str(file_path) for file_path in used_files)) + logging.debug(f"Successfully saved {used_files_path}") + # Report collected warnings and errors in case of failure warning_summary = sbom_logging.summarize_warnings() error_summary = sbom_logging.summarize_errors() @@ -30,6 +64,11 @@ def main(): logging.warning(warning_summary) if error_summary: logging.error(error_summary) + if not config.write_output_on_error: + logging.info( + "Use --write-output-on-error to generate output documents even when errors occur. " + "Note that in this case the generated SPDX documents may be incomplete." + ) sys.exit(1) diff --git a/tools/sbom/sbom/cmd_graph/__init__.py b/tools/sbom/sbom/cmd_graph/__init__.py new file mode 100644 index 000000000000..9d661a5c3d93 --- /dev/null +++ b/tools/sbom/sbom/cmd_graph/__init__.py @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from .cmd_graph import CmdGraph +from .cmd_graph_node import CmdGraphNode, CmdGraphNodeConfig + +__all__ = ["CmdGraph", "CmdGraphNode", "CmdGraphNodeConfig"] diff --git a/tools/sbom/sbom/cmd_graph/cmd_file.py b/tools/sbom/sbom/cmd_graph/cmd_file.py new file mode 100644 index 000000000000..d85ef5de0c26 --- /dev/null +++ b/tools/sbom/sbom/cmd_graph/cmd_file.py @@ -0,0 +1,149 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import os +import re +from dataclasses import dataclass, field +from sbom.cmd_graph.deps_parser import parse_cmd_file_deps +from sbom.cmd_graph.savedcmd_parser import parse_inputs_from_commands +import sbom.sbom_logging as sbom_logging +from sbom.path_utils import PathStr + +SAVEDCMD_PATTERN = re.compile(r"^(saved)?cmd_.*?:=\s*(?P<full_command>.+)$") +SOURCE_PATTERN = re.compile(r"^source.*?:=\s*(?P<source_file>.+)$") + + +@dataclass +class CmdFile: + cmd_file_path: PathStr + savedcmd: str + source: PathStr | None = None + deps: list[str] = field(default_factory=list[str]) + make_rules: list[str] = field(default_factory=list[str]) + + @classmethod + def create(cls, cmd_file_path: PathStr) -> "CmdFile | None": + """ + Parses a .cmd file. + .cmd files are assumed to have one of the following structures: + 1. Full Cmd File + (saved)?cmd_<output> := <command> + source_<output> := <main_input> + deps_<output> := \ + <dependencies> + <output> := $(deps_<output>) + $(deps_<output>): + + 2. Command Only Cmd File + (saved)?cmd_<output> := <command> + + 3. Single Dependency Cmd File + (saved)?cmd_<output> := <command> + <output> := <dependency> + + Args: + cmd_file_path (Path): absolute Path to a .cmd file + + Returns: + cmd_file (CmdFile): Parsed cmd file. + """ + with open(cmd_file_path, "rt") as f: + lines = [line.strip() for line in f.readlines() if line.strip() != "" and not line.startswith("#")] + + # savedcmd + match = SAVEDCMD_PATTERN.match(lines[0]) + if match is None: + sbom_logging.error( + "Skip parsing '{cmd_file_path}' because no 'savedcmd_' command was found.", cmd_file_path=cmd_file_path + ) + return None + savedcmd = match.group("full_command") + + # Command Only Cmd File + if len(lines) == 1: + return CmdFile(cmd_file_path, savedcmd) + + # Single Dependency Cmd File + if len(lines) == 2: + dep = lines[1].split(":")[1].strip() + return CmdFile(cmd_file_path, savedcmd, deps=[dep]) + + # Full Cmd File + # source + line1 = SOURCE_PATTERN.match(lines[1]) + if line1 is None: + sbom_logging.error( + "Skip parsing '{cmd_file_path}' because no 'source_' entry was found.", cmd_file_path=cmd_file_path + ) + return CmdFile(cmd_file_path, savedcmd) + source = line1.group("source_file") + + # deps + deps: list[str] = [] + i = 3 # lines[2] includes the variable assignment but no actual dependency, so we need to start at lines[3]. + while i < len(lines): + if not lines[i].endswith("\\"): + break + deps.append(lines[i][:-1].strip()) + i += 1 + + # make_rules + make_rules = lines[i:] + + return CmdFile(cmd_file_path, savedcmd, source, deps, make_rules) + + def get_dependencies( + self: "CmdFile", target_path: PathStr, obj_tree: PathStr, fail_on_unknown_build_command: bool + ) -> list[PathStr]: + """ + Parses all dependencies required to build a target file from its cmd file. + + Args: + target_path: path to the target file relative to `obj_tree`. + obj_tree: absolute path to the object tree. + fail_on_unknown_build_command: Whether to fail if an unknown build command is encountered. + + Returns: + list[PathStr]: dependency file paths relative to `obj_tree`. + """ + input_files: list[PathStr] = [ + str(p) for p in parse_inputs_from_commands(self.savedcmd, fail_on_unknown_build_command) + ] + if self.deps: + input_files += [str(p) for p in parse_cmd_file_deps(self.deps)] + input_files = _expand_resolve_files(input_files, obj_tree) + + cmd_file_dependencies: list[PathStr] = [] + for input_file in input_files: + # input files are either absolute or relative to the object tree + if os.path.isabs(input_file): + input_file = os.path.relpath(input_file, obj_tree) + if input_file == target_path: + # Skip target file to prevent cycles. This is necessary because some multi stage commands first create an output and then pass it as input to the next command, e.g., objcopy. + continue + cmd_file_dependencies.append(input_file) + + return cmd_file_dependencies + + +def _expand_resolve_files(input_files: list[PathStr], obj_tree: PathStr) -> list[PathStr]: + """ + Expands resolve files which may reference additional files via '@' notation. + + Args: + input_files (list[PathStr]): List of file paths relative to the object tree, where paths starting with '@' refer to files + containing further file paths, each on a separate line. + obj_tree: Absolute path to the root of the object tree. + + Returns: + list[PathStr]: Flattened list of all input file paths, with any nested '@' file references resolved recursively. + """ + expanded_input_files: list[PathStr] = [] + for input_file in input_files: + if not input_file.startswith("@"): + expanded_input_files.append(input_file) + continue + with open(os.path.join(obj_tree, input_file.lstrip("@")), "rt") as f: + resolve_file_content = [line_stripped for line in f.readlines() if (line_stripped := line.strip())] + expanded_input_files += _expand_resolve_files(resolve_file_content, obj_tree) + return expanded_input_files diff --git a/tools/sbom/sbom/cmd_graph/cmd_graph.py b/tools/sbom/sbom/cmd_graph/cmd_graph.py new file mode 100644 index 000000000000..cad54243ff3f --- /dev/null +++ b/tools/sbom/sbom/cmd_graph/cmd_graph.py @@ -0,0 +1,46 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from collections import deque +from dataclasses import dataclass, field +from typing import Iterator + +from sbom.cmd_graph.cmd_graph_node import CmdGraphNode, CmdGraphNodeConfig +from sbom.path_utils import PathStr + + +@dataclass +class CmdGraph: + """Directed acyclic graph of build dependencies primarily inferred from .cmd files produced during kernel builds""" + + roots: list[CmdGraphNode] = field(default_factory=list[CmdGraphNode]) + + @classmethod + def create(cls, root_paths: list[PathStr], config: CmdGraphNodeConfig) -> "CmdGraph": + """ + Recursively builds a dependency graph starting from `root_paths`. + Dependencies are mainly discovered by parsing the `.cmd` files. + + Args: + root_paths (list[PathStr]): List of paths to root outputs relative to obj_tree + config (CmdGraphNodeConfig): Configuration options + + Returns: + CmdGraph: A graph of all build dependencies for the given root files. + """ + node_cache: dict[PathStr, CmdGraphNode] = {} + root_nodes = [CmdGraphNode.create(root_path, config, node_cache) for root_path in root_paths] + return CmdGraph(root_nodes) + + def __iter__(self) -> Iterator[CmdGraphNode]: + """Traverse the graph in breadth-first order, yielding each unique node.""" + visited: set[PathStr] = set() + node_stack: deque[CmdGraphNode] = deque(self.roots) + while len(node_stack) > 0: + node = node_stack.popleft() + if node.absolute_path in visited: + continue + + visited.add(node.absolute_path) + node_stack.extend(node.children) + yield node diff --git a/tools/sbom/sbom/cmd_graph/cmd_graph_node.py b/tools/sbom/sbom/cmd_graph/cmd_graph_node.py new file mode 100644 index 000000000000..fdaed0f0ccba --- /dev/null +++ b/tools/sbom/sbom/cmd_graph/cmd_graph_node.py @@ -0,0 +1,120 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass, field +from itertools import chain +import logging +import os +from typing import Iterator, Protocol + +from sbom import sbom_logging +from sbom.cmd_graph.cmd_file import CmdFile +from sbom.path_utils import PathStr, is_relative_to + + +@dataclass +class IncbinDependency: + node: "CmdGraphNode" + full_statement: str + + +class CmdGraphNodeConfig(Protocol): + obj_tree: PathStr + src_tree: PathStr + fail_on_unknown_build_command: bool + + +@dataclass +class CmdGraphNode: + """A node in the cmd graph representing a single file and its dependencies.""" + + absolute_path: PathStr + """Absolute path to the file this node represents.""" + + cmd_file: CmdFile | None = None + """Parsed .cmd file describing how the file at absolute_path was built, or None if not available.""" + + cmd_file_dependencies: list["CmdGraphNode"] = field(default_factory=list["CmdGraphNode"]) + incbin_dependencies: list[IncbinDependency] = field(default_factory=list[IncbinDependency]) + hardcoded_dependencies: list["CmdGraphNode"] = field(default_factory=list["CmdGraphNode"]) + + @property + def children(self) -> Iterator["CmdGraphNode"]: + seen: set[PathStr] = set() + for node in chain( + self.cmd_file_dependencies, + (dep.node for dep in self.incbin_dependencies), + self.hardcoded_dependencies, + ): + if node.absolute_path not in seen: + seen.add(node.absolute_path) + yield node + + @classmethod + def create( + cls, + target_path: PathStr, + config: CmdGraphNodeConfig, + cache: dict[PathStr, "CmdGraphNode"] | None = None, + depth: int = 0, + ) -> "CmdGraphNode": + """ + Recursively builds a dependency graph starting from `target_path`. + Dependencies are mainly discovered by parsing the `.<target_path.name>.cmd` file. + + Args: + target_path: Path to the target file relative to obj_tree. + config: Config options + cache: Tracks processed nodes to prevent cycles. + depth: Internal parameter to track the current recursion depth. + + Returns: + CmdGraphNode: cmd graph node representing the target file + """ + if cache is None: + cache = {} + + target_path_absolute = ( + os.path.realpath(p) + if os.path.islink(p := os.path.join(config.obj_tree, target_path)) + else os.path.normpath(p) + ) + + if target_path_absolute in cache: + return cache[target_path_absolute] + + if depth == 0: + logging.debug(f"Build node: {target_path}") + + cmd_file_path = _to_cmd_path(target_path_absolute) + cmd_file = CmdFile.create(cmd_file_path) if os.path.exists(cmd_file_path) else None + node = CmdGraphNode(target_path_absolute, cmd_file) + cache[target_path_absolute] = node + + if not os.path.exists(target_path_absolute): + error_or_warning = ( + sbom_logging.error + if is_relative_to(target_path_absolute, config.obj_tree) + or is_relative_to(target_path_absolute, config.src_tree) + else sbom_logging.warning + ) + error_or_warning( + "Skip parsing '{target_path_absolute}' because file does not exist", + target_path_absolute=target_path_absolute, + ) + return node + + if cmd_file is not None: + node.cmd_file_dependencies = [ + CmdGraphNode.create(cmd_file_dependency_path, config, cache, depth + 1) + for cmd_file_dependency_path in cmd_file.get_dependencies( + target_path, config.obj_tree, config.fail_on_unknown_build_command + ) + ] + + return node + + +def _to_cmd_path(path: PathStr) -> PathStr: + name = os.path.basename(path) + return path.removesuffix(name) + f".{name}.cmd" diff --git a/tools/sbom/sbom/cmd_graph/deps_parser.py b/tools/sbom/sbom/cmd_graph/deps_parser.py new file mode 100644 index 000000000000..fb3ccdd415b5 --- /dev/null +++ b/tools/sbom/sbom/cmd_graph/deps_parser.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import re +import sbom.sbom_logging as sbom_logging +from sbom.path_utils import PathStr + +# Match dependencies on config files +# Example match: "$(wildcard include/config/CONFIG_SOMETHING)" +CONFIG_PATTERN = re.compile(r"\$\(wildcard (include/config/[^)]+)\)") + +# Match dependencies on the objtool binary +# Example match: "$(wildcard ./tools/objtool/objtool)" +OBJTOOL_PATTERN = re.compile(r"\$\(wildcard \./tools/objtool/objtool\)") + +# Match any Makefile wildcard reference +# Example match: "$(wildcard path/to/file)" +WILDCARD_PATTERN = re.compile(r"\$\(wildcard (?P<path>[^)]+)\)") + +# Match ordinary paths: +# - ^(\/)?: Optionally starts with a '/' +# - (([\w\-\., ]*)\/)*: Zero or more directory levels +# - [\w\-\., ]+$: Path component (file or directory) +# Example matches: "/foo/bar.c", "dir1/dir2/file.txt", "plainfile" +VALID_PATH_PATTERN = re.compile(r"^(\/)?(([\w\-\., ]*)\/)*[\w\-\., ]+$") + + +def parse_cmd_file_deps(deps: list[str]) -> list[PathStr]: + """ + Parse dependency strings of a .cmd file and return valid input file paths. + + Args: + deps: List of dependency strings as found in `.cmd` files. + + Returns: + input_files: List of input file paths + """ + input_files: list[PathStr] = [] + for dep in deps: + dep = dep.strip() + match dep: + case _ if CONFIG_PATTERN.match(dep) or OBJTOOL_PATTERN.match(dep): + # config paths like include/config/<CONFIG_NAME> should not be included in the graph + continue + case _ if match := WILDCARD_PATTERN.match(dep): + path = match.group("path") + input_files.append(path) + case _ if VALID_PATH_PATTERN.match(dep): + input_files.append(dep) + case _: + sbom_logging.error("Skip parsing dependency {dep} because of unrecognized format", dep=dep) + return input_files diff --git a/tools/sbom/sbom/config.py b/tools/sbom/sbom/config.py index 3dc569ae0c43..39e556a4c53b 100644 --- a/tools/sbom/sbom/config.py +++ b/tools/sbom/sbom/config.py @@ -3,15 +3,43 @@ import argparse from dataclasses import dataclass +import os +from typing import Any +from sbom.path_utils import PathStr @dataclass class KernelSbomConfig: + src_tree: PathStr + """Absolute path to the Linux kernel source directory.""" + + obj_tree: PathStr + """Absolute path to the build output directory.""" + + root_paths: list[PathStr] + """List of paths to root outputs (relative to obj_tree) to base the SBOM on.""" + + generate_used_files: bool + """Whether to generate a flat list of all source files used in the build. + If False, no used-files document is created.""" + + used_files_file_name: str + """If `generate_used_files` is True, specifies the file name for the used-files document.""" + + output_directory: PathStr + """Path to the directory where the generated output documents will be saved.""" + debug: bool """Whether to enable debug logging.""" + fail_on_unknown_build_command: bool + """Whether to fail if an unknown build command is encountered in a .cmd file.""" + + write_output_on_error: bool + """Whether to write output documents even if errors occur.""" + -def _parse_cli_arguments() -> dict[str, bool]: +def _parse_cli_arguments() -> dict[str, Any]: """ Parse command-line arguments using argparse. @@ -19,8 +47,49 @@ def _parse_cli_arguments() -> dict[str, bool]: Dictionary of parsed arguments. """ parser = argparse.ArgumentParser( + formatter_class=argparse.RawTextHelpFormatter, description="Generate SPDX SBOM documents for kernel builds", ) + parser.add_argument( + "--src-tree", + default="../linux", + help="Path to the kernel source tree (default: ../linux)", + ) + parser.add_argument( + "--obj-tree", + default="../linux/kernel_build", + help="Path to the build output directory (default: ../linux/kernel_build)", + ) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument( + "--roots", + nargs="+", + default="arch/x86/boot/bzImage", + help="Space-separated list of paths relative to obj-tree for which the SBOM will be created.\n" + "Cannot be used together with --roots-file. (default: arch/x86/boot/bzImage)", + ) + group.add_argument( + "--roots-file", + help="Path to a file containing the root paths (one per line). Cannot be used together with --roots.", + ) + parser.add_argument( + "--generate-used-files", + action="store_true", + default=False, + help=( + "Whether to create the sbom.used-files.txt file, a flat list of all " + "source files used for the kernel build.\n" + "If src-tree and obj-tree are equal it is not possible to reliably " + "classify source files.\n" + "In this case sbom.used-files.txt will contain all files used for the " + "kernel build including all build artifacts. (default: False)" + ), + ) + parser.add_argument( + "--output-directory", + default=".", + help="Path to the directory where the generated output documents will be stored (default: .)", + ) parser.add_argument( "--debug", action="store_true", @@ -28,6 +97,28 @@ def _parse_cli_arguments() -> dict[str, bool]: help="Enable debug logs (default: False)", ) + # Error handling settings + parser.add_argument( + "--do-not-fail-on-unknown-build-command", + action="store_true", + default=False, + help=( + "Whether to fail if an unknown build command is encountered in a .cmd file.\n" + "If set to True, errors are logged as warnings instead. (default: False)" + ), + ) + parser.add_argument( + "--write-output-on-error", + action="store_true", + default=False, + help=( + "Write output documents even if errors occur. The resulting documents " + "may be incomplete.\n" + "A summary of warnings and errors can be found in the 'comment' property " + "of the CreationInfo element. (default: False)" + ), + ) + args = vars(parser.parse_args()) return args @@ -42,6 +133,58 @@ def get_config() -> KernelSbomConfig: # Parse cli arguments args = _parse_cli_arguments() + # Extract and validate cli arguments + src_tree = os.path.realpath(args["src_tree"]) + obj_tree = os.path.realpath(args["obj_tree"]) + root_paths = [] + if args["roots_file"]: + with open(args["roots_file"], "rt") as f: + root_paths = [root.strip() for root in f.readlines()] + else: + root_paths = args["roots"] + _validate_path_arguments(src_tree, obj_tree, root_paths) + + generate_used_files = args["generate_used_files"] + output_directory = os.path.realpath(args["output_directory"]) debug = args["debug"] - return KernelSbomConfig(debug=debug) + fail_on_unknown_build_command = not args["do_not_fail_on_unknown_build_command"] + write_output_on_error = args["write_output_on_error"] + + # Hardcoded config + used_files_file_name = "sbom.used-files.txt" + + return KernelSbomConfig( + src_tree=src_tree, + obj_tree=obj_tree, + root_paths=root_paths, + generate_used_files=generate_used_files, + used_files_file_name=used_files_file_name, + output_directory=output_directory, + debug=debug, + fail_on_unknown_build_command=fail_on_unknown_build_command, + write_output_on_error=write_output_on_error, + ) + + +def _validate_path_arguments(src_tree: PathStr, obj_tree: PathStr, root_paths: list[PathStr]) -> None: + """ + Validate that the provided paths exist. + + Args: + src_tree: Absolute path to the source tree. + obj_tree: Absolute path to the object tree. + root_paths: List of root paths relative to obj_tree. + + Raises: + argparse.ArgumentTypeError: If any of the paths don't exist. + """ + if not os.path.exists(src_tree): + raise argparse.ArgumentTypeError(f"--src-tree {src_tree} does not exist") + if not os.path.exists(obj_tree): + raise argparse.ArgumentTypeError(f"--obj-tree {obj_tree} does not exist") + for root_path in root_paths: + if not os.path.exists(os.path.join(obj_tree, root_path)): + raise argparse.ArgumentTypeError( + f"path to root artifact {os.path.join(obj_tree, root_path)} does not exist" + ) -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:42 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Implement Python dataclasses to model the SPDX classes required within an SPDX document. The class and property names are consistent with the SPDX 3.0.1 specification. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 +++ tools/sbom/sbom/spdx/core.py | 182 ++++++++++++++++++++++++ tools/sbom/sbom/spdx/serialization.py | 56 ++++++++ tools/sbom/sbom/spdx/simplelicensing.py | 20 +++ tools/sbom/sbom/spdx/software.py | 71 +++++++++ tools/sbom/sbom/spdx/spdxId.py | 36 +++++ 7 files changed, 389 insertions(+) create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py diff --git a/tools/sbom/sbom/spdx/__init__.py b/tools/sbom/sbom/spdx/__init__.py new file mode 100644 index 000000000000..4097b59f8f17 --- /dev/null +++ b/tools/sbom/sbom/spdx/__init__.py @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from .spdxId import SpdxId, SpdxIdGenerator +from .serialization import JsonLdSpdxDocument + +__all__ = ["JsonLdSpdxDocument", "SpdxId", "SpdxIdGenerator"] diff --git a/tools/sbom/sbom/spdx/build.py b/tools/sbom/sbom/spdx/build.py new file mode 100644 index 000000000000..180a8f1e8bd3 --- /dev/null +++ b/tools/sbom/sbom/spdx/build.py @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass, field +from sbom.spdx.core import DictionaryEntry, Element, Hash + + +@dataclass(kw_only=True) +class Build(Element): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Build/Classes/Build/""" + + type: str = field(init=False, default="build_Build") + build_buildType: str + build_buildId: str + build_environment: list[DictionaryEntry] = field(default_factory=list[DictionaryEntry]) + build_configSourceUri: list[str] = field(default_factory=list[str]) + build_configSourceDigest: list[Hash] = field(default_factory=list[Hash]) diff --git a/tools/sbom/sbom/spdx/core.py b/tools/sbom/sbom/spdx/core.py new file mode 100644 index 000000000000..c5de9194bb89 --- /dev/null +++ b/tools/sbom/sbom/spdx/core.py @@ -0,0 +1,182 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Any, Literal +from sbom.spdx.spdxId import SpdxId + +SPDX_SPEC_VERSION = "3.0.1" + +ExternalIdentifierType = Literal["email", "gitoid", "urlScheme"] +HashAlgorithm = Literal["sha256", "sha512"] +ProfileIdentifierType = Literal["core", "software", "build", "lite", "simpleLicensing"] +RelationshipType = Literal[ + "contains", + "generates", + "hasDeclaredLicense", + "hasInput", + "hasOutput", + "ancestorOf", + "hasDistributionArtifact", + "dependsOn", +] +RelationshipCompleteness = Literal["complete", "incomplete", "noAssertion"] + + +@dataclass +class SpdxObject: + def to_dict(self) -> dict[str, Any]: + def _to_dict(v: Any): + return v.to_dict() if hasattr(v, "to_dict") else v + + d: dict[str, Any] = {} + for field_name in self.__dataclass_fields__: + value = getattr(self, field_name) + if not value: + continue + + if isinstance(value, Element): + d[field_name] = value.spdxId + elif isinstance(value, list) and len(value) > 0 and isinstance(value[0], Element): # type: ignore + value: list[Element] = value + d[field_name] = [v.spdxId for v in value] + else: + d[field_name] = [_to_dict(v) for v in value] if isinstance(value, list) else _to_dict(value) # type: ignore + return d + + +@dataclass(kw_only=True) +class IntegrityMethod(SpdxObject): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/IntegrityMethod/""" + + +@dataclass(kw_only=True) +class Hash(IntegrityMethod): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/Hash/""" + + type: str = field(init=False, default="Hash") + hashValue: str + algorithm: HashAlgorithm + + +@dataclass(kw_only=True) +class Element(SpdxObject): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/Element/""" + + type: str = field(init=False, default="Element") + spdxId: SpdxId + creationInfo: str = "_:creationinfo" + name: str | None = None + verifiedUsing: list[Hash] = field(default_factory=list[Hash]) + comment: str | None = None + + +@dataclass(kw_only=True) +class ExternalMap(SpdxObject): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/ExternalMap/""" + + type: str = field(init=False, default="ExternalMap") + externalSpdxId: SpdxId + + +@dataclass(kw_only=True) +class NamespaceMap(SpdxObject): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/NamespaceMap/""" + + type: str = field(init=False, default="NamespaceMap") + prefix: str + namespace: str + + +@dataclass(kw_only=True) +class ElementCollection(Element): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/ElementCollection/""" + + type: str = field(init=False, default="ElementCollection") + element: list[Element] = field(default_factory=list[Element]) + rootElement: list[Element] = field(default_factory=list[Element]) + profileConformance: list[ProfileIdentifierType] = field(default_factory=list[ProfileIdentifierType]) + + +@dataclass(kw_only=True) +class SpdxDocument(ElementCollection): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/SpdxDocument/""" + + type: str = field(init=False, default="SpdxDocument") + import_: list[ExternalMap] = field(default_factory=list[ExternalMap]) + namespaceMap: list[NamespaceMap] = field(default_factory=list[NamespaceMap]) + + def to_dict(self) -> dict[str, Any]: + return {("import" if k == "import_" else k): v for k, v in super().to_dict().items()} + + +@dataclass(kw_only=True) +class ExternalIdentifier(SpdxObject): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/ExternalIdentifier/""" + + type: str = field(init=False, default="ExternalIdentifier") + externalIdentifierType: ExternalIdentifierType + identifier: str + + +@dataclass(kw_only=True) +class Agent(Element): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/Agent/""" + + type: str = field(init=False, default="Agent") + externalIdentifier: list[ExternalIdentifier] = field(default_factory=list[ExternalIdentifier]) + + +@dataclass(kw_only=True) +class SoftwareAgent(Agent): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/SoftwareAgent/""" + + type: str = field(init=False, default="SoftwareAgent") + + +@dataclass(kw_only=True) +class CreationInfo(SpdxObject): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/CreationInfo/""" + + type: str = field(init=False, default="CreationInfo") + id: SpdxId = "_:creationinfo" + specVersion: str = SPDX_SPEC_VERSION + createdBy: list[Agent] + created: str = field(default_factory=lambda: datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")) + comment: str | None = None + + def to_dict(self) -> dict[str, Any]: + return {("@id" if k == "id" else k): v for k, v in super().to_dict().items()} + + +@dataclass(kw_only=True) +class Relationship(Element): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/Relationship/""" + + type: str = field(init=False, default="Relationship") + relationshipType: RelationshipType + from_: Element # underscore because 'from' is a reserved keyword + to: list[Element] + completeness: RelationshipCompleteness | None = None + + def to_dict(self) -> dict[str, Any]: + return {("from" if k == "from_" else k): v for k, v in super().to_dict().items()} + + +@dataclass(kw_only=True) +class Artifact(Element): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/Artifact/""" + + type: str = field(init=False, default="Artifact") + builtTime: str | None = None + originatedBy: list[Agent] = field(default_factory=list[Agent]) + + +@dataclass(kw_only=True) +class DictionaryEntry(SpdxObject): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Core/Classes/DictionaryEntry/""" + + type: str = field(init=False, default="DictionaryEntry") + key: str + value: str diff --git a/tools/sbom/sbom/spdx/serialization.py b/tools/sbom/sbom/spdx/serialization.py new file mode 100644 index 000000000000..c830d6b3cf19 --- /dev/null +++ b/tools/sbom/sbom/spdx/serialization.py @@ -0,0 +1,56 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import json +from typing import Any +from sbom.path_utils import PathStr +from sbom.spdx.core import SPDX_SPEC_VERSION, SpdxDocument, SpdxObject + + +class JsonLdSpdxDocument: + """Represents an SPDX document in JSON-LD format for serialization.""" + + context: list[str | dict[str, str]] + graph: list[SpdxObject] + + def __init__(self, graph: list[SpdxObject]) -> None: + """ + Initialize a JSON-LD SPDX document from a graph of SPDX objects. + The graph must contain a single SpdxDocument element. + + Args: + graph: List of SPDX objects representing the complete SPDX document. + """ + self.graph = graph + spdx_document = next(element for element in graph if isinstance(element, SpdxDocument)) + self.context = [ + f"https://spdx.org/rdf/{SPDX_SPEC_VERSION}/spdx-context.jsonld", + {namespaceMap.prefix: namespaceMap.namespace for namespaceMap in spdx_document.namespaceMap}, + ] + spdx_document.namespaceMap = [] + + def to_dict(self) -> dict[str, Any]: + """ + Convert the SPDX document to a dictionary representation suitable for JSON serialization. + + Returns: + Dictionary with @context and @graph keys following JSON-LD format. + """ + return { + "@context": self.context, + "@graph": [item.to_dict() for item in self.graph], + } + + def save(self, path: PathStr, prettify: bool) -> None: + """ + Save the SPDX document to a JSON file. + + Args: + path: File path where the document will be saved. + prettify: Whether to pretty-print the JSON with indentation. + """ + with open(path, "w", encoding="utf-8") as f: + if prettify: + json.dump(self.to_dict(), f, indent=2) + else: + json.dump(self.to_dict(), f, separators=(",", ":")) diff --git a/tools/sbom/sbom/spdx/simplelicensing.py b/tools/sbom/sbom/spdx/simplelicensing.py new file mode 100644 index 000000000000..750ddd24ad89 --- /dev/null +++ b/tools/sbom/sbom/spdx/simplelicensing.py @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass, field +from sbom.spdx.core import Element + + +@dataclass(kw_only=True) +class AnyLicenseInfo(Element): + """https://spdx.github.io/spdx-spec/v3.0.1/model/SimpleLicensing/Classes/AnyLicenseInfo/""" + + type: str = field(init=False, default="simplelicensing_AnyLicenseInfo") + + +@dataclass(kw_only=True) +class LicenseExpression(AnyLicenseInfo): + """https://spdx.github.io/spdx-spec/v3.0.1/model/SimpleLicensing/Classes/LicenseExpression/""" + + type: str = field(init=False, default="simplelicensing_LicenseExpression") + simplelicensing_licenseExpression: str diff --git a/tools/sbom/sbom/spdx/software.py b/tools/sbom/sbom/spdx/software.py new file mode 100644 index 000000000000..208e0168b939 --- /dev/null +++ b/tools/sbom/sbom/spdx/software.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass, field +from typing import Literal +from sbom.spdx.core import Artifact, ElementCollection, IntegrityMethod + + +SbomType = Literal["source", "build"] +FileKindType = Literal["file", "directory"] +SoftwarePurpose = Literal[ + "source", + "archive", + "library", + "file", + "data", + "configuration", + "executable", + "module", + "application", + "documentation", + "other", +] +ContentIdentifierType = Literal["gitoid", "swhid"] + + +@dataclass(kw_only=True) +class Sbom(ElementCollection): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Software/Classes/Sbom/""" + + type: str = field(init=False, default="software_Sbom") + software_sbomType: list[SbomType] = field(default_factory=list[SbomType]) + + +@dataclass(kw_only=True) +class ContentIdentifier(IntegrityMethod): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Software/Classes/ContentIdentifier/""" + + type: str = field(init=False, default="software_ContentIdentifier") + software_contentIdentifierType: ContentIdentifierType + software_contentIdentifierValue: str + + +@dataclass(kw_only=True) +class SoftwareArtifact(Artifact): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Software/Classes/SoftwareArtifact/""" + + type: str = field(init=False, default="software_Artifact") + software_primaryPurpose: SoftwarePurpose | None = None + software_additionalPurpose: list[SoftwarePurpose] = field(default_factory=list[SoftwarePurpose]) + software_copyrightText: str | None = None + software_contentIdentifier: list[ContentIdentifier] = field(default_factory=list[ContentIdentifier]) + + +@dataclass(kw_only=True) +class Package(SoftwareArtifact): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Software/Classes/Package/""" + + type: str = field(init=False, default="software_Package") + name: str # type: ignore + software_packageVersion: str | None = None + software_downloadLocation: str | None = None + + +@dataclass(kw_only=True) +class File(SoftwareArtifact): + """https://spdx.github.io/spdx-spec/v3.0.1/model/Software/Classes/File/""" + + type: str = field(init=False, default="software_File") + name: str # type: ignore + software_fileKind: FileKindType | None = None diff --git a/tools/sbom/sbom/spdx/spdxId.py b/tools/sbom/sbom/spdx/spdxId.py new file mode 100644 index 000000000000..589e85c5f706 --- /dev/null +++ b/tools/sbom/sbom/spdx/spdxId.py @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from itertools import count +from typing import Iterator + +SpdxId = str + + +class SpdxIdGenerator: + _namespace: str + _prefix: str | None = None + _counter: Iterator[int] + + def __init__(self, namespace: str, prefix: str | None = None) -> None: + """ + Initialize the SPDX ID generator with a namespace. + + Args: + namespace: The full namespace to use for generated IDs. + prefix: Optional. If provided, generated IDs will use this prefix instead of the full namespace. + """ + self._namespace = namespace + self._prefix = prefix + self._counter = count(0) + + def generate(self) -> SpdxId: + return f"{f'{self._prefix}:' if self._prefix else self._namespace}{next(self._counter)}" + + @property + def prefix(self) -> str | None: + return self._prefix + + @property + def namespace(self) -> str: + return self._namespace -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:44 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Add infrastructure to serialize an SPDX graph as a JSON-LD document. NamespaceMaps in the SPDX document are converted to custom prefixes in the @context field of the JSON-LD output. The SBOM tool uses NamespaceMaps solely to shorten SPDX IDs, avoiding repetition of full namespace URIs by using short prefixes. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- tools/sbom/Makefile | 3 +- tools/sbom/sbom.py | 52 +++++++++++++++++ tools/sbom/sbom/config.py | 56 +++++++++++++++++++ tools/sbom/sbom/path_utils.py | 11 ++++ tools/sbom/sbom/spdx_graph/__init__.py | 7 +++ .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 36 ++++++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 ++++++++++++ 7 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py diff --git a/tools/sbom/Makefile b/tools/sbom/Makefile index b4ef72b30960..f907f427bf8d 100644 --- a/tools/sbom/Makefile +++ b/tools/sbom/Makefile @@ -32,7 +32,8 @@ $(SBOM_TARGETS) &: $(SBOM_DEPS) --src-tree $(srctree) \ --obj-tree $(objtree) \ --roots-file $(SBOM_ROOTS_FILE) \ - --output-directory $(objtree) + --output-directory $(objtree) \ + --generate-spdx @rm $(SBOM_ROOTS_FILE) diff --git a/tools/sbom/sbom.py b/tools/sbom/sbom.py index 25d912a282de..426521ade460 100644 --- a/tools/sbom/sbom.py +++ b/tools/sbom/sbom.py @@ -6,13 +6,18 @@ Compute software bill of materials in SPDX format describing a kernel build. """ +import json import logging import os import sys import time +import uuid import sbom.sbom_logging as sbom_logging from sbom.config import get_config from sbom.path_utils import is_relative_to +from sbom.spdx import JsonLdSpdxDocument, SpdxIdGenerator +from sbom.spdx.core import CreationInfo, SpdxDocument +from sbom.spdx_graph import SpdxIdGeneratorCollection, build_spdx_graphs from sbom.cmd_graph import CmdGraph @@ -56,10 +61,57 @@ def main(): f.write("\n".join(str(file_path) for file_path in used_files)) logging.debug(f"Successfully saved {used_files_path}") + if config.generate_spdx is False: + return + + # Build SPDX Documents + logging.debug("Start generating SPDX graph based on cmd graph") + start_time = time.time() + + # The real uuid will be generated based on the content of the SPDX graphs + # to ensure that the same SPDX document is always assigned the same uuid. + PLACEHOLDER_UUID = "00000000-0000-0000-0000-000000000000" + spdx_id_base_namespace = f"{config.spdxId_prefix}{PLACEHOLDER_UUID}/" + spdx_id_generators = SpdxIdGeneratorCollection( + base=SpdxIdGenerator(prefix="p", namespace=spdx_id_base_namespace), + source=SpdxIdGenerator(prefix="s", namespace=f"{spdx_id_base_namespace}source/"), + build=SpdxIdGenerator(prefix="b", namespace=f"{spdx_id_base_namespace}build/"), + output=SpdxIdGenerator(prefix="o", namespace=f"{spdx_id_base_namespace}output/"), + ) + + spdx_graphs = build_spdx_graphs( + cmd_graph, + spdx_id_generators, + config, + ) + spdx_id_uuid = uuid.uuid5( + uuid.NAMESPACE_URL, + "".join( + json.dumps(element.to_dict()) for spdx_graph in spdx_graphs.values() for element in spdx_graph.to_list() + ), + ) + logging.debug(f"Generated SPDX graph in {time.time() - start_time} seconds") + # Report collected warnings and errors in case of failure warning_summary = sbom_logging.summarize_warnings() error_summary = sbom_logging.summarize_errors() + if not sbom_logging.has_errors() or config.write_output_on_error: + for kernel_sbom_kind, spdx_graph in spdx_graphs.items(): + spdx_graph_objects = spdx_graph.to_list() + # Add warning and error summary to creation info comment + creation_info = next(element for element in spdx_graph_objects if isinstance(element, CreationInfo)) + creation_info.comment = "\n".join([warning_summary, error_summary]).strip() + # Replace Placeholder uuid with real uuid for spdxIds + spdx_document = next(element for element in spdx_graph_objects if isinstance(element, SpdxDocument)) + for namespaceMap in spdx_document.namespaceMap: + namespaceMap.namespace = namespaceMap.namespace.replace(PLACEHOLDER_UUID, str(spdx_id_uuid)) + # Serialize SPDX graph to JSON-LD + spdx_doc = JsonLdSpdxDocument(graph=spdx_graph_objects) + save_path = os.path.join(config.output_directory, config.spdx_file_names[kernel_sbom_kind]) + spdx_doc.save(save_path, config.prettify_json) + logging.debug(f"Successfully saved {save_path}") + if warning_summary: logging.warning(warning_summary) if error_summary: diff --git a/tools/sbom/sbom/config.py b/tools/sbom/sbom/config.py index 39e556a4c53b..0985457c3cae 100644 --- a/tools/sbom/sbom/config.py +++ b/tools/sbom/sbom/config.py @@ -3,11 +3,18 @@ import argparse from dataclasses import dataclass +from enum import Enum import os from typing import Any from sbom.path_utils import PathStr +class KernelSpdxDocumentKind(Enum): + SOURCE = "source" + BUILD = "build" + OUTPUT = "output" + + @dataclass class KernelSbomConfig: src_tree: PathStr @@ -19,6 +26,13 @@ class KernelSbomConfig: root_paths: list[PathStr] """List of paths to root outputs (relative to obj_tree) to base the SBOM on.""" + generate_spdx: bool + """Whether to generate SPDX SBOM documents. If False, no SPDX files are created.""" + + spdx_file_names: dict[KernelSpdxDocumentKind, str] + """If `generate_spdx` is True, defines the file names for each SPDX SBOM kind + (source, build, output) to store on disk.""" + generate_used_files: bool """Whether to generate a flat list of all source files used in the build. If False, no used-files document is created.""" @@ -38,6 +52,12 @@ class KernelSbomConfig: write_output_on_error: bool """Whether to write output documents even if errors occur.""" + spdxId_prefix: str + """Prefix to use for all SPDX element IDs.""" + + prettify_json: bool + """Whether to pretty-print generated SPDX JSON documents.""" + def _parse_cli_arguments() -> dict[str, Any]: """ @@ -72,6 +92,15 @@ def _parse_cli_arguments() -> dict[str, Any]: "--roots-file", help="Path to a file containing the root paths (one per line). Cannot be used together with --roots.", ) + parser.add_argument( + "--generate-spdx", + action="store_true", + default=False, + help=( + "Whether to create sbom-source.spdx.json, sbom-build.spdx.json and " + "sbom-output.spdx.json documents (default: False)" + ), + ) parser.add_argument( "--generate-used-files", action="store_true", @@ -119,6 +148,20 @@ def _parse_cli_arguments() -> dict[str, Any]: ), ) + # SPDX specific options + spdx_group = parser.add_argument_group("SPDX options", "Options for customizing SPDX document generation") + spdx_group.add_argument( + "--spdxId-prefix", + default="urn:spdx.dev:", + help="The prefix to use for all spdxId properties. (default: urn:spdx.dev:)", + ) + spdx_group.add_argument( + "--prettify-json", + action="store_true", + default=False, + help="Whether to pretty print the generated spdx.json documents (default: False)", + ) + args = vars(parser.parse_args()) return args @@ -144,6 +187,7 @@ def get_config() -> KernelSbomConfig: root_paths = args["roots"] _validate_path_arguments(src_tree, obj_tree, root_paths) + generate_spdx = args["generate_spdx"] generate_used_files = args["generate_used_files"] output_directory = os.path.realpath(args["output_directory"]) debug = args["debug"] @@ -151,19 +195,31 @@ def get_config() -> KernelSbomConfig: fail_on_unknown_build_command = not args["do_not_fail_on_unknown_build_command"] write_output_on_error = args["write_output_on_error"] + spdxId_prefix = args["spdxId_prefix"] + prettify_json = args["prettify_json"] + # Hardcoded config + spdx_file_names = { + KernelSpdxDocumentKind.SOURCE: "sbom-source.spdx.json", + KernelSpdxDocumentKind.BUILD: "sbom-build.spdx.json", + KernelSpdxDocumentKind.OUTPUT: "sbom-output.spdx.json", + } used_files_file_name = "sbom.used-files.txt" return KernelSbomConfig( src_tree=src_tree, obj_tree=obj_tree, root_paths=root_paths, + generate_spdx=generate_spdx, + spdx_file_names=spdx_file_names, generate_used_files=generate_used_files, used_files_file_name=used_files_file_name, output_directory=output_directory, debug=debug, fail_on_unknown_build_command=fail_on_unknown_build_command, write_output_on_error=write_output_on_error, + spdxId_prefix=spdxId_prefix, + prettify_json=prettify_json, ) diff --git a/tools/sbom/sbom/path_utils.py b/tools/sbom/sbom/path_utils.py new file mode 100644 index 000000000000..d28d67b25398 --- /dev/null +++ b/tools/sbom/sbom/path_utils.py @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import os + +PathStr = str +"""Filesystem path represented as a plain string for better performance than pathlib.Path.""" + + +def is_relative_to(path: PathStr, base: PathStr) -> bool: + return os.path.commonpath([path, base]) == base diff --git a/tools/sbom/sbom/spdx_graph/__init__.py b/tools/sbom/sbom/spdx_graph/__init__.py new file mode 100644 index 000000000000..3557b1d51bf9 --- /dev/null +++ b/tools/sbom/sbom/spdx_graph/__init__.py @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from .build_spdx_graphs import build_spdx_graphs +from .spdx_graph_model import SpdxIdGeneratorCollection + +__all__ = ["build_spdx_graphs", "SpdxIdGeneratorCollection"] diff --git a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py new file mode 100644 index 000000000000..bb3db4e423da --- /dev/null +++ b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + + +from typing import Protocol + +from sbom.config import KernelSpdxDocumentKind +from sbom.cmd_graph import CmdGraph +from sbom.path_utils import PathStr +from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection + + +class SpdxGraphConfig(Protocol): + obj_tree: PathStr + src_tree: PathStr + + +def build_spdx_graphs( + cmd_graph: CmdGraph, + spdx_id_generators: SpdxIdGeneratorCollection, + config: SpdxGraphConfig, +) -> dict[KernelSpdxDocumentKind, SpdxGraph]: + """ + Builds SPDX graphs (output, source, and build) based on a cmd dependency graph. + If the source and object trees are identical, no dedicated source graph can be created. + In that case the source files are added to the build graph instead. + + Args: + cmd_graph: The dependency graph of a kernel build. + spdx_id_generators: Collection of SPDX ID generators. + config: Configuration options. + + Returns: + Dictionary of SPDX graphs + """ + return {} diff --git a/tools/sbom/sbom/spdx_graph/spdx_graph_model.py b/tools/sbom/sbom/spdx_graph/spdx_graph_model.py new file mode 100644 index 000000000000..682194d4362a --- /dev/null +++ b/tools/sbom/sbom/spdx_graph/spdx_graph_model.py @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass +from sbom.spdx.core import CreationInfo, SoftwareAgent, SpdxDocument, SpdxObject +from sbom.spdx.software import Sbom +from sbom.spdx.spdxId import SpdxIdGenerator + + +@dataclass +class SpdxGraph: + """Represents the complete graph of a single SPDX document.""" + + spdx_document: SpdxDocument + agent: SoftwareAgent + creation_info: CreationInfo + sbom: Sbom + + def to_list(self) -> list[SpdxObject]: + return [ + self.spdx_document, + self.agent, + self.creation_info, + self.sbom, + *self.sbom.element, + ] + + +@dataclass +class SpdxIdGeneratorCollection: + """Holds SPDX ID generators for different document types to ensure globally unique SPDX IDs.""" + + base: SpdxIdGenerator + source: SpdxIdGenerator + build: SpdxIdGenerator + output: SpdxIdGenerator -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:45 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Implement shared SPDX elements used in all three documents. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- tools/sbom/sbom/config.py | 25 +++++++++++++++ .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 5 ++- .../sbom/spdx_graph/shared_spdx_elements.py | 32 +++++++++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py diff --git a/tools/sbom/sbom/config.py b/tools/sbom/sbom/config.py index 0985457c3cae..9278e2be7cb2 100644 --- a/tools/sbom/sbom/config.py +++ b/tools/sbom/sbom/config.py @@ -3,6 +3,7 @@ import argparse from dataclasses import dataclass +from datetime import datetime from enum import Enum import os from typing import Any @@ -52,6 +53,9 @@ class KernelSbomConfig: write_output_on_error: bool """Whether to write output documents even if errors occur.""" + created: datetime + """Datetime to use for the SPDX created property of the CreationInfo element.""" + spdxId_prefix: str """Prefix to use for all SPDX element IDs.""" @@ -150,6 +154,16 @@ def _parse_cli_arguments() -> dict[str, Any]: # SPDX specific options spdx_group = parser.add_argument_group("SPDX options", "Options for customizing SPDX document generation") + spdx_group.add_argument( + "--created", + default=None, + help=( + "The SPDX created property to use for the CreationInfo element in " + "ISO format (YYYY-MM-DD [HH:MM:SS]).\n" + "If not provided the last modification time of the first root output " + "is used. (default: None)" + ), + ) spdx_group.add_argument( "--spdxId-prefix", default="urn:spdx.dev:", @@ -195,6 +209,16 @@ def get_config() -> KernelSbomConfig: fail_on_unknown_build_command = not args["do_not_fail_on_unknown_build_command"] write_output_on_error = args["write_output_on_error"] + if args["created"] is None: + created = datetime.fromtimestamp(os.path.getmtime(os.path.join(obj_tree, root_paths[0]))) + else: + try: + created = datetime.fromisoformat(args["created"]) + except ValueError: + raise argparse.ArgumentTypeError( + f"Invalid date format for argument '--created': '{args['created']}'. " + "Expected ISO format (YYYY-MM-DD [HH:MM:SS])." + ) spdxId_prefix = args["spdxId_prefix"] prettify_json = args["prettify_json"] @@ -218,6 +242,7 @@ def get_config() -> KernelSbomConfig: debug=debug, fail_on_unknown_build_command=fail_on_unknown_build_command, write_output_on_error=write_output_on_error, + created=created, spdxId_prefix=spdxId_prefix, prettify_json=prettify_json, ) diff --git a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py index bb3db4e423da..9c47258a31c6 100644 --- a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +++ b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py @@ -1,18 +1,20 @@ # SPDX-License-Identifier: GPL-2.0-only OR MIT # Copyright (C) 2025 TNG Technology Consulting GmbH - +from datetime import datetime from typing import Protocol from sbom.config import KernelSpdxDocumentKind from sbom.cmd_graph import CmdGraph from sbom.path_utils import PathStr from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection +from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements class SpdxGraphConfig(Protocol): obj_tree: PathStr src_tree: PathStr + created: datetime def build_spdx_graphs( @@ -33,4 +35,5 @@ def build_spdx_graphs( Returns: Dictionary of SPDX graphs """ + shared_elements = SharedSpdxElements.create(spdx_id_generators.base, config.created) return {} diff --git a/tools/sbom/sbom/spdx_graph/shared_spdx_elements.py b/tools/sbom/sbom/spdx_graph/shared_spdx_elements.py new file mode 100644 index 000000000000..0c83428f4c70 --- /dev/null +++ b/tools/sbom/sbom/spdx_graph/shared_spdx_elements.py @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass +from datetime import datetime +from sbom.spdx.core import CreationInfo, SoftwareAgent +from sbom.spdx.spdxId import SpdxIdGenerator + + +@dataclass(frozen=True) +class SharedSpdxElements: + agent: SoftwareAgent + creation_info: CreationInfo + + @classmethod + def create(cls, spdx_id_generator: SpdxIdGenerator, created: datetime) -> "SharedSpdxElements": + """ + Creates shared SPDX elements used across multiple documents. + + Args: + spdx_id_generator: Generator for creating SPDX IDs. + created: SPDX 'created' property used for the creation info. + + Returns: + SharedSpdxElements with agent and creation info. + """ + agent = SoftwareAgent( + spdxId=spdx_id_generator.generate(), + name="KernelSbom", + ) + creation_info = CreationInfo(createdBy=[agent], created=created.strftime("%Y-%m-%dT%H:%M:%SZ")) + return SharedSpdxElements(agent=agent, creation_info=creation_info) -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:46 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Implement the kernel_file module that collects file metadata, including license identifier for source files, SHA-256 hash, Git blob object ID, an estimation of the file type, and whether files belong to the source, build, or output SBOM. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 2 + tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++++++++++++ 2 files changed, 312 insertions(+) create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py diff --git a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py index 9c47258a31c6..0f95f99d560a 100644 --- a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +++ b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py @@ -7,6 +7,7 @@ from typing import Protocol from sbom.config import KernelSpdxDocumentKind from sbom.cmd_graph import CmdGraph from sbom.path_utils import PathStr +from sbom.spdx_graph.kernel_file import KernelFileCollection from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements @@ -36,4 +37,5 @@ def build_spdx_graphs( Dictionary of SPDX graphs """ shared_elements = SharedSpdxElements.create(spdx_id_generators.base, config.created) + kernel_files = KernelFileCollection.create(cmd_graph, config.obj_tree, config.src_tree, spdx_id_generators) return {} diff --git a/tools/sbom/sbom/spdx_graph/kernel_file.py b/tools/sbom/sbom/spdx_graph/kernel_file.py new file mode 100644 index 000000000000..84582567bc4d --- /dev/null +++ b/tools/sbom/sbom/spdx_graph/kernel_file.py @@ -0,0 +1,310 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass +from enum import Enum +import hashlib +import os +import re +from sbom.cmd_graph import CmdGraph +from sbom.path_utils import PathStr, is_relative_to +from sbom.spdx import SpdxId, SpdxIdGenerator +from sbom.spdx.core import Hash +from sbom.spdx.software import ContentIdentifier, File, SoftwarePurpose +import sbom.sbom_logging as sbom_logging +from sbom.spdx_graph.spdx_graph_model import SpdxIdGeneratorCollection + + +class KernelFileLocation(Enum): + """Represents the location of a file relative to the source/object trees.""" + + SOURCE_TREE = "source_tree" + """File is located in the source tree.""" + OBJ_TREE = "obj_tree" + """File is located in the object tree.""" + EXTERNAL = "external" + """File is located outside both source and object trees.""" + BOTH = "both" + """File is located in a folder that is both source and object tree.""" + + +@dataclass +class KernelFile: + """kernel-specific metadata used to generate an SPDX File element.""" + + absolute_path: PathStr + """Absolute path of the file.""" + file_location: KernelFileLocation + """Location of the file relative to the source/object trees.""" + name: str + """Name of the file element. Should be relative to the source tree if + file_location equals SOURCE_TREE and relative to the object tree if + file_location equals OBJ_TREE. If file_location equals EXTERNAL, the + absolute path is used.""" + license_identifier: str | None + """SPDX license ID if file_location equals SOURCE_TREE or BOTH; otherwise None.""" + spdx_id_generator: SpdxIdGenerator + """Generator for the SPDX ID of the file element.""" + + _spdx_file_element: File | None = None + + @classmethod + def create( + cls, + absolute_path: PathStr, + obj_tree: PathStr, + src_tree: PathStr, + spdx_id_generators: SpdxIdGeneratorCollection, + is_output: bool, + ) -> "KernelFile": + is_in_obj_tree = is_relative_to(absolute_path, obj_tree) + is_in_src_tree = is_relative_to(absolute_path, src_tree) + + # file element name should be relative to output or src tree if possible + if not is_in_src_tree and not is_in_obj_tree: + file_element_name = str(absolute_path) + file_location = KernelFileLocation.EXTERNAL + spdx_id_generator = spdx_id_generators.build + elif is_in_src_tree and src_tree == obj_tree: + file_element_name = os.path.relpath(absolute_path, obj_tree) + file_location = KernelFileLocation.BOTH + spdx_id_generator = spdx_id_generators.output if is_output else spdx_id_generators.build + elif is_in_obj_tree: + file_element_name = os.path.relpath(absolute_path, obj_tree) + file_location = KernelFileLocation.OBJ_TREE + spdx_id_generator = spdx_id_generators.output if is_output else spdx_id_generators.build + else: + file_element_name = os.path.relpath(absolute_path, src_tree) + file_location = KernelFileLocation.SOURCE_TREE + spdx_id_generator = spdx_id_generators.source + + # parse spdx license identifier + license_identifier = ( + _parse_spdx_license_identifier(absolute_path) + if file_location == KernelFileLocation.SOURCE_TREE or file_location == KernelFileLocation.BOTH + else None + ) + + return KernelFile( + absolute_path, + file_location, + file_element_name, + license_identifier, + spdx_id_generator, + ) + + @property + def spdx_file_element(self) -> File: + if self._spdx_file_element is None: + self._spdx_file_element = _build_file_element( + self.absolute_path, + self.name, + self.spdx_id_generator.generate(), + self.file_location, + ) + return self._spdx_file_element + + +@dataclass +class KernelFileCollection: + """Collection of kernel files.""" + + source: dict[PathStr, KernelFile] + build: dict[PathStr, KernelFile] + output: dict[PathStr, KernelFile] + + @classmethod + def create( + cls, + cmd_graph: CmdGraph, + obj_tree: PathStr, + src_tree: PathStr, + spdx_id_generators: SpdxIdGeneratorCollection, + ) -> "KernelFileCollection": + source: dict[PathStr, KernelFile] = {} + build: dict[PathStr, KernelFile] = {} + output: dict[PathStr, KernelFile] = {} + root_node_paths = {node.absolute_path for node in cmd_graph.roots} + for node in cmd_graph: + is_root = node.absolute_path in root_node_paths + kernel_file = KernelFile.create( + node.absolute_path, + obj_tree, + src_tree, + spdx_id_generators, + is_root, + ) + if is_root: + output[kernel_file.absolute_path] = kernel_file + elif kernel_file.file_location == KernelFileLocation.SOURCE_TREE: + source[kernel_file.absolute_path] = kernel_file + else: + build[kernel_file.absolute_path] = kernel_file + + return KernelFileCollection(source, build, output) + + def to_dict(self) -> dict[PathStr, KernelFile]: + return {**self.source, **self.build, **self.output} + + +def _build_file_element(absolute_path: PathStr, name: str, spdx_id: SpdxId, file_location: KernelFileLocation) -> File: + verifiedUsing: list[Hash] = [] + content_identifier: list[ContentIdentifier] = [] + if os.path.exists(absolute_path): + verifiedUsing = [Hash(algorithm="sha256", hashValue=_sha256(absolute_path))] + content_identifier = [ + ContentIdentifier( + software_contentIdentifierType="gitoid", + software_contentIdentifierValue=_git_blob_oid(absolute_path), + ) + ] + elif file_location == KernelFileLocation.EXTERNAL: + sbom_logging.warning( + "Cannot compute hash for {absolute_path} because file does not exist.", + absolute_path=absolute_path, + ) + else: + sbom_logging.error( + "Cannot compute hash for {absolute_path} because file does not exist.", + absolute_path=absolute_path, + ) + + # primary purpose + primary_purpose = _get_primary_purpose(absolute_path) + + return File( + spdxId=spdx_id, + name=name, + verifiedUsing=verifiedUsing, + software_primaryPurpose=primary_purpose, + software_contentIdentifier=content_identifier, + ) + + +def _sha256(path: PathStr) -> str: + """Compute the SHA-256 hash of a file.""" + with open(path, "rb") as f: + data = f.read() + return hashlib.sha256(data).hexdigest() + + +def _git_blob_oid(file_path: str) -> str: + """ + Compute the Git blob object ID (SHA-1) for a file, like `git hash-object`. + + Args: + file_path: Path to the file. + + Returns: + SHA-1 hash (hex) of the Git blob object. + """ + with open(file_path, "rb") as f: + content = f.read() + header = f"blob {len(content)}\0".encode() + store = header + content + sha1_hash = hashlib.sha1(store).hexdigest() + return sha1_hash + + +# REUSE-IgnoreStart +SPDX_LICENSE_IDENTIFIER_PATTERN = re.compile(r"SPDX-License-Identifier:\s*(?P<id>.*?)(?:\s*(\*/|$))") +# REUSE-IgnoreEnd + + +def _parse_spdx_license_identifier(absolute_path: str, max_lines: int = 5) -> str | None: + """ + Extracts the SPDX-License-Identifier from the first few lines of a source file. + + Args: + absolute_path: Path to the source file. + max_lines: Number of lines to scan from the top (default: 5). + + Returns: + The license identifier string (e.g., 'GPL-2.0-only') if found, otherwise None. + """ + try: + with open(absolute_path, "r") as f: + for _ in range(max_lines): + match = SPDX_LICENSE_IDENTIFIER_PATTERN.search(f.readline()) + if match: + return match.group("id") + except (UnicodeDecodeError, OSError): + return None + return None + + +def _get_primary_purpose(absolute_path: PathStr) -> SoftwarePurpose | None: + def ends_with(suffixes: list[str]) -> bool: + return any(absolute_path.endswith(suffix) for suffix in suffixes) + + def includes_path_segments(path_segments: list[str]) -> bool: + return any(segment in absolute_path for segment in path_segments) + + # Source code + if ends_with([".c", ".h", ".S", ".s", ".rs", ".pl"]): + return "source" + + # Libraries + if ends_with([".a", ".so", ".rlib"]): + return "library" + + # Archives + if ends_with([".xz", ".cpio", ".gz", ".tar", ".zip"]): + return "archive" + + # Applications + if ends_with(["bzImage", "Image"]): + return "application" + + # Executables / machine code + if ends_with([".bin", ".elf", "vmlinux", "vmlinux.unstripped", "bpfilter_umh"]): + return "executable" + + # Kernel modules + if ends_with([".ko"]): + return "module" + + # Data files + if ends_with( + [ + ".tbl", + ".relocs", + ".rmeta", + ".in", + ".dbg", + ".x509", + ".pbm", + ".ppm", + ".dtb", + ".uc", + ".inc", + ".dts", + ".dtsi", + ".dtbo", + ".xml", + ".ro", + "initramfs_inc_data", + "default_cpio_list", + "x509_certificate_list", + "utf8data.c_shipped", + "blacklist_hash_list", + "x509_revocation_list", + "cpucaps", + "sysreg", + ] + ) or includes_path_segments(["drivers/gpu/drm/radeon/reg_srcs/"]): + return "data" + + # Configuration files + if ends_with([".pem", ".key", ".conf", ".config", ".cfg", ".bconf"]): + return "configuration" + + # Documentation + if ends_with([".md"]): + return "documentation" + + # Other / miscellaneous + if ends_with([".o", ".tmp"]): + return "other" + + sbom_logging.warning("Could not infer primary purpose for {absolute_path}", absolute_path=absolute_path) -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:47 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Implement the SPDX source graph which contains all source files involved during the build, along with the licensing information for each file. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 8 ++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++++++++++++++++ 2 files changed, 134 insertions(+) create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py diff --git a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py index 2af0fbe6cdbe..a61257a905f3 100644 --- a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +++ b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py @@ -10,6 +10,7 @@ from sbom.path_utils import PathStr from sbom.spdx_graph.kernel_file import KernelFileCollection from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements +from sbom.spdx_graph.spdx_source_graph import SpdxSourceGraph from sbom.spdx_graph.spdx_output_graph import SpdxOutputGraph @@ -54,4 +55,11 @@ def build_spdx_graphs( KernelSpdxDocumentKind.OUTPUT: output_graph, } + if len(kernel_files.source) > 0: + spdx_graphs[KernelSpdxDocumentKind.SOURCE] = SpdxSourceGraph.create( + source_files=list(kernel_files.source.values()), + shared_elements=shared_elements, + spdx_id_generators=spdx_id_generators, + ) + return spdx_graphs diff --git a/tools/sbom/sbom/spdx_graph/spdx_source_graph.py b/tools/sbom/sbom/spdx_graph/spdx_source_graph.py new file mode 100644 index 000000000000..16176c4ea5ee --- /dev/null +++ b/tools/sbom/sbom/spdx_graph/spdx_source_graph.py @@ -0,0 +1,126 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass +from sbom.spdx import SpdxIdGenerator +from sbom.spdx.core import Element, NamespaceMap, Relationship, SpdxDocument +from sbom.spdx.simplelicensing import LicenseExpression +from sbom.spdx.software import File, Sbom +from sbom.spdx_graph.kernel_file import KernelFile +from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements +from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection + + +@dataclass +class SpdxSourceGraph(SpdxGraph): + """SPDX graph representing source files""" + + @classmethod + def create( + cls, + source_files: list[KernelFile], + shared_elements: SharedSpdxElements, + spdx_id_generators: SpdxIdGeneratorCollection, + ) -> "SpdxSourceGraph": + """ + Args: + source_files: List of files within the kernel source tree. + shared_elements: Shared SPDX elements used across multiple documents. + spdx_id_generators: Collection of SPDX ID generators. + + Returns: + SpdxSourceGraph: The SPDX source graph. + """ + # SpdxDocument + source_spdx_document = SpdxDocument( + spdxId=spdx_id_generators.source.generate(), + profileConformance=["core", "software", "simpleLicensing"], + namespaceMap=[ + NamespaceMap(prefix=generator.prefix, namespace=generator.namespace) + for generator in [spdx_id_generators.source, spdx_id_generators.base] + if generator.prefix is not None + ], + ) + + # Sbom + source_sbom = Sbom( + spdxId=spdx_id_generators.source.generate(), + software_sbomType=["source"], + ) + + # Src Tree Elements + src_tree_element = File( + spdxId=spdx_id_generators.source.generate(), + name="$(src_tree)", + software_fileKind="directory", + ) + src_tree_contains_relationship = Relationship( + spdxId=spdx_id_generators.source.generate(), + relationshipType="contains", + from_=src_tree_element, + to=[], + ) + + # Source file elements + source_file_elements: list[Element] = [file.spdx_file_element for file in source_files] + + # Source file license elements + source_file_license_identifiers, source_file_license_relationships = source_file_license_elements( + source_files, spdx_id_generators.source + ) + + # Update relationships + source_spdx_document.rootElement = [source_sbom] + source_sbom.rootElement = [src_tree_element] + source_sbom.element = [ + src_tree_element, + src_tree_contains_relationship, + *source_file_elements, + *source_file_license_identifiers, + *source_file_license_relationships, + ] + src_tree_contains_relationship.to = source_file_elements + + source_graph = SpdxSourceGraph( + source_spdx_document, + shared_elements.agent, + shared_elements.creation_info, + source_sbom, + ) + return source_graph + + +def source_file_license_elements( + source_files: list[KernelFile], spdx_id_generator: SpdxIdGenerator +) -> tuple[list[LicenseExpression], list[Relationship]]: + """ + Creates SPDX license expressions and links them to the given source files + via hasDeclaredLicense relationships. + + Args: + source_files: List of files within the kernel source tree. + spdx_id_generator: Generator for unique SPDX IDs. + + Returns: + Tuple of (license expressions, hasDeclaredLicense relationships). + """ + license_expressions: dict[str, LicenseExpression] = {} + for file in source_files: + if file.license_identifier is None or file.license_identifier in license_expressions: + continue + license_expressions[file.license_identifier] = LicenseExpression( + spdxId=spdx_id_generator.generate(), + simplelicensing_licenseExpression=file.license_identifier, + ) + + source_file_license_relationships = [ + Relationship( + spdxId=spdx_id_generator.generate(), + relationshipType="hasDeclaredLicense", + from_=file.spdx_file_element, + to=[license_expressions[file.license_identifier]], + ) + for file in source_files + if file.license_identifier is not None + ] + return ([*license_expressions.values()], source_file_license_relationships) -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:49 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Implement the SPDX output graph which contains the distributable build outputs and high level metadata about the build. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- tools/sbom/Makefile | 4 +- tools/sbom/sbom/config.py | 64 ++++++ tools/sbom/sbom/environment.py | 150 ++++++++++++++ .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 18 +- .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 ++++++++++++++++++ 5 files changed, 422 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py diff --git a/tools/sbom/Makefile b/tools/sbom/Makefile index f907f427bf8d..6af0f0f6e2eb 100644 --- a/tools/sbom/Makefile +++ b/tools/sbom/Makefile @@ -33,7 +33,9 @@ $(SBOM_TARGETS) &: $(SBOM_DEPS) --obj-tree $(objtree) \ --roots-file $(SBOM_ROOTS_FILE) \ --output-directory $(objtree) \ - --generate-spdx + --generate-spdx \ + --package-license "GPL-2.0 WITH Linux-syscall-note" \ + --package-version "$(KERNELVERSION)" @rm $(SBOM_ROOTS_FILE) diff --git a/tools/sbom/sbom/config.py b/tools/sbom/sbom/config.py index 9278e2be7cb2..de57d9d94edb 100644 --- a/tools/sbom/sbom/config.py +++ b/tools/sbom/sbom/config.py @@ -59,6 +59,21 @@ class KernelSbomConfig: spdxId_prefix: str """Prefix to use for all SPDX element IDs.""" + build_type: str + """SPDX buildType property to use for all Build elements.""" + + build_id: str | None + """SPDX buildId property to use for all Build elements.""" + + package_license: str + """License expression applied to all SPDX Packages.""" + + package_version: str | None + """Version string applied to all SPDX Packages.""" + + package_copyright_text: str | None + """Copyright text applied to all SPDX Packages.""" + prettify_json: bool """Whether to pretty-print generated SPDX JSON documents.""" @@ -169,6 +184,40 @@ def _parse_cli_arguments() -> dict[str, Any]: default="urn:spdx.dev:", help="The prefix to use for all spdxId properties. (default: urn:spdx.dev:)", ) + spdx_group.add_argument( + "--build-type", + default="urn:spdx.dev:Kbuild", + help="The SPDX buildType property to use for all Build elements. (default: urn:spdx.dev:Kbuild)", + ) + spdx_group.add_argument( + "--build-id", + default=None, + help="The SPDX buildId property to use for all Build elements.\n" + "If not provided the spdxId of the high level Build element is used as the buildId. (default: None)", + ) + spdx_group.add_argument( + "--package-license", + default="NOASSERTION", + help=( + "The SPDX licenseExpression property to use for the LicenseExpression " + "linked to all SPDX Package elements. (default: NOASSERTION)" + ), + ) + spdx_group.add_argument( + "--package-version", + default=None, + help="The SPDX packageVersion property to use for all SPDX Package elements. (default: None)", + ) + spdx_group.add_argument( + "--package-copyright-text", + default=None, + help=( + "The SPDX copyrightText property to use for all SPDX Package elements.\n" + "If not specified, and if a COPYING file exists in the source tree,\n" + "the package-copyright-text is set to the content of this file. " + "(default: None)" + ), + ) spdx_group.add_argument( "--prettify-json", action="store_true", @@ -220,6 +269,16 @@ def get_config() -> KernelSbomConfig: "Expected ISO format (YYYY-MM-DD [HH:MM:SS])." ) spdxId_prefix = args["spdxId_prefix"] + build_type = args["build_type"] + build_id = args["build_id"] + package_license = args["package_license"] + package_version = args["package_version"] if args["package_version"] is not None else None + package_copyright_text: str | None = None + if args["package_copyright_text"] is not None: + package_copyright_text = args["package_copyright_text"] + elif os.path.isfile(copying_path := os.path.join(src_tree, "COPYING")): + with open(copying_path, "r") as f: + package_copyright_text = f.read() prettify_json = args["prettify_json"] # Hardcoded config @@ -244,6 +303,11 @@ def get_config() -> KernelSbomConfig: write_output_on_error=write_output_on_error, created=created, spdxId_prefix=spdxId_prefix, + build_type=build_type, + build_id=build_id, + package_license=package_license, + package_version=package_version, + package_copyright_text=package_copyright_text, prettify_json=prettify_json, ) diff --git a/tools/sbom/sbom/environment.py b/tools/sbom/sbom/environment.py index b3fb2f0ba61d..f3a54bd613f9 100644 --- a/tools/sbom/sbom/environment.py +++ b/tools/sbom/sbom/environment.py @@ -3,12 +3,162 @@ import os +KERNEL_BUILD_VARIABLES_ALLOWLIST = [ + "AFLAGS_KERNEL", + "AFLAGS_MODULE", + "AR", + "ARCH", + "ARCH_CORE", + "ARCH_DRIVERS", + "ARCH_LIB", + "AWK", + "BASH", + "BINDGEN", + "BITS", + "CC", + "CC_FLAGS_FPU", + "CC_FLAGS_NO_FPU", + "CFLAGS_GCOV", + "CFLAGS_KERNEL", + "CFLAGS_MODULE", + "CHECK", + "CHECKFLAGS", + "CLIPPY_CONF_DIR", + "CONFIG_SHELL", + "CPP", + "CROSS_COMPILE", + "CURDIR", + "GNUMAKEFLAGS", + "HOSTCC", + "HOSTCXX", + "HOSTPKG_CONFIG", + "HOSTRUSTC", + "INSTALLKERNEL", + "INSTALL_DTBS_PATH", + "INSTALL_HDR_PATH", + "INSTALL_PATH", + "KBUILD_AFLAGS", + "KBUILD_AFLAGS_KERNEL", + "KBUILD_AFLAGS_MODULE", + "KBUILD_BUILTIN", + "KBUILD_CFLAGS", + "KBUILD_CFLAGS_KERNEL", + "KBUILD_CFLAGS_MODULE", + "KBUILD_CHECKSRC", + "KBUILD_CLIPPY", + "KBUILD_CPPFLAGS", + "KBUILD_EXTMOD", + "KBUILD_EXTRA_WARN", + "KBUILD_HOSTCFLAGS", + "KBUILD_HOSTCXXFLAGS", + "KBUILD_HOSTLDFLAGS", + "KBUILD_HOSTLDLIBS", + "KBUILD_HOSTRUSTFLAGS", + "KBUILD_IMAGE", + "KBUILD_LDFLAGS", + "KBUILD_LDFLAGS_MODULE", + "KBUILD_LDS", + "KBUILD_MODULES", + "KBUILD_PROCMACROLDFLAGS", + "KBUILD_RUSTFLAGS", + "KBUILD_RUSTFLAGS_KERNEL", + "KBUILD_RUSTFLAGS_MODULE", + "KBUILD_USERCFLAGS", + "KBUILD_USERLDFLAGS", + "KBUILD_VERBOSE", + "KBUILD_VMLINUX_LIBS", + "KBZIP2", + "KCONFIG_CONFIG", + "KERNELDOC", + "KERNELRELEASE", + "KERNELVERSION", + "KGZIP", + "KLZOP", + "LC_COLLATE", + "LC_NUMERIC", + "LD", + "LDFLAGS_MODULE", + "LEX", + "LINUXINCLUDE", + "LZ4", + "LZMA", + "MAKE", + "MAKEFILES", + "MAKEFILE_LIST", + "MAKEFLAGS", + "MAKELEVEL", + "MAKEOVERRIDES", + "MAKE_COMMAND", + "MAKE_HOST", + "MAKE_TERMERR", + "MAKE_TERMOUT", + "MAKE_VERSION", + "MFLAGS", + "MODLIB", + "NM", + "NOSTDINC_FLAGS", + "O", + "OBJCOPY", + "OBJCOPYFLAGS", + "OBJDUMP", + "PAHOLE", + "PATCHLEVEL", + "PERL", + "PYTHON3", + "Q", + "RCS_FIND_IGNORE", + "READELF", + "REALMODE_CFLAGS", + "RESOLVE_BTFIDS", + "RETHUNK_CFLAGS", + "RETHUNK_RUSTFLAGS", + "RETPOLINE_CFLAGS", + "RETPOLINE_RUSTFLAGS", + "RETPOLINE_VDSO_CFLAGS", + "RUSTC", + "RUSTC_BOOTSTRAP", + "RUSTC_OR_CLIPPY", + "RUSTC_OR_CLIPPY_QUIET", + "RUSTDOC", + "RUSTFLAGS_KERNEL", + "RUSTFLAGS_MODULE", + "RUSTFMT", + "SRCARCH", + "STRIP", + "SUBLEVEL", + "SUFFIXES", + "TAR", + "UTS_MACHINE", + "VERSION", + "VPATH", + "XZ", + "YACC", + "ZSTD", + "building_out_of_srctree", + "cross_compiling", + "objtree", + "quiet", + "rust_common_flags", + "srcroot", + "srctree", + "sub_make_done", + "subdir", +] + class Environment: """ Read-only accessor for kernel build environment variables. """ + @classmethod + def KERNEL_BUILD_VARIABLES(cls) -> dict[str, str | None]: + return {name: os.getenv(name) for name in KERNEL_BUILD_VARIABLES_ALLOWLIST} + + @classmethod + def ARCH(cls) -> str | None: + return os.getenv("ARCH") + @classmethod def SRCARCH(cls) -> str | None: return os.getenv("SRCARCH") diff --git a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py index 0f95f99d560a..2af0fbe6cdbe 100644 --- a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +++ b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py @@ -10,12 +10,18 @@ from sbom.path_utils import PathStr from sbom.spdx_graph.kernel_file import KernelFileCollection from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements +from sbom.spdx_graph.spdx_output_graph import SpdxOutputGraph class SpdxGraphConfig(Protocol): obj_tree: PathStr src_tree: PathStr created: datetime + build_type: str + build_id: str | None + package_license: str + package_version: str | None + package_copyright_text: str | None def build_spdx_graphs( @@ -38,4 +44,14 @@ def build_spdx_graphs( """ shared_elements = SharedSpdxElements.create(spdx_id_generators.base, config.created) kernel_files = KernelFileCollection.create(cmd_graph, config.obj_tree, config.src_tree, spdx_id_generators) - return {} + output_graph = SpdxOutputGraph.create( + root_files=list(kernel_files.output.values()), + shared_elements=shared_elements, + spdx_id_generators=spdx_id_generators, + config=config, + ) + spdx_graphs: dict[KernelSpdxDocumentKind, SpdxGraph] = { + KernelSpdxDocumentKind.OUTPUT: output_graph, + } + + return spdx_graphs diff --git a/tools/sbom/sbom/spdx_graph/spdx_output_graph.py b/tools/sbom/sbom/spdx_graph/spdx_output_graph.py new file mode 100644 index 000000000000..1ae0f935e0b9 --- /dev/null +++ b/tools/sbom/sbom/spdx_graph/spdx_output_graph.py @@ -0,0 +1,188 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass +import os +from typing import Protocol +from sbom.environment import Environment +from sbom.path_utils import PathStr +from sbom.spdx.build import Build +from sbom.spdx.core import DictionaryEntry, NamespaceMap, Relationship, SpdxDocument +from sbom.spdx.simplelicensing import LicenseExpression +from sbom.spdx.software import File, Package, Sbom +from sbom.spdx.spdxId import SpdxIdGenerator +from sbom.spdx_graph.kernel_file import KernelFile +from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements +from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection + + +class SpdxOutputGraphConfig(Protocol): + obj_tree: PathStr + src_tree: PathStr + build_type: str + build_id: str | None + package_license: str + package_version: str | None + package_copyright_text: str | None + + +@dataclass +class SpdxOutputGraph(SpdxGraph): + """SPDX graph representing distributable output files""" + + high_level_build_element: Build + + @classmethod + def create( + cls, + root_files: list[KernelFile], + shared_elements: SharedSpdxElements, + spdx_id_generators: SpdxIdGeneratorCollection, + config: SpdxOutputGraphConfig, + ) -> "SpdxOutputGraph": + """ + Args: + root_files: List of distributable output files which act as roots + of the dependency graph. + shared_elements: Shared SPDX elements used across multiple documents. + spdx_id_generators: Collection of SPDX ID generators. + config: Configuration options. + + Returns: + SpdxOutputGraph: The SPDX output graph. + """ + # SpdxDocument + spdx_document = SpdxDocument( + spdxId=spdx_id_generators.output.generate(), + profileConformance=["core", "software", "build", "simpleLicensing"], + namespaceMap=[ + NamespaceMap(prefix=generator.prefix, namespace=generator.namespace) + for generator in [spdx_id_generators.output, spdx_id_generators.base] + if generator.prefix is not None + ], + ) + + # Sbom + sbom = Sbom( + spdxId=spdx_id_generators.output.generate(), + software_sbomType=["build"], + ) + + # High-level Build elements + config_source_element = KernelFile.create( + absolute_path=os.path.join(config.obj_tree, ".config"), + obj_tree=config.obj_tree, + src_tree=config.src_tree, + spdx_id_generators=spdx_id_generators, + is_output=True, + ).spdx_file_element + high_level_build_element, high_level_build_element_hasOutput_relationship = _high_level_build_elements( + config.build_type, + config.build_id, + config_source_element, + spdx_id_generators.output, + ) + + # Root file elements + root_file_elements: list[File] = [file.spdx_file_element for file in root_files] + + # Package elements + package_elements = [ + Package( + spdxId=spdx_id_generators.output.generate(), + name=_get_package_name(file.name), + software_packageVersion=config.package_version, + software_copyrightText=config.package_copyright_text, + originatedBy=[shared_elements.agent], + comment=f"Architecture={arch}" if (arch := Environment.ARCH() or Environment.SRCARCH()) else None, + software_primaryPurpose=file.software_primaryPurpose, + ) + for file in root_file_elements + ] + package_hasDistributionArtifact_file_relationships = [ + Relationship( + spdxId=spdx_id_generators.output.generate(), + relationshipType="hasDistributionArtifact", + from_=package, + to=[file], + ) + for package, file in zip(package_elements, root_file_elements) + ] + package_license_expression = LicenseExpression( + spdxId=spdx_id_generators.output.generate(), + simplelicensing_licenseExpression=config.package_license, + ) + package_hasDeclaredLicense_relationships = [ + Relationship( + spdxId=spdx_id_generators.output.generate(), + relationshipType="hasDeclaredLicense", + from_=package, + to=[package_license_expression], + ) + for package in package_elements + ] + + # Update relationships + spdx_document.rootElement = [sbom] + + sbom.rootElement = [*package_elements] + sbom.element = [ + config_source_element, + high_level_build_element, + high_level_build_element_hasOutput_relationship, + *root_file_elements, + *package_elements, + *package_hasDistributionArtifact_file_relationships, + package_license_expression, + *package_hasDeclaredLicense_relationships, + ] + + high_level_build_element_hasOutput_relationship.to = [*root_file_elements] + + output_graph = SpdxOutputGraph( + spdx_document, + shared_elements.agent, + shared_elements.creation_info, + sbom, + high_level_build_element, + ) + return output_graph + + +def _get_package_name(filename: str) -> str: + """ + Generates a SPDX package name from a filename. + Kernel images (bzImage, Image) get a descriptive name, others use the basename of the file. + """ + KERNEL_FILENAMES = ["bzImage", "Image"] + basename = os.path.basename(filename) + return f"Linux Kernel ({basename})" if basename in KERNEL_FILENAMES else basename + + +def _high_level_build_elements( + build_type: str, + build_id: str | None, + config_source_element: File, + spdx_id_generator: SpdxIdGenerator, +) -> tuple[Build, Relationship]: + build_spdxId = spdx_id_generator.generate() + high_level_build_element = Build( + spdxId=build_spdxId, + build_buildType=build_type, + build_buildId=build_id if build_id is not None else build_spdxId, + build_environment=[ + DictionaryEntry(key=key, value=value) + for key, value in Environment.KERNEL_BUILD_VARIABLES().items() + if value + ], + build_configSourceUri=[config_source_element.spdxId], + build_configSourceDigest=config_source_element.verifiedUsing, + ) + + high_level_build_element_hasOutput_relationship = Relationship( + spdxId=spdx_id_generator.generate(), + relationshipType="hasOutput", + from_=high_level_build_element, + to=[], + ) + return high_level_build_element, high_level_build_element_hasOutput_relationship -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:48 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Verify that SPDX-License-Identifier headers at the top of source files are parsed correctly. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py diff --git a/tools/sbom/tests/spdx_graph/__init__.py b/tools/sbom/tests/spdx_graph/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tools/sbom/tests/spdx_graph/test_kernel_file.py b/tools/sbom/tests/spdx_graph/test_kernel_file.py new file mode 100644 index 000000000000..bc44e7a97d2a --- /dev/null +++ b/tools/sbom/tests/spdx_graph/test_kernel_file.py @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import unittest +from pathlib import Path +import tempfile +from sbom.spdx_graph.kernel_file import _parse_spdx_license_identifier # type: ignore + + +class TestKernelFile(unittest.TestCase): + def setUp(self): + self.tmpdir = tempfile.TemporaryDirectory() + self.src_tree = Path(self.tmpdir.name) + + def tearDown(self): + self.tmpdir.cleanup() + + def test_parse_spdx_license_identifier(self): + # REUSE-IgnoreStart + test_cases: list[tuple[str, str | None]] = [ + ("/* SPDX-License-Identifier: MIT*/", "MIT"), + ("// SPDX-License-Identifier: GPL-2.0-only", "GPL-2.0-only"), + ("/* SPDX-License-Identifier: GPL-2.0-or-later OR MIT */", "GPL-2.0-or-later OR MIT"), + ("/* SPDX-License-Identifier: Apache-2.0 */\n extra text", "Apache-2.0"), + ("int main() { return 0; }", None), + ] + # REUSE-IgnoreEnd + + for i, (file_content, expected_identifier) in enumerate(test_cases): + file_path = self.src_tree / f"file_{i}.c" + file_path.write_text(file_content) + self.assertEqual(_parse_spdx_license_identifier(str(file_path)), expected_identifier) -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:52 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Implement the SPDX build graph to describe the relationships between source files in the source SBOM and output files in the output SBOM. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 17 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 ++++++++++++++++++ 2 files changed, 334 insertions(+) create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py diff --git a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py index a61257a905f3..eecc52156449 100644 --- a/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py +++ b/tools/sbom/sbom/spdx_graph/build_spdx_graphs.py @@ -4,6 +4,7 @@ from datetime import datetime from typing import Protocol +import logging from sbom.config import KernelSpdxDocumentKind from sbom.cmd_graph import CmdGraph from sbom.path_utils import PathStr @@ -11,6 +12,7 @@ from sbom.spdx_graph.kernel_file import KernelFileCollection from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements from sbom.spdx_graph.spdx_source_graph import SpdxSourceGraph +from sbom.spdx_graph.spdx_build_graph import SpdxBuildGraph from sbom.spdx_graph.spdx_output_graph import SpdxOutputGraph @@ -61,5 +63,20 @@ def build_spdx_graphs( shared_elements=shared_elements, spdx_id_generators=spdx_id_generators, ) + else: + logging.info( + "Skipped creating a dedicated source SBOM because source files cannot be " + "reliably classified when the source and object trees are identical. " + "Added source files to the build SBOM instead." + ) + + build_graph = SpdxBuildGraph.create( + cmd_graph, + kernel_files, + shared_elements, + output_graph.high_level_build_element, + spdx_id_generators, + ) + spdx_graphs[KernelSpdxDocumentKind.BUILD] = build_graph return spdx_graphs diff --git a/tools/sbom/sbom/spdx_graph/spdx_build_graph.py b/tools/sbom/sbom/spdx_graph/spdx_build_graph.py new file mode 100644 index 000000000000..2956800fa9ed --- /dev/null +++ b/tools/sbom/sbom/spdx_graph/spdx_build_graph.py @@ -0,0 +1,317 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +from dataclasses import dataclass +from typing import Mapping +from sbom.cmd_graph import CmdGraph +from sbom.path_utils import PathStr +from sbom.spdx import SpdxIdGenerator +from sbom.spdx.build import Build +from sbom.spdx.core import ExternalMap, NamespaceMap, Relationship, SpdxDocument +from sbom.spdx.software import File, Sbom +from sbom.spdx_graph.kernel_file import KernelFileCollection +from sbom.spdx_graph.shared_spdx_elements import SharedSpdxElements +from sbom.spdx_graph.spdx_graph_model import SpdxGraph, SpdxIdGeneratorCollection +from sbom.spdx_graph.spdx_source_graph import source_file_license_elements + + +@dataclass +class SpdxBuildGraph(SpdxGraph): + """SPDX graph representing build dependencies connecting source files and + distributable output files""" + + @classmethod + def create( + cls, + cmd_graph: CmdGraph, + kernel_files: KernelFileCollection, + shared_elements: SharedSpdxElements, + high_level_build_element: Build, + spdx_id_generators: SpdxIdGeneratorCollection, + ) -> "SpdxBuildGraph": + if len(kernel_files.source) > 0: + return _create_spdx_build_graph( + cmd_graph, + kernel_files, + shared_elements, + high_level_build_element, + spdx_id_generators, + ) + else: + return _create_spdx_build_graph_with_mixed_sources( + cmd_graph, + kernel_files, + shared_elements, + high_level_build_element, + spdx_id_generators, + ) + + +def _create_spdx_build_graph( + cmd_graph: CmdGraph, + kernel_files: KernelFileCollection, + shared_elements: SharedSpdxElements, + high_level_build_element: Build, + spdx_id_generators: SpdxIdGeneratorCollection, +) -> SpdxBuildGraph: + """ + Creates an SPDX build graph where source and output files are referenced + from external documents. + + Args: + cmd_graph: The dependency graph of a kernel build. + kernel_files: Collection of categorized kernel files involved in the build. + shared_elements: SPDX elements shared across multiple documents. + high_level_build_element: The high-level Build element referenced by the build graph. + spdx_id_generators: Collection of generators for SPDX element IDs. + + Returns: + SpdxBuildGraph: The SPDX build graph connecting source files and distributable output files. + """ + # SpdxDocument + build_spdx_document = SpdxDocument( + spdxId=spdx_id_generators.build.generate(), + profileConformance=["core", "software", "build"], + namespaceMap=[ + NamespaceMap(prefix=generator.prefix, namespace=generator.namespace) + for generator in [ + spdx_id_generators.build, + spdx_id_generators.source, + spdx_id_generators.output, + spdx_id_generators.base, + ] + if generator.prefix is not None + ], + ) + + # Sbom + build_sbom = Sbom( + spdxId=spdx_id_generators.build.generate(), + software_sbomType=["build"], + ) + + # Src and object tree elements + obj_tree_element = File( + spdxId=spdx_id_generators.build.generate(), + name="$(obj_tree)", + software_fileKind="directory", + ) + obj_tree_contains_relationship = Relationship( + spdxId=spdx_id_generators.build.generate(), + relationshipType="contains", + from_=obj_tree_element, + to=[], + ) + + # File elements + build_file_elements = [file.spdx_file_element for file in kernel_files.build.values()] + file_relationships = _file_relationships( + cmd_graph=cmd_graph, + file_elements={key: file.spdx_file_element for key, file in kernel_files.to_dict().items()}, + high_level_build_element=high_level_build_element, + spdx_id_generator=spdx_id_generators.build, + ) + + # Update relationships + build_spdx_document.rootElement = [build_sbom] + + build_spdx_document.import_ = [ + *( + ExternalMap(externalSpdxId=file_element.spdx_file_element.spdxId) + for file_element in kernel_files.source.values() + ), + ExternalMap(externalSpdxId=high_level_build_element.spdxId), + *(ExternalMap(externalSpdxId=file.spdx_file_element.spdxId) for file in kernel_files.output.values()), + ] + + build_sbom.rootElement = [obj_tree_element] + build_sbom.element = [ + obj_tree_element, + obj_tree_contains_relationship, + *build_file_elements, + *file_relationships, + ] + + obj_tree_contains_relationship.to = [ + *build_file_elements, + *(file.spdx_file_element for file in kernel_files.output.values()), + ] + + # create Spdx graphs + build_graph = SpdxBuildGraph( + build_spdx_document, + shared_elements.agent, + shared_elements.creation_info, + build_sbom, + ) + return build_graph + + +def _create_spdx_build_graph_with_mixed_sources( + cmd_graph: CmdGraph, + kernel_files: KernelFileCollection, + shared_elements: SharedSpdxElements, + high_level_build_element: Build, + spdx_id_generators: SpdxIdGeneratorCollection, +) -> SpdxBuildGraph: + """ + Creates an SPDX build graph where only output files are referenced from + an external document. Source files are included directly in the build graph. + + Args: + cmd_graph: The dependency graph of a kernel build. + kernel_files: Collection of categorized kernel files involved in the build. + shared_elements: SPDX elements shared across multiple documents. + high_level_build_element: The high-level Build element referenced by the build graph. + spdx_id_generators: Collection of generators for SPDX element IDs. + + Returns: + SpdxBuildGraph: The SPDX build graph connecting source files and distributable output files. + """ + # SpdxDocument + build_spdx_document = SpdxDocument( + spdxId=spdx_id_generators.build.generate(), + profileConformance=["core", "software", "build"], + namespaceMap=[ + NamespaceMap(prefix=generator.prefix, namespace=generator.namespace) + for generator in [ + spdx_id_generators.build, + spdx_id_generators.output, + spdx_id_generators.base, + ] + if generator.prefix is not None + ], + ) + + # Sbom + build_sbom = Sbom( + spdxId=spdx_id_generators.build.generate(), + software_sbomType=["build"], + ) + + # File elements + build_file_elements = [file.spdx_file_element for file in kernel_files.build.values()] + file_relationships = _file_relationships( + cmd_graph=cmd_graph, + file_elements={key: file.spdx_file_element for key, file in kernel_files.to_dict().items()}, + high_level_build_element=high_level_build_element, + spdx_id_generator=spdx_id_generators.build, + ) + + # Source file license elements + source_file_license_identifiers, source_file_license_relationships = source_file_license_elements( + list(kernel_files.build.values()), spdx_id_generators.build + ) + + # Update relationships + build_spdx_document.rootElement = [build_sbom] + root_file_elements = [file.spdx_file_element for file in kernel_files.output.values()] + build_spdx_document.import_ = [ + ExternalMap(externalSpdxId=high_level_build_element.spdxId), + *(ExternalMap(externalSpdxId=file.spdxId) for file in root_file_elements), + ] + + build_sbom.rootElement = [*root_file_elements] + build_sbom.element = [ + *build_file_elements, + *source_file_license_identifiers, + *source_file_license_relationships, + *file_relationships, + ] + + build_graph = SpdxBuildGraph( + build_spdx_document, + shared_elements.agent, + shared_elements.creation_info, + build_sbom, + ) + return build_graph + + +def _file_relationships( + cmd_graph: CmdGraph, + file_elements: Mapping[PathStr, File], + high_level_build_element: Build, + spdx_id_generator: SpdxIdGenerator, +) -> list[Build | Relationship]: + """ + Construct SPDX Build and Relationship elements representing dependency + relationships in the cmd graph. + + Args: + cmd_graph: The dependency graph of a kernel build. + file_elements: Mapping of filesystem paths (PathStr) to their + corresponding SPDX File elements. + high_level_build_element: The SPDX Build element representing the overall build process/root. + spdx_id_generator: Generator for unique SPDX IDs. + + Returns: + list[Build | Relationship]: List of SPDX Build and Relationship elements + """ + high_level_build_ancestorOf_relationship = Relationship( + spdxId=spdx_id_generator.generate(), + relationshipType="ancestorOf", + from_=high_level_build_element, + completeness="complete", + to=[], + ) + + # Create a relationship between each node (output file) + # and its children (input files) + build_and_relationship_elements: list[Build | Relationship] = [high_level_build_ancestorOf_relationship] + for node in cmd_graph: + if next(node.children, None) is None: + continue + + # .cmd file dependencies + if node.cmd_file is not None: + build_element = Build( + spdxId=spdx_id_generator.generate(), + build_buildType=high_level_build_element.build_buildType, + build_buildId=high_level_build_element.build_buildId, + comment=node.cmd_file.savedcmd, + ) + hasInput_relationship = Relationship( + spdxId=spdx_id_generator.generate(), + relationshipType="hasInput", + from_=build_element, + to=[file_elements[child_node.absolute_path] for child_node in node.children], + ) + hasOutput_relationship = Relationship( + spdxId=spdx_id_generator.generate(), + relationshipType="hasOutput", + from_=build_element, + to=[file_elements[node.absolute_path]], + ) + build_and_relationship_elements += [ + build_element, + hasInput_relationship, + hasOutput_relationship, + ] + high_level_build_ancestorOf_relationship.to.append(build_element) + + # incbin dependencies + if len(node.incbin_dependencies) > 0: + incbin_dependsOn_relationship = Relationship( + spdxId=spdx_id_generator.generate(), + relationshipType="dependsOn", + comment="\n".join([incbin_dependency.full_statement for incbin_dependency in node.incbin_dependencies]), + from_=file_elements[node.absolute_path], + to=[ + file_elements[incbin_dependency.node.absolute_path] + for incbin_dependency in node.incbin_dependencies + ], + ) + build_and_relationship_elements.append(incbin_dependsOn_relationship) + + # hardcoded dependencies + if len(node.hardcoded_dependencies) > 0: + hardcoded_dependency_relationship = Relationship( + spdxId=spdx_id_generator.generate(), + relationshipType="dependsOn", + from_=file_elements[node.absolute_path], + to=[file_elements[n.absolute_path] for n in node.hardcoded_dependencies], + ) + build_and_relationship_elements.append(hardcoded_dependency_relationship) + + return build_and_relationship_elements -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:50 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Add unit tests to verify that command parsers correctly extract input files from build commands. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++++++++++ 3 files changed, 383 insertions(+) create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py diff --git a/tools/sbom/tests/__init__.py b/tools/sbom/tests/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tools/sbom/tests/cmd_graph/__init__.py b/tools/sbom/tests/cmd_graph/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tools/sbom/tests/cmd_graph/test_savedcmd_parser.py b/tools/sbom/tests/cmd_graph/test_savedcmd_parser.py new file mode 100644 index 000000000000..9409bc65ee25 --- /dev/null +++ b/tools/sbom/tests/cmd_graph/test_savedcmd_parser.py @@ -0,0 +1,383 @@ +# SPDX-License-Identifier: GPL-2.0-only OR MIT +# Copyright (C) 2025 TNG Technology Consulting GmbH + +import unittest + +from sbom.cmd_graph.savedcmd_parser import parse_inputs_from_commands +import sbom.sbom_logging as sbom_logging + + +class TestSavedCmdParser(unittest.TestCase): + def _assert_parsing(self, cmd: str, expected: str) -> None: + sbom_logging.init() + parsed = parse_inputs_from_commands(cmd, fail_on_unknown_build_command=False) + target = [] if expected == "" else expected.split(" ") + self.assertEqual(parsed, target) + errors = sbom_logging._error_logger.messages # type: ignore + self.assertEqual(errors, {}) + + # Compound command tests + def test_dd_cat(self): + cmd = "(dd if=arch/x86/boot/setup.bin bs=4k conv=sync status=none; cat arch/x86/boot/vmlinux.bin) >arch/x86/boot/bzImage" + expected = "arch/x86/boot/setup.bin arch/x86/boot/vmlinux.bin" + self._assert_parsing(cmd, expected) + + def test_manual_file_creation(self): + cmd = """{ symbase=__dtbo_overlay_bad_unresolved; echo '$(pound)include <asm-generic/vmlinux.lds.h>'; echo '.section .rodata,"a"'; echo '.balign STRUCT_ALIGNMENT'; echo ".global $${symbase}_begin"; echo "$${symbase}_begin:"; echo '.incbin "drivers/of/unittest-data/overlay_bad_unresolved.dtbo" '; echo ".global $${symbase}_end"; echo "$${symbase}_end:"; echo '.balign STRUCT_ALIGNMENT'; } > drivers/of/unittest-data/overlay_bad_unresolved.dtbo.S""" + expected = "" + self._assert_parsing(cmd, expected) + + def test_cat_xz_wrap(self): + cmd = "{ cat arch/x86/boot/compressed/vmlinux.bin | sh ../scripts/xz_wrap.sh; printf \\130\\064\\024\\000; } > arch/x86/boot/compressed/vmlinux.bin.xz" + expected = "arch/x86/boot/compressed/vmlinux.bin" + self._assert_parsing(cmd, expected) + + def test_printf_sed(self): + cmd = r"""{ printf 'static char tomoyo_builtin_profile[] __initdata =\n'; sed -e 's/\\/\\\\/g' -e 's/\"/\\"/g' -e 's/\(.*\)/\t"\1\\n"/' -- /dev/null; printf '\t"";\n'; printf 'static char tomoyo_builtin_exception_policy[] __initdata =\n'; sed -e 's/\\/\\\\/g' -e 's/\"/\\"/g' -e 's/\(.*\)/\t"\1\\n"/' -- ../security/tomoyo/policy/exception_policy.conf.default; printf '\t"";\n'; printf 'static char tomoyo_builtin_domain_policy[] __initdata =\n'; sed -e 's/\\/\\\\/g' -e 's/\"/\\"/g' -e 's/\(.*\)/\t"\1\\n"/' -- /dev/null; printf '\t"";\n'; printf 'static char tomoyo_builtin_manager[] __initdata =\n'; sed -e 's/\\/\\\\/g' -e 's/\"/\\"/g' -e 's/\(.*\)/\t"\1\\n"/' -- /dev/null; printf '\t"";\n'; printf 'static char tomoyo_builtin_stat[] __initdata =\n'; sed -e 's/\\/\\\\/g' -e 's/\"/\\"/g' -e 's/\(.*\)/\t"\1\\n"/' -- /dev/null; printf '\t"";\n'; } > security/tomoyo/builtin-policy.h""" + expected = "../security/tomoyo/policy/exception_policy.conf.default" + self._assert_parsing(cmd, expected) + + def test_bin2c_echo(self): + cmd = """(echo "static char tomoyo_builtin_profile[] __initdata ="; ./scripts/bin2c </dev/null; echo ";"; echo "static char tomoyo_builtin_exception_policy[] __initdata ="; ./scripts/bin2c <../security/tomoyo/policy/exception_policy.conf.default; echo ";"; echo "static char tomoyo_builtin_domain_policy[] __initdata ="; ./scripts/bin2c </dev/null; echo ";"; echo "static char tomoyo_builtin_manager[] __initdata ="; ./scripts/bin2c </dev/null; echo ";"; echo "static char tomoyo_builtin_stat[] __initdata ="; ./scripts/bin2c </dev/null; echo ";") >security/tomoyo/builtin-policy.h""" + expected = "../security/tomoyo/policy/exception_policy.conf.default" + self._assert_parsing(cmd, expected) + + def test_cat_colon(self): + cmd = "{ cat init/modules.order; cat usr/modules.order; cat arch/x86/modules.order; cat arch/x86/boot/startup/modules.order; cat kernel/modules.order; cat certs/modules.order; cat mm/modules.order; cat fs/modules.order; cat ipc/modules.order; cat security/modules.order; cat crypto/modules.order; cat block/modules.order; cat io_uring/modules.order; cat lib/modules.order; cat arch/x86/lib/modules.order; cat drivers/modules.order; cat sound/modules.order; cat samples/modules.order; cat net/modules.order; cat virt/modules.order; cat arch/x86/pci/modules.order; cat arch/x86/power/modules.order; cat arch/x86/video/modules.order; :; } > modules.order" + expected = "init/modules.order usr/modules.order arch/x86/modules.order arch/x86/boot/startup/modules.order kernel/modules.order certs/modules.order mm/modules.order fs/modules.order ipc/modules.order security/modules.order crypto/modules.order block/modules.order io_uring/modules.order lib/modules.order arch/x86/lib/modules.order drivers/modules.order sound/modules.order samples/modules.order net/modules.order virt/modules.order arch/x86/pci/modules.order arch/x86/power/modules.order arch/x86/video/modules.order" + self._assert_parsing(cmd, expected) + + def test_cat_zstd(self): + cmd = "{ cat arch/x86/boot/compressed/vmlinux.bin arch/x86/boot/compressed/vmlinux.relocs | zstd -22 --ultra; printf \\340\\362\\066\\003; } > arch/x86/boot/compressed/vmlinux.bin.zst" + expected = "arch/x86/boot/compressed/vmlinux.bin arch/x86/boot/compressed/vmlinux.relocs" + self._assert_parsing(cmd, expected) + + # cat command tests + def test_cat_redirect(self): + cmd = "cat ../fs/unicode/utf8data.c_shipped > fs/unicode/utf8data.c" + expected = "../fs/unicode/utf8data.c_shipped" + self._assert_parsing(cmd, expected) + + def test_cat_piped(self): + cmd = "cat arch/x86/boot/compressed/vmlinux.bin arch/x86/boot/compressed/vmlinux.relocs | gzip -n -f -9 > arch/x86/boot/compressed/vmlinux.bin.gz" + expected = "arch/x86/boot/compressed/vmlinux.bin arch/x86/boot/compressed/vmlinux.relocs" + self._assert_parsing(cmd, expected) + + # sed command tests + def test_sed(self): + cmd = "sed -n 's/.*define *BLIST_\\([A-Z0-9_]*\\) *.*/BLIST_FLAG_NAME(\\1),/p' ../include/scsi/scsi_devinfo.h > drivers/scsi/scsi_devinfo_tbl.c" + expected = "../include/scsi/scsi_devinfo.h" + self._assert_parsing(cmd, expected) + + # awk command tests + def test_awk(self): + cmd = "awk -f ../arch/arm64/tools/gen-cpucaps.awk ../arch/arm64/tools/cpucaps > arch/arm64/include/generated/asm/cpucap-defs.h" + expected = "../arch/arm64/tools/cpucaps" + self._assert_parsing(cmd, expected) + + def test_awk_with_input_redirection(self): + cmd = "awk -v N=1 -f ../lib/raid6/unroll.awk < ../lib/raid6/int.uc > lib/raid6/int1.c" + expected = "../lib/raid6/int.uc" + self._assert_parsing(cmd, expected) + + # openssl command tests + def test_openssl(self): + cmd = "openssl req -new -nodes -utf8 -sha256 -days 36500 -batch -x509 -config certs/x509.genkey -outform PEM -out certs/signing_key.pem -keyout certs/signing_key.pem 2>&1" + expected = "" + self._assert_parsing(cmd, expected) + + # gcc/clang command tests + def test_gcc(self): + cmd = ( + "gcc -Wp,-MMD,arch/x86/pci/.i386.o.d -nostdinc -I../arch/x86/include -I./arch/x86/include/generated -I../include -I./include -I../arch/x86/include/uapi -I./arch/x86/include/generated/uapi -I../include/uapi -I./include/generated/uapi -include ../include/linux/compiler-version.h -include ../include/linux/kconfig.h -include ../include/linux/compiler_types.h -D__KERNEL__ -fmacro-prefix-map=../= -Werror -std=gnu11 -fshort-wchar -funsigned-char -fno-common -fno-PIE -fno-strict-aliasing -mno-sse -mno-mmx -mno-sse2 -mno-3dnow -mno-avx -fcf-protection=branch -fno-jump-tables -m64 -falign-jumps=1 -falign-loops=1 -mno-80387 -mno-fp-ret-in-387 -mpreferred-stack-boundary=3 -mskip-rax-setup -march=x86-64 -mtune=generic -mno-red-zone -mcmodel=kernel -mstack-protector-guard-reg=gs -mstack-protector-guard-symbol=__ref_stack_chk_guard -Wno-sign-compare -fno-asynchronous-unwind-tables -mindirect-branch=thunk-extern -mindirect-branch-register -mindirect-branch-cs-prefix -mfunction-return=thunk-extern -fno-jump-tables -fpatchable-function-entry=16,16 -fno-delete-null-pointer-checks -O2 -fno-allow-store-data-races -fstack-protector-strong -fomit-frame-pointer -fno-stack-clash-protection -falign-functions=16 -fno-strict-overflow -fno-stack-check -fconserve-stack -fno-builtin-wcslen -Wall -Wextra -Wundef -Werror=implicit-function-declaration -Werror=implicit-int -Werror=return-type -Werror=strict-prototypes -Wno-format-security -Wno-trigraphs -Wno-frame-address -Wno-address-of-packed-member -Wmissing-declarations -Wmissing-prototypes -Wframe-larger-than=2048 -Wno-main -Wvla-larger-than=1 -Wno-pointer-sign -Wcast-function-type -Wno-array-bounds -Wno-stringop-overflow -Wno-alloc-size-larger-than -Wimplicit-fallthrough=5 -Werror=date-time -Werror=incompatible-pointer-types -Werror=designated-init -Wenum-conversion -Wunused -Wno-unused-but-set-variable -Wno-unused-const-variable -Wno-packed-not-aligned -Wno-format-overflow -Wno-format-truncation -Wno-stringop-truncation -Wno-override-init -Wno-missing-field-initializers -Wno-type-limits -Wno-shift-negative-value -Wno-maybe-uninitialized -Wno-sign-compare -Wno-unused-parameter -I../arch/x86/pci -Iarch/x86/pci -DKBUILD_MODFILE=" + "arch/x86/pci/i386" + " -DKBUILD_BASENAME=" + "i386" + " -DKBUILD_MODNAME=" + "i386" + " -D__KBUILD_MODNAME=kmod_i386 -c -o arch/x86/pci/i386.o ../arch/x86/pci/i386.c " + ) + expected = "../arch/x86/pci/i386.c" + self._assert_parsing(cmd, expected) + + def test_gcc_linking(self): + cmd = "gcc -o arch/x86/tools/relocs arch/x86/tools/relocs_32.o arch/x86/tools/relocs_64.o arch/x86/tools/relocs_common.o" + expected = "arch/x86/tools/relocs_32.o arch/x86/tools/relocs_64.o arch/x86/tools/relocs_common.o" + self._assert_parsing(cmd, expected) + + def test_gcc_without_compile_flag(self): + cmd = "gcc -Wp,-MMD,arch/x86/boot/compressed/.mkpiggy.d -Wall -Wmissing-prototypes -Wstrict-prototypes -O2 -fomit-frame-pointer -std=gnu11 -I ../scripts/include -I../tools/include -I arch/x86/boot/compressed -o arch/x86/boot/compressed/mkpiggy ../arch/x86/boot/compressed/mkpiggy.c" + expected = "../arch/x86/boot/compressed/mkpiggy.c" + self._assert_parsing(cmd, expected) + + def test_clang(self): + cmd = """clang -Wp,-MMD,arch/x86/entry/.entry_64_compat.o.d -nostdinc -I../arch/x86/include -I./arch/x86/include/generated -I../include -I./include -I../arch/x86/include/uapi -I./arch/x86/include/generated/uapi -I../include/uapi -I./include/generated/uapi -include ../include/linux/compiler-version.h -include ../include/linux/kconfig.h -D__KERNEL__ --target=x86_64-linux-gnu -fintegrated-as -Werror=unknown-warning-option -Werror=ignored-optimization-argument -Werror=option-ignored -Werror=unused-command-line-argument -fmacro-prefix-map=../= -Werror -D__ASSEMBLY__ -fno-PIE -m64 -I../arch/x86/entry -Iarch/x86/entry -DKBUILD_MODFILE='"arch/x86/entry/entry_64_compat"' -DKBUILD_MODNAME='"entry_64_compat"' -D__KBUILD_MODNAME=kmod_entry_64_compat -c -o arch/x86/entry/entry_64_compat.o ../arch/x86/entry/entry_64_compat.S""" + expected = "../arch/x86/entry/entry_64_compat.S" + self._assert_parsing(cmd, expected) + + # ld command tests + def test_ld(self): + cmd = 'ld -o arch/x86/entry/vdso/vdso64.so.dbg -shared --hash-style=both --build-id=sha1 --no-undefined --eh-frame-hdr -Bsymbolic -z noexecstack -m elf_x86_64 -soname linux-vdso.so.1 -z max-page-size=4096 -T arch/x86/entry/vdso/vdso.lds arch/x86/entry/vdso/vdso-note.o arch/x86/entry/vdso/vclock_gettime.o arch/x86/entry/vdso/vgetcpu.o arch/x86/entry/vdso/vgetrandom.o arch/x86/entry/vdso/vgetrandom-chacha.o; if readelf -rW arch/x86/entry/vdso/vdso64.so.dbg | grep -v _NONE | grep -q " R_\w*_"; then (echo >&2 "arch/x86/entry/vdso/vdso64.so.dbg: dynamic relocations are not supported"; rm -f arch/x86/entry/vdso/vdso64.so.dbg; /bin/false); fi' # type: ignore + expected = "arch/x86/entry/vdso/vdso-note.o arch/x86/entry/vdso/vclock_gettime.o arch/x86/entry/vdso/vgetcpu.o arch/x86/entry/vdso/vgetrandom.o arch/x86/entry/vdso/vgetrandom-chacha.o" + self._assert_parsing(cmd, expected) + + def test_ld_whole_archive(self): + cmd = "ld -m elf_x86_64 -z noexecstack -r -o vmlinux.o --whole-archive vmlinux.a --no-whole-archive --start-group --end-group" + expected = "vmlinux.a" + self._assert_parsing(cmd, expected) + + def test_ld_with_at_symbol(self): + cmd = "ld.lld -m elf_x86_64 -z noexecstack -r -o fs/efivarfs/efivarfs.o @fs/efivarfs/efivarfs.mod ; ./tools/objtool/objtool --hacks=jump_label --hacks=noinstr --hacks=skylake --ibt --orc --retpoline --rethunk --static-call --uaccess --prefix=16 --link --module fs/efivarfs/efivarfs.o" + expected = "@fs/efivarfs/efivarfs.mod" + self._assert_parsing(cmd, expected) + + def test_ld_if_objdump(self): + cmd = """ld -o arch/x86/entry/vdso/vdso64.so.dbg -shared --hash-style=both --build-id=sha1 --eh-frame-hdr -Bsymbolic -z noexecstack -m elf_x86_64 -soname linux-vdso.so.1 --no-undefined -z max-page-size=4096 -T arch/x86/entry/vdso/vdso.lds arch/x86/entry/vdso/vdso-note.o arch/x86/entry/vdso/vclock_gettime.o arch/x86/entry/vdso/vgetcpu.o arch/x86/entry/vdso/vsgx.o && sh ./arch/x86/entry/vdso/checkundef.sh 'nm' 'arch/x86/entry/vdso/vdso64.so.dbg'; if objdump -R arch/x86/entry/vdso/vdso64.so.dbg | grep -E -h "R_X86_64_JUMP_SLOT|R_X86_64_GLOB_DAT|R_X86_64_RELATIVE| R_386_GLOB_DAT|R_386_JMP_SLOT|R_386_RELATIVE"; then (echo >&2 "arch/x86/entry/vdso/vdso64.so.dbg: dynamic relocations are not supported"; rm -f arch/x86/entry/vdso/vdso64.so.dbg; /bin/false); fi""" + expected = "arch/x86/entry/vdso/vdso-note.o arch/x86/entry/vdso/vclock_gettime.o arch/x86/entry/vdso/vgetcpu.o arch/x86/entry/vdso/vsgx.o" + self._assert_parsing(cmd, expected) + + # printf | xargs ar command tests + def test_ar_printf(self): + cmd = 'rm -f built-in.a; printf "./%s " init/built-in.a usr/built-in.a arch/x86/built-in.a arch/x86/boot/startup/built-in.a kernel/built-in.a certs/built-in.a mm/built-in.a fs/built-in.a ipc/built-in.a security/built-in.a crypto/built-in.a block/built-in.a io_uring/built-in.a lib/built-in.a arch/x86/lib/built-in.a drivers/built-in.a sound/built-in.a net/built-in.a virt/built-in.a arch/x86/pci/built-in.a arch/x86/power/built-in.a arch/x86/video/built-in.a | xargs ar cDPrST built-in.a' + expected = "./init/built-in.a ./usr/built-in.a ./arch/x86/built-in.a ./arch/x86/boot/startup/built-in.a ./kernel/built-in.a ./certs/built-in.a ./mm/built-in.a ./fs/built-in.a ./ipc/built-in.a ./security/built-in.a ./crypto/built-in.a ./block/built-in.a ./io_uring/built-in.a ./lib/built-in.a ./arch/x86/lib/built-in.a ./drivers/built-in.a ./sound/built-in.a ./net/built-in.a ./virt/built-in.a ./arch/x86/pci/built-in.a ./arch/x86/power/built-in.a ./arch/x86/video/built-in.a" + self._assert_parsing(cmd, expected) + + def test_ar_printf_nested(self): + cmd = 'rm -f arch/x86/pci/built-in.a; printf "arch/x86/pci/%s " i386.o init.o mmconfig_64.o direct.o mmconfig-shared.o fixup.o acpi.o legacy.o irq.o common.o early.o bus_numa.o amd_bus.o | xargs ar cDPrST arch/x86/pci/built-in.a' + expected = "arch/x86/pci/i386.o arch/x86/pci/init.o arch/x86/pci/mmconfig_64.o arch/x86/pci/direct.o arch/x86/pci/mmconfig-shared.o arch/x86/pci/fixup.o arch/x86/pci/acpi.o arch/x86/pci/legacy.o arch/x86/pci/irq.o arch/x86/pci/common.o arch/x86/pci/early.o arch/x86/pci/bus_numa.o arch/x86/pci/amd_bus.o" + self._assert_parsing(cmd, expected) + + # ar command tests + def test_ar_reordering(self): + cmd = "rm -f vmlinux.a; ar cDPrST vmlinux.a built-in.a lib/lib.a arch/x86/lib/lib.a; ar mPiT $$(ar t vmlinux.a | sed -n 1p) vmlinux.a $$(ar t vmlinux.a | grep -F -f ../scripts/head-object-list.txt)" + expected = "built-in.a lib/lib.a arch/x86/lib/lib.a" + self._assert_parsing(cmd, expected) + + def test_ar_default(self): + cmd = "rm -f lib/lib.a; ar cDPrsT lib/lib.a lib/argv_split.o lib/bug.o lib/buildid.o lib/clz_tab.o lib/cmdline.o lib/cpumask.o lib/ctype.o lib/dec_and_lock.o lib/decompress.o lib/decompress_bunzip2.o lib/decompress_inflate.o lib/decompress_unlz4.o lib/decompress_unlzma.o lib/decompress_unlzo.o lib/decompress_unxz.o lib/decompress_unzstd.o lib/dump_stack.o lib/earlycpio.o lib/extable.o lib/flex_proportions.o lib/idr.o lib/iomem_copy.o lib/irq_regs.o lib/is_single_threaded.o lib/klist.o lib/kobject.o lib/kobject_uevent.o lib/logic_pio.o lib/maple_tree.o lib/memcat_p.o lib/nmi_backtrace.o lib/objpool.o lib/plist.o lib/radix-tree.o lib/ratelimit.o lib/rbtree.o lib/seq_buf.o lib/siphash.o lib/string.o lib/sys_info.o lib/timerqueue.o lib/union_find.o lib/vsprintf.o lib/win_minmax.o lib/xarray.o" + expected = "lib/argv_split.o lib/bug.o lib/buildid.o lib/clz_tab.o lib/cmdline.o lib/cpumask.o lib/ctype.o lib/dec_and_lock.o lib/decompress.o lib/decompress_bunzip2.o lib/decompress_inflate.o lib/decompress_unlz4.o lib/decompress_unlzma.o lib/decompress_unlzo.o lib/decompress_unxz.o lib/decompress_unzstd.o lib/dump_stack.o lib/earlycpio.o lib/extable.o lib/flex_proportions.o lib/idr.o lib/iomem_copy.o lib/irq_regs.o lib/is_single_threaded.o lib/klist.o lib/kobject.o lib/kobject_uevent.o lib/logic_pio.o lib/maple_tree.o lib/memcat_p.o lib/nmi_backtrace.o lib/objpool.o lib/plist.o lib/radix-tree.o lib/ratelimit.o lib/rbtree.o lib/seq_buf.o lib/siphash.o lib/string.o lib/sys_info.o lib/timerqueue.o lib/union_find.o lib/vsprintf.o lib/win_minmax.o lib/xarray.o" + self._assert_parsing(cmd, expected) + + def test_ar_llvm(self): + cmd = "llvm-ar mPiT $$(llvm-ar t vmlinux.a | sed -n 1p) vmlinux.a $$(llvm-ar t vmlinux.a | grep -F -f ../scripts/head-object-list.txt)" + expected = "" + self._assert_parsing(cmd, expected) + + # nm command tests + def test_nm(self): + cmd = """llvm-nm -p --defined-only rust/core.o | awk '$$2~/(T|R|D|B)/ && $$3!~/__(pfx|cfi|odr_asan)/ { printf "EXPORT_SYMBOL_RUST_GPL(%s);\n",$$3 }' > rust/exports_core_generated.h""" + expected = "rust/core.o" + self._assert_parsing(cmd, expected) + + def test_nm_vmlinux(self): + cmd = r"nm vmlinux | sed -n -e 's/^\([0-9a-fA-F]*\) [ABbCDGRSTtVW] \(_text\|__start_rodata\|__bss_start\|_end\)$/#define VO_\2 _AC(0x\1,UL)/p' > arch/x86/boot/voffset.h" + expected = "vmlinux" + self._assert_parsing(cmd, expected) + + # objcopy command tests + def test_objcopy(self): + cmd = "objcopy --remove-section='.rel*' --remove-section=!'.rel*.dyn' vmlinux.unstripped vmlinux" + expected = "vmlinux.unstripped" + self._assert_parsing(cmd, expected) + + def test_objcopy_llvm(self): + cmd = "llvm-objcopy --remove-section='.rel*' --remove-section=!'.rel*.dyn' vmlinux.unstripped vmlinux" + expected = "vmlinux.unstripped" + self._assert_parsing(cmd, expected) + + # strip command tests + def test_strip(self): + cmd = "strip --strip-debug -o drivers/firmware/efi/libstub/mem.stub.o drivers/firmware/efi/libstub/mem.o" + expected = "drivers/firmware/efi/libstub/mem.o" + self._assert_parsing(cmd, expected) + + # rustc command tests + def test_rustc(self): + cmd = """OBJTREE=/workspace/linux/kernel_build rustc -Zbinary_dep_depinfo=y -Astable_features -Dnon_ascii_idents -Dunsafe_op_in_unsafe_fn -Wmissing_docs -Wrust_2018_idioms -Wclippy::all -Wclippy::as_ptr_cast_mut -Wclippy::as_underscore -Wclippy::cast_lossless -Wclippy::ignored_unit_patterns -Wclippy::mut_mut -Wclippy::needless_bitwise_bool -Aclippy::needless_lifetimes -Wclippy::no_mangle_with_rust_abi -Wclippy::ptr_as_ptr -Wclippy::ptr_cast_constness -Wclippy::ref_as_ptr -Wclippy::undocumented_unsafe_blocks -Wclippy::unnecessary_safety_comment -Wclippy::unnecessary_safety_doc -Wrustdoc::missing_crate_level_docs -Wrustdoc::unescaped_backticks -Cpanic=abort -Cembed-bitcode=n -Clto=n -Cforce-unwind-tables=n -Ccodegen-units=1 -Csymbol-mangling-version=v0 -Crelocation-model=static -Zfunction-sections=n -Wclippy::float_arithmetic --target=./scripts/target.json -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2 -Zcf-protection=branch -Zno-jump-tables -Ctarget-cpu=x86-64 -Ztune-cpu=generic -Cno-redzone=y -Ccode-model=kernel -Zfunction-return=thunk-extern -Zpatchable-function-entry=16,16 -Copt-level=2 -Cdebug-assertions=n -Coverflow-checks=y -Dwarnings @./include/generated/rustc_cfg --edition=2021 --cfg no_fp_fmt_parse --emit=dep-info=rust/.core.o.d --emit=obj=rust/core.o --emit=metadata=rust/libcore.rmeta --crate-type rlib -L./rust --crate-name core /usr/lib/rust-1.84/lib/rustlib/src/rust/library/core/src/lib.rs --sysroot=/dev/null ;llvm-objcopy --redefine-sym __addsf3=__rust__addsf3 --redefine-sym __eqsf2=__rust__eqsf2 --redefine-sym __extendsfdf2=__rust__extendsfdf2 --redefine-sym __gesf2=__rust__gesf2 --redefine-sym __lesf2=__rust__lesf2 --redefine-sym __ltsf2=__rust__ltsf2 --redefine-sym __mulsf3=__rust__mulsf3 --redefine-sym __nesf2=__rust__nesf2 --redefine-sym __truncdfsf2=__rust__truncdfsf2 --redefine-sym __unordsf2=__rust__unordsf2 --redefine-sym __adddf3=__rust__adddf3 --redefine-sym __eqdf2=__rust__eqdf2 --redefine-sym __ledf2=__rust__ledf2 --redefine-sym __ltdf2=__rust__ltdf2 --redefine-sym __muldf3=__rust__muldf3 --redefine-sym __unorddf2=__rust__unorddf2 --redefine-sym __muloti4=__rust__muloti4 --redefine-sym __multi3=__rust__multi3 --redefine-sym __udivmodti4=__rust__udivmodti4 --redefine-sym __udivti3=__rust__udivti3 --redefine-sym __umodti3=__rust__umodti3 rust/core.o""" + expected = "/usr/lib/rust-1.84/lib/rustlib/src/rust/library/core/src/lib.rs rust/core.o" + self._assert_parsing(cmd, expected) + + # rustdoc command tests + def test_rustdoc(self): + cmd = """OBJTREE=/workspace/linux/kernel_build rustdoc --test --edition=2021 -Zbinary_dep_depinfo=y -Astable_features -Dnon_ascii_idents -Dunsafe_op_in_unsafe_fn -Wmissing_docs -Wrust_2018_idioms -Wunreachable_pub -Wclippy::all -Wclippy::as_ptr_cast_mut -Wclippy::as_underscore -Wclippy::cast_lossless -Wclippy::ignored_unit_patterns -Wclippy::mut_mut -Wclippy::needless_bitwise_bool -Aclippy::needless_lifetimes -Wclippy::no_mangle_with_rust_abi -Wclippy::ptr_as_ptr -Wclippy::ptr_cast_constness -Wclippy::ref_as_ptr -Wclippy::undocumented_unsafe_blocks -Wclippy::unnecessary_safety_comment -Wclippy::unnecessary_safety_doc -Wrustdoc::missing_crate_level_docs -Wrustdoc::unescaped_backticks -Cpanic=abort -Cembed-bitcode=n -Clto=n -Cforce-unwind-tables=n -Ccodegen-units=1 -Csymbol-mangling-version=v0 -Crelocation-model=static -Zfunction-sections=n -Wclippy::float_arithmetic --target=aarch64-unknown-none -Ctarget-feature="-neon" -Cforce-unwind-tables=n -Zbranch-protection=pac-ret -Copt-level=2 -Cdebug-assertions=y -Coverflow-checks=y -Dwarnings -Cforce-frame-pointers=y -Zsanitizer=kernel-address -Zsanitizer-recover=kernel-address -Cllvm-args=-asan-mapping-offset=0xdfff800000000000 -Cpasses=sancov-module -Cllvm-args=-sanitizer-coverage-level=3 -Cllvm-args=-sanitizer-coverage-trace-pc -Cllvm-args=-sanitizer-coverage-trace-compares @./include/generated/rustc_cfg -L./rust --extern ffi --extern pin_init --extern kernel --extern build_error --extern macros --extern bindings --extern uapi --no-run --crate-name kernel -Zunstable-options --sysroot=/dev/null --test-builder ./scripts/rustdoc_test_builder ../rust/kernel/lib.rs >/dev/null""" + expected = "../rust/kernel/lib.rs" + self._assert_parsing(cmd, expected) + + def test_rustdoc_test_gen(self): + cmd = "./scripts/rustdoc_test_gen" + expected = "" + self._assert_parsing(cmd, expected) + + # flex command tests + def test_flex(self): + cmd = "flex -oscripts/kconfig/lexer.lex.c -L ../scripts/kconfig/lexer.l" + expected = "../scripts/kconfig/lexer.l" + self._assert_parsing(cmd, expected) + + # bison command tests + def test_bison(self): + cmd = "bison -o scripts/kconfig/parser.tab.c --defines=scripts/kconfig/parser.tab.h -t -l ../scripts/kconfig/parser.y" + expected = "../scripts/kconfig/parser.y" + self._assert_parsing(cmd, expected) + + # bindgen command tests + def test_bindgen(self): + cmd = ( + "bindgen ../rust/bindings/bindings_helper.h " + "--blocklist-type __kernel_s?size_t --blocklist-type __kernel_ptrdiff_t " + "--opaque-type xregs_state --opaque-type desc_struct --no-doc-comments " + "--rust-target 1.68 --use-core --with-derive-default -o rust/bindings/bindings_generated.rs " + "-- -Wp,-MMD,rust/bindings/.bindings_generated.rs.d -nostdinc -I../arch/x86/include " + "-include ../include/linux/compiler-version.h -D__KERNEL__ -fintegrated-as -fno-builtin -DMODULE; " + "sed -Ei 's/pub const RUST_CONST_HELPER_([a-zA-Z0-9_]*)/pub const \\1/g' rust/bindings/bindings_generated.rs" + ) + expected = "../rust/bindings/bindings_helper.h ../include/linux/compiler-version.h" + self._assert_parsing(cmd, expected) + + # perl command tests + def test_perl(self): + cmd = "perl ../lib/crypto/x86/poly1305-x86_64-cryptogams.pl > lib/crypto/x86/poly1305-x86_64-cryptogams.S" + expected = "../lib/crypto/x86/poly1305-x86_64-cryptogams.pl" + self._assert_parsing(cmd, expected) + + # link-vmlinux.sh command tests + def test_link_vmlinux(self): + cmd = '../scripts/link-vmlinux.sh "ld" "-m elf_x86_64 -z noexecstack" "-z max-page-size=0x200000 --build-id=sha1 --orphan-handling=error --emit-relocs --discard-none" "vmlinux.unstripped"; true' + expected = "vmlinux.a" + self._assert_parsing(cmd, expected) + + def test_link_vmlinux_postlink(self): + cmd = '../scripts/link-vmlinux.sh "ld" "-m elf_x86_64 -z noexecstack --no-warn-rwx-segments" "--emit-relocs --discard-none -z max-page-size=0x200000 --build-id=sha1 -X --orphan-handling=error"; make -f ../arch/x86/Makefile.postlink vmlinux' + expected = "vmlinux.a" + self._assert_parsing(cmd, expected) + + # syscallhdr.sh command tests + def test_syscallhdr(self): + cmd = "sh ../scripts/syscallhdr.sh --abis common,64 --emit-nr ../arch/x86/entry/syscalls/syscall_64.tbl arch/x86/include/generated/uapi/asm/unistd_64.h" + expected = "../arch/x86/entry/syscalls/syscall_64.tbl" + self._assert_parsing(cmd, expected) + + # syscalltbl.sh command tests + def test_syscalltbl(self): + cmd = "sh ../scripts/syscalltbl.sh --abis common,64 ../arch/x86/entry/syscalls/syscall_64.tbl arch/x86/include/generated/asm/syscalls_64.h" + expected = "../arch/x86/entry/syscalls/syscall_64.tbl" + self._assert_parsing(cmd, expected) + + # mkcapflags.sh command tests + def test_mkcapflags(self): + cmd = "sh ../arch/x86/kernel/cpu/mkcapflags.sh arch/x86/kernel/cpu/capflags.c ../arch/x86/kernel/cpu/../../include/asm/cpufeatures.h ../arch/x86/kernel/cpu/../../include/asm/vmxfeatures.h ../arch/x86/kernel/cpu/mkcapflags.sh FORCE" + expected = "../arch/x86/kernel/cpu/../../include/asm/cpufeatures.h ../arch/x86/kernel/cpu/../../include/asm/vmxfeatures.h" + self._assert_parsing(cmd, expected) + + # orc_hash.sh command tests + def test_orc_hash(self): + cmd = "mkdir -p arch/x86/include/generated/asm/; sh ../scripts/orc_hash.sh < ../arch/x86/include/asm/orc_types.h > arch/x86/include/generated/asm/orc_hash.h" + expected = "../arch/x86/include/asm/orc_types.h" + self._assert_parsing(cmd, expected) + + # xen-hypercalls.sh command tests + def test_xen_hypercalls(self): + cmd = "sh '../scripts/xen-hypercalls.sh' arch/x86/include/generated/asm/xen-hypercalls.h ../include/xen/interface/xen-mca.h ../include/xen/interface/xen.h ../include/xen/interface/xenpmu.h" + expected = "../include/xen/interface/xen-mca.h ../include/xen/interface/xen.h ../include/xen/interface/xenpmu.h" + self._assert_parsing(cmd, expected) + + # gen_initramfs.sh command tests + def test_gen_initramfs(self): + cmd = "sh ../usr/gen_initramfs.sh -o usr/initramfs_data.cpio -l usr/.initramfs_data.cpio.d ../usr/default_cpio_list" + expected = "../usr/default_cpio_list" + self._assert_parsing(cmd, expected) + + # vdso2c command tests + def test_vdso2c(self): + cmd = "arch/x86/entry/vdso/vdso2c arch/x86/entry/vdso/vdso64.so.dbg arch/x86/entry/vdso/vdso64.so arch/x86/entry/vdso/vdso-image-64.c" + expected = "arch/x86/entry/vdso/vdso64.so.dbg arch/x86/entry/vdso/vdso64.so" + self._assert_parsing(cmd, expected) + + # mkpiggy command tests + def test_mkpiggy(self): + cmd = "arch/x86/boot/compressed/mkpiggy arch/x86/boot/compressed/vmlinux.bin.gz > arch/x86/boot/compressed/piggy.S" + expected = "arch/x86/boot/compressed/vmlinux.bin.gz" + self._assert_parsing(cmd, expected) + + # relocs command tests + def test_relocs(self): + cmd = "arch/x86/tools/relocs vmlinux.unstripped > arch/x86/boot/compressed/vmlinux.relocs;arch/x86/tools/relocs --abs-relocs vmlinux.unstripped" + expected = "vmlinux.unstripped" + self._assert_parsing(cmd, expected) + + def test_relocs_with_realmode(self): + cmd = ( + "arch/x86/tools/relocs --realmode arch/x86/realmode/rm/realmode.elf > arch/x86/realmode/rm/realmode.relocs" + ) + expected = "arch/x86/realmode/rm/realmode.elf" + self._assert_parsing(cmd, expected) + + # mk_elfconfig command tests + def test_mk_elfconfig(self): + cmd = "scripts/mod/mk_elfconfig < scripts/mod/empty.o > scripts/mod/elfconfig.h" + expected = "scripts/mod/empty.o" + self._assert_parsing(cmd, expected) + + # tools/build command tests + def test_build(self): + cmd = "arch/x86/boot/tools/build arch/x86/boot/setup.bin arch/x86/boot/vmlinux.bin arch/x86/boot/zoffset.h arch/x86/boot/bzImage" + expected = "arch/x86/boot/setup.bin arch/x86/boot/vmlinux.bin arch/x86/boot/zoffset.h" + self._assert_parsing(cmd, expected) + + # extract-cert command tests + def test_extract_cert(self): + cmd = 'certs/extract-cert "" certs/signing_key.x509' + expected = "" + self._assert_parsing(cmd, expected) + + # dtc command tests + def test_dtc_cat(self): + cmd = "./scripts/dtc/dtc -o drivers/of/empty_root.dtb -b 0 -i../drivers/of/ -i../scripts/dtc/include-prefixes -Wno-unique_unit_address -Wno-unit_address_vs_reg -Wno-avoid_unnecessary_addr_size -Wno-alias_paths -Wno-graph_child_address -Wno-simple_bus_reg -d drivers/of/.empty_root.dtb.d.dtc.tmp drivers/of/.empty_root.dtb.dts.tmp ; cat drivers/of/.empty_root.dtb.d.pre.tmp drivers/of/.empty_root.dtb.d.dtc.tmp > drivers/of/.empty_root.dtb.d" + expected = "drivers/of/.empty_root.dtb.dts.tmp drivers/of/.empty_root.dtb.d.pre.tmp drivers/of/.empty_root.dtb.d.dtc.tmp" + self._assert_parsing(cmd, expected) + + # pnmtologo command tests + def test_pnmtologo(self): + cmd = "drivers/video/logo/pnmtologo -t clut224 -n logo_linux_clut224 -o drivers/video/logo/logo_linux_clut224.c ../drivers/video/logo/logo_linux_clut224.ppm" + expected = "../drivers/video/logo/logo_linux_clut224.ppm" + self._assert_parsing(cmd, expected) + + # relacheck command tests + def test_relacheck(self): + cmd = "arch/arm64/kernel/pi/relacheck arch/arm64/kernel/pi/idreg-override.pi.o arch/arm64/kernel/pi/idreg-override.o" + expected = "arch/arm64/kernel/pi/idreg-override.pi.o" + self._assert_parsing(cmd, expected) + + # mkregtable command tests + def test_mkregtable(self): + cmd = "drivers/gpu/drm/radeon/mkregtable ../drivers/gpu/drm/radeon/reg_srcs/r100 > drivers/gpu/drm/radeon/r100_reg_safe.h" + expected = "../drivers/gpu/drm/radeon/reg_srcs/r100" + self._assert_parsing(cmd, expected) + + # genheaders command tests + def test_genheaders(self): + cmd = "security/selinux/genheaders security/selinux/flask.h security/selinux/av_permissions.h" + expected = "" + self._assert_parsing(cmd, expected) + + # mkcpustr command tests + def test_mkcpustr(self): + cmd = "arch/x86/boot/mkcpustr > arch/x86/boot/cpustr.h" + expected = "" + self._assert_parsing(cmd, expected) + + # polgen command tests + def test_polgen(self): + cmd = "scripts/ipe/polgen/polgen security/ipe/boot_policy.c" + expected = "" + self._assert_parsing(cmd, expected) + + # gen_header.py command tests + def test_gen_header(self): + cmd = "mkdir -p drivers/gpu/drm/msm/generated && python3 ../drivers/gpu/drm/msm/registers/gen_header.py --no-validate --rnn ../drivers/gpu/drm/msm/registers --xml ../drivers/gpu/drm/msm/registers/adreno/a2xx.xml c-defines > drivers/gpu/drm/msm/generated/a2xx.xml.h" + expected = "../drivers/gpu/drm/msm/registers/adreno/a2xx.xml" + self._assert_parsing(cmd, expected) + + +if __name__ == "__main__": + unittest.main() -- 2.34.1
{ "author": "Luis Augenstein <luis.augenstein@tngtech.com>", "date": "Tue, 20 Jan 2026 12:53:51 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Tue, Jan 20, 2026 at 12:53:38PM +0100, Luis Augenstein wrote: I'm still getting: make[3]: Nothing to be done for 'sbom'. When rebuilding the kernel and nothing needs to be done for the sbom. That message should not be there, right? thanks, greg k-h
{ "author": "Greg KH <gregkh@linuxfoundation.org>", "date": "Tue, 20 Jan 2026 16:40:09 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Thu, Jan 22, 2026 at 4:31 AM Luis Augenstein <luis.augenstein@tngtech.com> wrote: Hmm... Is this supposed to have two files in `expected`? I mean, `core.o` is really the output of the rule, even if it gets modified in-place in the middle. Cheers, Miguel
{ "author": "Miguel Ojeda <miguel.ojeda.sandonis@gmail.com>", "date": "Thu, 22 Jan 2026 07:00:19 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Wed, Jan 21, 2026 at 6:55 AM Luis Augenstein <luis.augenstein@tngtech.com> wrote: I am out of the loop, and I don't know the requirements here, but what kind of approaches were considered for this? Parsing the `.cmd`s seems a bit ad-hoc / after-the-fact approach, and from a very cursory look at the patches, it seems to require a fair amount of hardcoding, e.g. it seems we may need to list every generator tool in `SINGLE_COMMAND_PARSERS`? Now, if this is meant to be best-effort and cover the most important parts, it may be fine -- again, I don't know the requirements here. But if it is meant to accurately match everything, then it will require keeping those lists in sync with Kbuild, right? Hmm... I feel like changing the build system itself (whether at the Kbuild level or even a customized Make itself if needed) to record this information would be conceptually simpler / more elegant, even if changing Kbuild itself can sometimes be quite a challenge. In addition, why does this need to be a `CONFIG_` option? Should this be a separate tool or at most a target that supports whatever config happens to be, rather than part of the config itself? Thanks! Cheers, Miguel
{ "author": "Miguel Ojeda <miguel.ojeda.sandonis@gmail.com>", "date": "Thu, 22 Jan 2026 07:18:18 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Thu, Jan 22, 2026 at 07:18:18AM +0100, Miguel Ojeda wrote: Lots of different attempts, usually using bpf and other run-time tracing tools. But it was determined that we already have this info in our build dependancy files, so parsing them was picked. If you know of a better way, that would be great! It should match everything, and yes, it will require keeping things in sync. Changing kbuild would be great too, if you know of a way we can get that info out of it. It should be part of the kernel build process, and generated as part of it as it will want to go into some packages directly. Having to run the build "again" is probably not a good idea (i.e. do you want to modify all the distro rpm scripts?) thanks, greg k-h
{ "author": "Greg KH <gregkh@linuxfoundation.org>", "date": "Thu, 22 Jan 2026 07:35:42 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Thu, Jan 22, 2026 at 7:35 AM Greg KH <gregkh@linuxfoundation.org> wrote: Yes, if I understand correctly, then this should be done on the build system side (i.e. I don't see how BPF/tracing could achieve this, so maybe I am missing something), but what I meant is that there are several ways to do this in the build system side. One is this kind of post-processing after the build, which is easier in that it avoids touching Kbuild and can be written in something like Python, which always helps. The downside (my worry) is that it introduces yet another layer to Kbuild. My first instinct would have been to try to see if the build system itself could already give us what is built while it gets built (i.e. just like it outputs the `cmd` files). So I wondered if that was considered. It depends on what is needed, but Kbuild of course knows about input and output files and dependencies, so I was thinking of outputting that information in an easier format instead of having to parse command lines from the `cmd` files. Even with `CONFIG_SBOM`, they will need to modify at least their kernel configuration, and perhaps more if they want to save the SBOM files differently, e.g. in another package etc. So I am not sure if it is a big difference for any distro than adding a word to their `make` line. Now, I understand it may be easier to tell users to "just turn one more config", and perhaps it looks more "integrated" to them, but I mainly asked because, to me, the SBOM is orthogonal to the kernel configuration. In other words, I would have expected to be able to get an SBOM for any build, without having to modify the kernel configuration at all. After all, the kernel image should not change at all whether there is an SBOM or not. We also do not do that for some other big "globally orthogonal" things that involve generating extra files, like documentation. I hope that helps somehow... Cheers, Miguel
{ "author": "Miguel Ojeda <miguel.ojeda.sandonis@gmail.com>", "date": "Sun, 25 Jan 2026 16:20:40 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Thu, Jan 22, 2026 at 9:32 PM Luis Augenstein <luis.augenstein@tngtech.com> wrote: I was not suggesting to take it out of `make` completely if the environment is needed, but rather have the user call the target (which could still depend on the kernel build like you have it now). For instance, for generating the rust-analyzer configuration, we want to have the environment too, so we have a Make target that users call when they need it, rather than making it a configuration of the kernel. Now, I can understand there may be other reasons (please see my reply to Greg). Thanks! Cheers, Miguel
{ "author": "Miguel Ojeda <miguel.ojeda.sandonis@gmail.com>", "date": "Sun, 25 Jan 2026 16:30:16 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Sun, Jan 25, 2026 at 4:20 PM Miguel Ojeda <miguel.ojeda.sandonis@gmail.com> wrote: Well, I guess the SBOM could be saved into the kernel itself (and perhaps retrieved in different ways, e.g. at runtime), in which case, then an option definitely makes sense. Cheers, Miguel
{ "author": "Miguel Ojeda <miguel.ojeda.sandonis@gmail.com>", "date": "Sun, 25 Jan 2026 16:33:28 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Sun, Jan 25, 2026 at 04:20:40PM +0100, Miguel Ojeda wrote: for a horrible hack of an example of how you can do this using bpf/tracing, see this "fun" thing that I use every so often: https://github.com/gregkh/gregkh-linux/blob/master/scripts/trace_kernel_build.sh it uses bpftrace to inject a script and then do a build and then post-process the output. Not something you should ever do on a "real" build system :) That's what is happening here, it's post-processing the build files to detetct the dependancy graph it already knows about. cmake can do this, that's what Zephyr uses, but we don't use cmake for kernel builds. I know the gnu toolchain developers have talked about adding this to make/gcc/whatever in the past, and I thought Red Hat was funding them to do that, but it seems to have never gone anywhere and it's been years since I last heard from them. "all" we need is the list of files that are used to make the resulting kernel image and modules. Given that the kernel build is self-contained, and does not pull in anything from outside of its tree (well, with the exception of some rust things I think), we should be ok. And kbuild already encodes this information in the cmd files, for the most part (there are corner cases and exceptions which the developers here have gone through great lengths to track down and document in the scripts.) So 99% of the info is there already, which is why the cmd files are used for parsing, no need to re-create that info in yet-another-format, right? Let's stick with a config option for now please. If the distros who will need/want this decide to do it in a different way, they can send patches :) For now, this should be sufficient. It's a build-time output, just like debugging symbols are, and documentation. Ok, documentation is a separate build target, and "to the side" of the source build, but you get the idea :) The SBOM is directly tied to the kernel configuration in that it needs to know the config in order to determine exactly what files were used to generate the resulting binaries. That's what the SBOM is documenting, not "all of the files in the tarball", but just "these are the files that are required to build the binaries". Which is a tiny subset of the overall files in the tree, and is really, all that the target system cares about. thanks, greg k-h
{ "author": "Greg KH <gregkh@linuxfoundation.org>", "date": "Sun, 25 Jan 2026 16:34:46 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Sun, Jan 25, 2026 at 04:33:28PM +0100, Miguel Ojeda wrote: Ick, let's not dump the HUGE sbom json file inside the binary kernel image itself, unless you want to do something like /proc/sbom.gz? That would be funny, but a big waste of memory :) greg k-h
{ "author": "Greg KH <gregkh@linuxfoundation.org>", "date": "Sun, 25 Jan 2026 16:40:52 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
On Sun, Jan 25, 2026 at 4:34 PM Greg KH <gregkh@linuxfoundation.org> wrote: Oof... So you really meant tracing the builder. :) Yeah, I am aware -- I mentioned both sides to explain the upsides and my worry about hardcoding all this stuff out of band. Well, Make can ""do"" things like that, in the sense that we can program it, which is essentially what Kbuild does -- it "hacks" the usual Make graph to do extra stuff on top. i.e. Kbuild and friends are the ones writing the `.cmd` files and running custom filtering and so on, not Make, and just like we abuse Make to do that, in principle we could encode and output more information (if that would help). To be clear, I am not sure exactly what information it is needed -- when I was Cc'd for the Rust bit, I noticed it was parsing the command line to try to guess more deps (?), which seemed odd and I wondered whether we could provide that (even if it requires additions) so that we don't need to parse those. By "corner cases and exceptions", I assume you mean the hardcoded ones (not the command line parsing), which I hadn't noticed yet. Those aren't really documented from what I can see? It is just the list of cases, which we will also have to maintain. I also see the `.incbin` now, which is even more hardcoding, but I see Makefiles explicitly adding the dependency on their side, which is closer to what I am saying: that it would be better to add the dependencies (or whatever information is needed) in the build system side. In other words, we could make those generate a `.cmd` file or similar, rather than hardcode it on the script. I guess my question to Luis et al. is: for things like `.incbin` and the hardcoded dependencies, is there a reason to avoid declaring any missing dependencies or to generate the `.cmd` files to begin with? The patches say, for instance: Some files in the kernel build process are not tracked by the .cmd dependency mechanism. Parsing these dependencies programmatically is too complex for the scope of this project. Therefore, this function provides manually defined dependencies to be added to the build graph. And my point is precisely that we should not be parsing Makefiles, but neither command lines, if at all possible. Instead, if there are missing dependencies, we should fix them; and if there are missing `.cmd`s (i.e. dependency information not saved) you need, we could add those, and so on. Yeah, the extra information may be just in `deps_` in the `.cmd`, or it could be an extra variable there or whatever is needed, i.e. no need for a new format. i.e. what I was trying to avoid was the out-of-band hardcoding as much as possible. In case it wasn't clear: for the config bit, it wouldn't be a big change -- it would just require removing ~10 lines unless I am missing something. But if this was already discussed with users or you think it will be easier etc., then fine, I won't press. :) Just in case: debugging symbols are different -- they change the actual build (e.g. flags), and even the actual image (unless requested to be separate). So those make sense as a config option. (We also have other targets that work like docs, i.e. it is not just docs. But fine... :) To clarify, I didn't suggest we document the files in the tarball, nor that the kernel config doesn't influence the SBOM contents. What I am saying is that whether an SBOM is generated or not is orthogonal to the kernel configuration, and as a user I would have expected to be able to obtain one in my build without having to change any configuration. I hope that helps. Cheers, Miguel
{ "author": "Miguel Ojeda <miguel.ojeda.sandonis@gmail.com>", "date": "Sun, 25 Jan 2026 18:24:51 +0100", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v2 00/14] Add SPDX SBOM generation tool
This patch series introduces a Python-based tool for generating SBOM documents in the SPDX 3.0.1 format for kernel builds. A Software Bill of Materials (SBOM) describes the individual components of a software product. For the kernel, the goal is to describe the distributable build outputs (typically the kernel image and modules), the source files involved in producing these outputs, and the build process that connects the source and output files. To achieve this, the SBOM tool generates three SPDX documents: - sbom-output.spdx.json Describes the final build outputs together with high-level build metadata. - sbom-source.spdx.json Describes all source files involved in the build, including licensing information and additional file metadata. - sbom-build.spdx.json Describes the entire build process, linking source files from the source SBOM to output files in the output SBOM. The sbom tool is optional and runs only when CONFIG_SBOM is enabled. It is invoked after the build, once all output artifacts have been generated. Starting from the kernel image and modules as root nodes, the tool reconstructs the dependency graph up to the original source files. Build dependencies are primarily derived from the .cmd files generated by Kbuild, which record the full command used to build each output file. Currently, the tool only supports x86 and arm64 architectures. Co-developed-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Maximilian Huber <maximilian.huber@tngtech.com> Signed-off-by: Luis Augenstein <luis.augenstein@tngtech.com> --- Changes in v2: - regenerate sbom documents when build configuration changes --- Luis Augenstein (14): tools/sbom: integrate tool in make process tools/sbom: setup sbom logging tools/sbom: add command parsers tools/sbom: add cmd graph generation tools/sbom: add additional dependency sources for cmd graph tools/sbom: add SPDX classes tools/sbom: add JSON-LD serialization tools/sbom: add shared SPDX elements tools/sbom: collect file metadata tools/sbom: add SPDX output graph tools/sbom: add SPDX source graph tools/sbom: add SPDX build graph tools/sbom: add unit tests for command parsers tools/sbom: add unit tests for SPDX-License-Identifier parsing .gitignore | 1 + MAINTAINERS | 6 + Makefile | 15 +- lib/Kconfig.debug | 9 + tools/Makefile | 3 +- tools/sbom/Makefile | 42 ++ tools/sbom/README | 208 ++++++ tools/sbom/sbom.py | 129 ++++ tools/sbom/sbom/__init__.py | 0 tools/sbom/sbom/cmd_graph/__init__.py | 7 + tools/sbom/sbom/cmd_graph/cmd_file.py | 149 ++++ tools/sbom/sbom/cmd_graph/cmd_graph.py | 46 ++ tools/sbom/sbom/cmd_graph/cmd_graph_node.py | 142 ++++ tools/sbom/sbom/cmd_graph/deps_parser.py | 52 ++ .../sbom/cmd_graph/hardcoded_dependencies.py | 83 +++ tools/sbom/sbom/cmd_graph/incbin_parser.py | 42 ++ tools/sbom/sbom/cmd_graph/savedcmd_parser.py | 664 ++++++++++++++++++ tools/sbom/sbom/config.py | 335 +++++++++ tools/sbom/sbom/environment.py | 164 +++++ tools/sbom/sbom/path_utils.py | 11 + tools/sbom/sbom/sbom_logging.py | 88 +++ tools/sbom/sbom/spdx/__init__.py | 7 + tools/sbom/sbom/spdx/build.py | 17 + tools/sbom/sbom/spdx/core.py | 182 +++++ tools/sbom/sbom/spdx/serialization.py | 56 ++ tools/sbom/sbom/spdx/simplelicensing.py | 20 + tools/sbom/sbom/spdx/software.py | 71 ++ tools/sbom/sbom/spdx/spdxId.py | 36 + tools/sbom/sbom/spdx_graph/__init__.py | 7 + .../sbom/sbom/spdx_graph/build_spdx_graphs.py | 82 +++ tools/sbom/sbom/spdx_graph/kernel_file.py | 310 ++++++++ .../sbom/spdx_graph/shared_spdx_elements.py | 32 + .../sbom/sbom/spdx_graph/spdx_build_graph.py | 317 +++++++++ .../sbom/sbom/spdx_graph/spdx_graph_model.py | 36 + .../sbom/sbom/spdx_graph/spdx_output_graph.py | 188 +++++ .../sbom/sbom/spdx_graph/spdx_source_graph.py | 126 ++++ tools/sbom/tests/__init__.py | 0 tools/sbom/tests/cmd_graph/__init__.py | 0 .../tests/cmd_graph/test_savedcmd_parser.py | 383 ++++++++++ tools/sbom/tests/spdx_graph/__init__.py | 0 .../sbom/tests/spdx_graph/test_kernel_file.py | 32 + 41 files changed, 4096 insertions(+), 2 deletions(-) create mode 100644 tools/sbom/Makefile create mode 100644 tools/sbom/README create mode 100644 tools/sbom/sbom.py create mode 100644 tools/sbom/sbom/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/__init__.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_file.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph.py create mode 100644 tools/sbom/sbom/cmd_graph/cmd_graph_node.py create mode 100644 tools/sbom/sbom/cmd_graph/deps_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/hardcoded_dependencies.py create mode 100644 tools/sbom/sbom/cmd_graph/incbin_parser.py create mode 100644 tools/sbom/sbom/cmd_graph/savedcmd_parser.py create mode 100644 tools/sbom/sbom/config.py create mode 100644 tools/sbom/sbom/environment.py create mode 100644 tools/sbom/sbom/path_utils.py create mode 100644 tools/sbom/sbom/sbom_logging.py create mode 100644 tools/sbom/sbom/spdx/__init__.py create mode 100644 tools/sbom/sbom/spdx/build.py create mode 100644 tools/sbom/sbom/spdx/core.py create mode 100644 tools/sbom/sbom/spdx/serialization.py create mode 100644 tools/sbom/sbom/spdx/simplelicensing.py create mode 100644 tools/sbom/sbom/spdx/software.py create mode 100644 tools/sbom/sbom/spdx/spdxId.py create mode 100644 tools/sbom/sbom/spdx_graph/__init__.py create mode 100644 tools/sbom/sbom/spdx_graph/build_spdx_graphs.py create mode 100644 tools/sbom/sbom/spdx_graph/kernel_file.py create mode 100644 tools/sbom/sbom/spdx_graph/shared_spdx_elements.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_build_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_graph_model.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_output_graph.py create mode 100644 tools/sbom/sbom/spdx_graph/spdx_source_graph.py create mode 100644 tools/sbom/tests/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/__init__.py create mode 100644 tools/sbom/tests/cmd_graph/test_savedcmd_parser.py create mode 100644 tools/sbom/tests/spdx_graph/__init__.py create mode 100644 tools/sbom/tests/spdx_graph/test_kernel_file.py -- 2.34.1
Hi Luis, Greg, and Miguel, Sorry for not having any input up until this point, as I felt this was not going to be ready for 6.20/7.0 and I wanted to focus on getting things ready for that release (on top of other work). Some high level comments based on what has been discussed so far to follow, it was going to be hard to reply inline to everything. I will try to take a closer look at v3 in the next couple of weeks but I might not get to it until after the merge window closes. I agree with Miguel that if there is any information that we can add to the .cmd files or another file generated by Kbuild to avoid hard coding things while preprocessing, it should be pursued, as we should be making the build system work for us. We have already some prior art with post processing Kbuild files like scripts/clang-tools/gen_compile_commands.py so I am not too worried about that. At the same time, I do like how self contained the implementation currently is, as it is just there available for people to use if they want it but it impacts nothing if it is not being used. It also makes it an easier maintenance burden in the immediate term, as I would like this to be shown as useful to various entities before it starts to entangle itself into the build system. I think getting rid of CONFIG_SBOM in favor of just an sbom make target is a good direction. If we really wanted some sort of configuration option, I think it should only mean "generate an SBOM by default" and nothing more but I worry about this getting turned on via compile testing and causing issues. At that point, it feels like whatever entity wants this information can just add 'make sbom' to their build system since they may have to control the outputs beyond the simple "all" make target. I wonder if it would be better for this to live within scripts/ instead of tools/, as that should allow it to be integrated into the build process a little bit more naturally, such as using $(Q) instead of @, $(PYTHON3) instead of the bare python3, being able to access CONFIG_MODULES directly, and cleaning up the actual implementation of the sbom target in Makefile. Cheers, Nathan
{ "author": "Nathan Chancellor <nathan@kernel.org>", "date": "Tue, 27 Jan 2026 16:10:37 -0700", "thread_id": "6ed0fe99-3724-40c2-8d98-3309a3cf0104@tngtech.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The "qup-memory" interconnect path is optional and may not be defined in all device trees. Unroll the loop-based ICC path initialization to allow specific error handling for each path type. The "qup-core" and "qup-config" paths remain mandatory and will fail probe if missing, while "qup-memory" is now handled as optional and skipped when not present in the device tree. Co-developed-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com> Signed-off-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v1->v2: Bjorn: - Updated commit text. - Used local variable for more readable. --- drivers/soc/qcom/qcom-geni-se.c | 36 +++++++++++++++++---------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index cd1779b6a91a..b6167b968ef6 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -899,30 +899,32 @@ EXPORT_SYMBOL_GPL(geni_se_rx_dma_unprep); int geni_icc_get(struct geni_se *se, const char *icc_ddr) { - int i, err; - const char *icc_names[] = {"qup-core", "qup-config", icc_ddr}; + struct geni_icc_path *icc_paths = se->icc_paths; if (has_acpi_companion(se->dev)) return 0; - for (i = 0; i < ARRAY_SIZE(se->icc_paths); i++) { - if (!icc_names[i]) - continue; - - se->icc_paths[i].path = devm_of_icc_get(se->dev, icc_names[i]); - if (IS_ERR(se->icc_paths[i].path)) - goto err; + icc_paths[GENI_TO_CORE].path = devm_of_icc_get(se->dev, "qup-core"); + if (IS_ERR(icc_paths[GENI_TO_CORE].path)) + return dev_err_probe(se->dev, PTR_ERR(icc_paths[GENI_TO_CORE].path), + "Failed to get 'qup-core' ICC path\n"); + + icc_paths[CPU_TO_GENI].path = devm_of_icc_get(se->dev, "qup-config"); + if (IS_ERR(icc_paths[CPU_TO_GENI].path)) + return dev_err_probe(se->dev, PTR_ERR(icc_paths[CPU_TO_GENI].path), + "Failed to get 'qup-config' ICC path\n"); + + /* The DDR path is optional, depending on protocol and hw capabilities */ + icc_paths[GENI_TO_DDR].path = devm_of_icc_get(se->dev, "qup-memory"); + if (IS_ERR(icc_paths[GENI_TO_DDR].path)) { + if (PTR_ERR(icc_paths[GENI_TO_DDR].path) == -ENODATA) + icc_paths[GENI_TO_DDR].path = NULL; + else + return dev_err_probe(se->dev, PTR_ERR(icc_paths[GENI_TO_DDR].path), + "Failed to get 'qup-memory' ICC path\n"); } return 0; - -err: - err = PTR_ERR(se->icc_paths[i].path); - if (err != -EPROBE_DEFER) - dev_err_ratelimited(se->dev, "Failed to get ICC path '%s': %d\n", - icc_names[i], err); - return err; - } EXPORT_SYMBOL_GPL(geni_icc_get); -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:10 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Add a new function geni_icc_set_bw_ab() that allows callers to set average bandwidth values for all ICC (Interconnect) paths in a single call. This function takes separate parameters for core, config, and DDR average bandwidth values and applies them to the respective ICC paths. This provides a more convenient API for drivers that need to configure specific average bandwidth values. Co-developed-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com> Signed-off-by: Konrad Dybcio <konrad.dybcio@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- drivers/soc/qcom/qcom-geni-se.c | 22 ++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 1 + 2 files changed, 23 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index b6167b968ef6..b0542f836453 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -946,6 +946,28 @@ int geni_icc_set_bw(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_icc_set_bw); +/** + * geni_icc_set_bw_ab() - Set average bandwidth for all ICC paths and apply + * @se: Pointer to the concerned serial engine. + * @core_ab: Average bandwidth in kBps for GENI_TO_CORE path. + * @cfg_ab: Average bandwidth in kBps for CPU_TO_GENI path. + * @ddr_ab: Average bandwidth in kBps for GENI_TO_DDR path. + * + * Sets bandwidth values for all ICC paths and applies them. DDR path is + * optional and only set if it exists. + * + * Return: 0 on success, negative error code on failure. + */ +int geni_icc_set_bw_ab(struct geni_se *se, u32 core_ab, u32 cfg_ab, u32 ddr_ab) +{ + se->icc_paths[GENI_TO_CORE].avg_bw = core_ab; + se->icc_paths[CPU_TO_GENI].avg_bw = cfg_ab; + se->icc_paths[GENI_TO_DDR].avg_bw = ddr_ab; + + return geni_icc_set_bw(se); +} +EXPORT_SYMBOL_GPL(geni_icc_set_bw_ab); + void geni_icc_set_tag(struct geni_se *se, u32 tag) { int i; diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index 0a984e2579fe..980aabea2157 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -528,6 +528,7 @@ void geni_se_rx_dma_unprep(struct geni_se *se, dma_addr_t iova, size_t len); int geni_icc_get(struct geni_se *se, const char *icc_ddr); int geni_icc_set_bw(struct geni_se *se); +int geni_icc_set_bw_ab(struct geni_se *se, u32 core_ab, u32 cfg_ab, u32 ddr_ab); void geni_icc_set_tag(struct geni_se *se, u32 tag); int geni_icc_enable(struct geni_se *se); -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:11 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The GENI Serial Engine drivers (I2C, SPI, and SERIAL) currently duplicate code for initializing shared resources such as clocks and interconnect paths. Introduce a new helper API, geni_se_resources_init(), to centralize this initialization logic, improving modularity and simplifying the probe function. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v1 -> v2: - Updated proper return value for devm_pm_opp_set_clkname() --- drivers/soc/qcom/qcom-geni-se.c | 47 ++++++++++++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 6 ++++ 2 files changed, 53 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index b0542f836453..75e722cd1a94 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -19,6 +19,7 @@ #include <linux/of_platform.h> #include <linux/pinctrl/consumer.h> #include <linux/platform_device.h> +#include <linux/pm_opp.h> #include <linux/soc/qcom/geni-se.h> /** @@ -1012,6 +1013,52 @@ int geni_icc_disable(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_icc_disable); +/** + * geni_se_resources_init() - Initialize resources for a GENI SE device. + * @se: Pointer to the geni_se structure representing the GENI SE device. + * + * This function initializes various resources required by the GENI Serial Engine + * (SE) device, including clock resources (core and SE clocks), interconnect + * paths for communication. + * It retrieves optional and mandatory clock resources, adds an OF-based + * operating performance point (OPP) table, and sets up interconnect paths + * with default bandwidths. The function also sets a flag (`has_opp`) to + * indicate whether OPP support is available for the device. + * + * Return: 0 on success, or a negative errno on failure. + */ +int geni_se_resources_init(struct geni_se *se) +{ + int ret; + + se->core_clk = devm_clk_get_optional(se->dev, "core"); + if (IS_ERR(se->core_clk)) + return dev_err_probe(se->dev, PTR_ERR(se->core_clk), + "Failed to get optional core clk\n"); + + se->clk = devm_clk_get(se->dev, "se"); + if (IS_ERR(se->clk) && !has_acpi_companion(se->dev)) + return dev_err_probe(se->dev, PTR_ERR(se->clk), + "Failed to get SE clk\n"); + + ret = devm_pm_opp_set_clkname(se->dev, "se"); + if (ret) + return ret; + + ret = devm_pm_opp_of_add_table(se->dev); + if (ret && ret != -ENODEV) + return dev_err_probe(se->dev, ret, "Failed to add OPP table\n"); + + se->has_opp = (ret == 0); + + ret = geni_icc_get(se, "qup-memory"); + if (ret) + return ret; + + return geni_icc_set_bw_ab(se, GENI_DEFAULT_BW, GENI_DEFAULT_BW, GENI_DEFAULT_BW); +} +EXPORT_SYMBOL_GPL(geni_se_resources_init); + /** * geni_find_protocol_fw() - Locate and validate SE firmware for a protocol. * @dev: Pointer to the device structure. diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index 980aabea2157..c182dd0f0bde 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -60,18 +60,22 @@ struct geni_icc_path { * @dev: Pointer to the Serial Engine device * @wrapper: Pointer to the parent QUP Wrapper core * @clk: Handle to the core serial engine clock + * @core_clk: Auxiliary clock, which may be required by a protocol * @num_clk_levels: Number of valid clock levels in clk_perf_tbl * @clk_perf_tbl: Table of clock frequency input to serial engine clock * @icc_paths: Array of ICC paths for SE + * @has_opp: Indicates if OPP is supported */ struct geni_se { void __iomem *base; struct device *dev; struct geni_wrapper *wrapper; struct clk *clk; + struct clk *core_clk; unsigned int num_clk_levels; unsigned long *clk_perf_tbl; struct geni_icc_path icc_paths[3]; + bool has_opp; }; /* Common SE registers */ @@ -535,6 +539,8 @@ int geni_icc_enable(struct geni_se *se); int geni_icc_disable(struct geni_se *se); +int geni_se_resources_init(struct geni_se *se); + int geni_load_se_firmware(struct geni_se *se, enum geni_se_protocol_type protocol); #endif #endif -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:12 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Currently, core clk is handled individually in protocol drivers like the I2C driver. Move this clock management to the common clock APIs (geni_se_clks_on/off) that are already present in the common GENI SE driver to maintain consistency across all protocol drivers. Core clk is now properly managed alongside the other clocks (se->clk and wrapper clocks) in the fundamental clock control functions, eliminating the need for individual protocol drivers to handle this clock separately. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- drivers/soc/qcom/qcom-geni-se.c | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index 75e722cd1a94..2e41595ff912 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -583,6 +583,7 @@ static void geni_se_clks_off(struct geni_se *se) clk_disable_unprepare(se->clk); clk_bulk_disable_unprepare(wrapper->num_clks, wrapper->clks); + clk_disable_unprepare(se->core_clk); } /** @@ -619,7 +620,18 @@ static int geni_se_clks_on(struct geni_se *se) ret = clk_prepare_enable(se->clk); if (ret) - clk_bulk_disable_unprepare(wrapper->num_clks, wrapper->clks); + goto err_bulk_clks; + + ret = clk_prepare_enable(se->core_clk); + if (ret) + goto err_se_clk; + + return 0; + +err_se_clk: + clk_disable_unprepare(se->clk); +err_bulk_clks: + clk_bulk_disable_unprepare(wrapper->num_clks, wrapper->clks); return ret; } -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:13 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The GENI SE protocol drivers (I2C, SPI, UART) implement similar resource activation/deactivation sequences independently, leading to code duplication. Introduce geni_se_resources_activate()/geni_se_resources_deactivate() to power on/off resources.The activate function enables ICC, clocks, and TLMM whereas the deactivate function disables resources in reverse order including OPP rate reset, clocks, ICC and TLMM. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3 -> v4 Konrad - Removed core clk. v2 -> v3 - Added export symbol for new APIs. v1 -> v2 Bjorn - Updated commit message based code changes. - Removed geni_se_resource_state() API. - Utilized code snippet from geni_se_resources_off() --- drivers/soc/qcom/qcom-geni-se.c | 67 ++++++++++++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 4 ++ 2 files changed, 71 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index 2e41595ff912..17ab5bbeb621 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -1025,6 +1025,73 @@ int geni_icc_disable(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_icc_disable); +/** + * geni_se_resources_deactivate() - Deactivate GENI SE device resources + * @se: Pointer to the geni_se structure + * + * Deactivates device resources for power saving: OPP rate to 0, pin control + * to sleep state, turns off clocks, and disables interconnect. Skips ACPI devices. + * + * Return: 0 on success, negative error code on failure + */ +int geni_se_resources_deactivate(struct geni_se *se) +{ + int ret; + + if (has_acpi_companion(se->dev)) + return 0; + + if (se->has_opp) + dev_pm_opp_set_rate(se->dev, 0); + + ret = pinctrl_pm_select_sleep_state(se->dev); + if (ret) + return ret; + + geni_se_clks_off(se); + + return geni_icc_disable(se); +} +EXPORT_SYMBOL_GPL(geni_se_resources_deactivate); + +/** + * geni_se_resources_activate() - Activate GENI SE device resources + * @se: Pointer to the geni_se structure + * + * Activates device resources for operation: enables interconnect, prepares clocks, + * and sets pin control to default state. Includes error cleanup. Skips ACPI devices. + * + * Return: 0 on success, negative error code on failure + */ +int geni_se_resources_activate(struct geni_se *se) +{ + int ret; + + if (has_acpi_companion(se->dev)) + return 0; + + ret = geni_icc_enable(se); + if (ret) + return ret; + + ret = geni_se_clks_on(se); + if (ret) + goto out_icc_disable; + + ret = pinctrl_pm_select_default_state(se->dev); + if (ret) { + geni_se_clks_off(se); + goto out_icc_disable; + } + + return ret; + +out_icc_disable: + geni_icc_disable(se); + return ret; +} +EXPORT_SYMBOL_GPL(geni_se_resources_activate); + /** * geni_se_resources_init() - Initialize resources for a GENI SE device. * @se: Pointer to the geni_se structure representing the GENI SE device. diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index c182dd0f0bde..36a68149345c 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -541,6 +541,10 @@ int geni_icc_disable(struct geni_se *se); int geni_se_resources_init(struct geni_se *se); +int geni_se_resources_activate(struct geni_se *se); + +int geni_se_resources_deactivate(struct geni_se *se); + int geni_load_se_firmware(struct geni_se *se, enum geni_se_protocol_type protocol); #endif #endif -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:14 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The GENI Serial Engine drivers (I2C, SPI, and SERIAL) currently handle the attachment of power domains. This often leads to duplicated code logic across different driver probe functions. Introduce a new helper API, geni_se_domain_attach(), to centralize the logic for attaching "power" and "perf" domains to the GENI SE device. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4 Konrad - Updated function documentation --- drivers/soc/qcom/qcom-geni-se.c | 29 +++++++++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 4 ++++ 2 files changed, 33 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index 17ab5bbeb621..d80ae6c36582 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -19,6 +19,7 @@ #include <linux/of_platform.h> #include <linux/pinctrl/consumer.h> #include <linux/platform_device.h> +#include <linux/pm_domain.h> #include <linux/pm_opp.h> #include <linux/soc/qcom/geni-se.h> @@ -1092,6 +1093,34 @@ int geni_se_resources_activate(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_se_resources_activate); +/** + * geni_se_domain_attach() - Attach power domains to a GENI SE device. + * @se: Pointer to the geni_se structure representing the GENI SE device. + * + * This function attaches the power domains ("power" and "perf") required + * in the SCMI auto-VM environment to the GENI Serial Engine device. It + * initializes se->pd_list with the attached domains. + * + * Return: 0 on success, or a negative error code on failure. + */ +int geni_se_domain_attach(struct geni_se *se) +{ + struct dev_pm_domain_attach_data pd_data = { + .pd_flags = PD_FLAG_DEV_LINK_ON, + .pd_names = (const char*[]) { "power", "perf" }, + .num_pd_names = 2, + }; + int ret; + + ret = dev_pm_domain_attach_list(se->dev, + &pd_data, &se->pd_list); + if (ret <= 0) + return -EINVAL; + + return 0; +} +EXPORT_SYMBOL_GPL(geni_se_domain_attach); + /** * geni_se_resources_init() - Initialize resources for a GENI SE device. * @se: Pointer to the geni_se structure representing the GENI SE device. diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index 36a68149345c..5f75159c5531 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -64,6 +64,7 @@ struct geni_icc_path { * @num_clk_levels: Number of valid clock levels in clk_perf_tbl * @clk_perf_tbl: Table of clock frequency input to serial engine clock * @icc_paths: Array of ICC paths for SE + * @pd_list: Power domain list for managing power domains * @has_opp: Indicates if OPP is supported */ struct geni_se { @@ -75,6 +76,7 @@ struct geni_se { unsigned int num_clk_levels; unsigned long *clk_perf_tbl; struct geni_icc_path icc_paths[3]; + struct dev_pm_domain_list *pd_list; bool has_opp; }; @@ -546,5 +548,7 @@ int geni_se_resources_activate(struct geni_se *se); int geni_se_resources_deactivate(struct geni_se *se); int geni_load_se_firmware(struct geni_se *se, enum geni_se_protocol_type protocol); + +int geni_se_domain_attach(struct geni_se *se); #endif #endif -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:15 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The GENI Serial Engine (SE) drivers (I2C, SPI, and SERIAL) currently manage performance levels and operating points directly. This resulting in code duplication across drivers. such as configuring a specific level or find and apply an OPP based on a clock frequency. Introduce two new helper APIs, geni_se_set_perf_level() and geni_se_set_perf_opp(), addresses this issue by providing a streamlined method for the GENI Serial Engine (SE) drivers to find and set the OPP based on the desired performance level, thereby eliminating redundancy. Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- drivers/soc/qcom/qcom-geni-se.c | 50 ++++++++++++++++++++++++++++++++ include/linux/soc/qcom/geni-se.h | 4 +++ 2 files changed, 54 insertions(+) diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index d80ae6c36582..2241d1487031 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -282,6 +282,12 @@ struct se_fw_hdr { #define geni_setbits32(_addr, _v) writel(readl(_addr) | (_v), _addr) #define geni_clrbits32(_addr, _v) writel(readl(_addr) & ~(_v), _addr) +enum domain_idx { + DOMAIN_IDX_POWER, + DOMAIN_IDX_PERF, + DOMAIN_IDX_MAX +}; + /** * geni_se_get_qup_hw_version() - Read the QUP wrapper Hardware version * @se: Pointer to the corresponding serial engine. @@ -1093,6 +1099,50 @@ int geni_se_resources_activate(struct geni_se *se) } EXPORT_SYMBOL_GPL(geni_se_resources_activate); +/** + * geni_se_set_perf_level() - Set performance level for GENI SE. + * @se: Pointer to the struct geni_se instance. + * @level: The desired performance level. + * + * Sets the performance level by directly calling dev_pm_opp_set_level + * on the performance device associated with the SE. + * + * Return: 0 on success, or a negative error code on failure. + */ +int geni_se_set_perf_level(struct geni_se *se, unsigned long level) +{ + return dev_pm_opp_set_level(se->pd_list->pd_devs[DOMAIN_IDX_PERF], level); +} +EXPORT_SYMBOL_GPL(geni_se_set_perf_level); + +/** + * geni_se_set_perf_opp() - Set performance OPP for GENI SE by frequency. + * @se: Pointer to the struct geni_se instance. + * @clk_freq: The requested clock frequency. + * + * Finds the nearest operating performance point (OPP) for the given + * clock frequency and applies it to the SE's performance device. + * + * Return: 0 on success, or a negative error code on failure. + */ +int geni_se_set_perf_opp(struct geni_se *se, unsigned long clk_freq) +{ + struct device *perf_dev = se->pd_list->pd_devs[DOMAIN_IDX_PERF]; + struct dev_pm_opp *opp; + int ret; + + opp = dev_pm_opp_find_freq_floor(perf_dev, &clk_freq); + if (IS_ERR(opp)) { + dev_err(se->dev, "failed to find opp for freq %lu\n", clk_freq); + return PTR_ERR(opp); + } + + ret = dev_pm_opp_set_opp(perf_dev, opp); + dev_pm_opp_put(opp); + return ret; +} +EXPORT_SYMBOL_GPL(geni_se_set_perf_opp); + /** * geni_se_domain_attach() - Attach power domains to a GENI SE device. * @se: Pointer to the geni_se structure representing the GENI SE device. diff --git a/include/linux/soc/qcom/geni-se.h b/include/linux/soc/qcom/geni-se.h index 5f75159c5531..c5e6ab85df09 100644 --- a/include/linux/soc/qcom/geni-se.h +++ b/include/linux/soc/qcom/geni-se.h @@ -550,5 +550,9 @@ int geni_se_resources_deactivate(struct geni_se *se); int geni_load_se_firmware(struct geni_se *se, enum geni_se_protocol_type protocol); int geni_se_domain_attach(struct geni_se *se); + +int geni_se_set_perf_level(struct geni_se *se, unsigned long level); + +int geni_se_set_perf_opp(struct geni_se *se, unsigned long clk_freq); #endif #endif -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:16 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Add DT bindings for the QUP GENI I2C controller on sa8255p platforms. SA8255p platform abstracts resources such as clocks, interconnect and GPIO pins configuration in Firmware. SCMI power and perf protocol are utilized to request resource configurations. SA8255p platform does not require the Serial Engine (SE) common properties as the SE firmware is loaded and managed by the TrustZone (TZ) secure environment. Reviewed-by: Krzysztof Kozlowski <krzysztof.kozlowski@oss.qualcomm.com> Co-developed-by: Nikunj Kela <quic_nkela@quicinc.com> Signed-off-by: Nikunj Kela <quic_nkela@quicinc.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v2->v3: - Added Reviewed-by tag v1->v2: Krzysztof: - Added dma properties in example node - Removed minItems from power-domains property - Added in commit text about common property --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml diff --git a/Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml b/Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml new file mode 100644 index 000000000000..a61e40b5cbc1 --- /dev/null +++ b/Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +%YAML 1.2 +--- +$id: http://devicetree.org/schemas/i2c/qcom,sa8255p-geni-i2c.yaml# +$schema: http://devicetree.org/meta-schemas/core.yaml# + +title: Qualcomm SA8255p QUP GENI I2C Controller + +maintainers: + - Praveen Talari <praveen.talari@oss.qualcomm.com> + +properties: + compatible: + const: qcom,sa8255p-geni-i2c + + reg: + maxItems: 1 + + dmas: + maxItems: 2 + + dma-names: + items: + - const: tx + - const: rx + + interrupts: + maxItems: 1 + + power-domains: + maxItems: 2 + + power-domain-names: + items: + - const: power + - const: perf + +required: + - compatible + - reg + - interrupts + - power-domains + +allOf: + - $ref: /schemas/i2c/i2c-controller.yaml# + +unevaluatedProperties: false + +examples: + - | + #include <dt-bindings/interrupt-controller/arm-gic.h> + #include <dt-bindings/dma/qcom-gpi.h> + + i2c@a90000 { + compatible = "qcom,sa8255p-geni-i2c"; + reg = <0xa90000 0x4000>; + interrupts = <GIC_SPI 357 IRQ_TYPE_LEVEL_HIGH>; + dmas = <&gpi_dma0 0 0 QCOM_GPI_I2C>, + <&gpi_dma0 1 0 QCOM_GPI_I2C>; + dma-names = "tx", "rx"; + power-domains = <&scmi0_pd 0>, <&scmi0_dvfs 0>; + power-domain-names = "power", "perf"; + }; +... -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:17 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Moving the serial engine setup to geni_i2c_init() API for a cleaner probe function and utilizes the PM runtime API to control resources instead of direct clock-related APIs for better resource management. Enables reusability of the serial engine initialization like hibernation and deep sleep features where hardware context is lost. Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4: viken: - Added Acked-by tag - Removed extra space before invoke of geni_i2c_init(). v1->v2: Bjorn: - Updated commit text. --- drivers/i2c/busses/i2c-qcom-geni.c | 158 ++++++++++++++--------------- 1 file changed, 75 insertions(+), 83 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index ae609bdd2ec4..81ed1596ac9f 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -977,10 +977,77 @@ static int setup_gpi_dma(struct geni_i2c_dev *gi2c) return ret; } +static int geni_i2c_init(struct geni_i2c_dev *gi2c) +{ + const struct geni_i2c_desc *desc = NULL; + u32 proto, tx_depth; + bool fifo_disable; + int ret; + + ret = pm_runtime_resume_and_get(gi2c->se.dev); + if (ret < 0) { + dev_err(gi2c->se.dev, "error turning on device :%d\n", ret); + return ret; + } + + proto = geni_se_read_proto(&gi2c->se); + if (proto == GENI_SE_INVALID_PROTO) { + ret = geni_load_se_firmware(&gi2c->se, GENI_SE_I2C); + if (ret) { + dev_err_probe(gi2c->se.dev, ret, "i2c firmware load failed ret: %d\n", ret); + goto err; + } + } else if (proto != GENI_SE_I2C) { + ret = dev_err_probe(gi2c->se.dev, -ENXIO, "Invalid proto %d\n", proto); + goto err; + } + + desc = device_get_match_data(gi2c->se.dev); + if (desc && desc->no_dma_support) { + fifo_disable = false; + gi2c->no_dma = true; + } else { + fifo_disable = readl_relaxed(gi2c->se.base + GENI_IF_DISABLE_RO) & FIFO_IF_DISABLE; + } + + if (fifo_disable) { + /* FIFO is disabled, so we can only use GPI DMA */ + gi2c->gpi_mode = true; + ret = setup_gpi_dma(gi2c); + if (ret) + goto err; + + dev_dbg(gi2c->se.dev, "Using GPI DMA mode for I2C\n"); + } else { + gi2c->gpi_mode = false; + tx_depth = geni_se_get_tx_fifo_depth(&gi2c->se); + + /* I2C Master Hub Serial Elements doesn't have the HW_PARAM_0 register */ + if (!tx_depth && desc) + tx_depth = desc->tx_fifo_depth; + + if (!tx_depth) { + ret = dev_err_probe(gi2c->se.dev, -EINVAL, + "Invalid TX FIFO depth\n"); + goto err; + } + + gi2c->tx_wm = tx_depth - 1; + geni_se_init(&gi2c->se, gi2c->tx_wm, tx_depth); + geni_se_config_packing(&gi2c->se, BITS_PER_BYTE, + PACKING_BYTES_PW, true, true, true); + + dev_dbg(gi2c->se.dev, "i2c fifo/se-dma mode. fifo depth:%d\n", tx_depth); + } + +err: + pm_runtime_put(gi2c->se.dev); + return ret; +} + static int geni_i2c_probe(struct platform_device *pdev) { struct geni_i2c_dev *gi2c; - u32 proto, tx_depth, fifo_disable; int ret; struct device *dev = &pdev->dev; const struct geni_i2c_desc *desc = NULL; @@ -1060,102 +1127,27 @@ static int geni_i2c_probe(struct platform_device *pdev) if (ret) return ret; - ret = clk_prepare_enable(gi2c->core_clk); - if (ret) - return ret; - - ret = geni_se_resources_on(&gi2c->se); - if (ret) { - dev_err_probe(dev, ret, "Error turning on resources\n"); - goto err_clk; - } - proto = geni_se_read_proto(&gi2c->se); - if (proto == GENI_SE_INVALID_PROTO) { - ret = geni_load_se_firmware(&gi2c->se, GENI_SE_I2C); - if (ret) { - dev_err_probe(dev, ret, "i2c firmware load failed ret: %d\n", ret); - goto err_resources; - } - } else if (proto != GENI_SE_I2C) { - ret = dev_err_probe(dev, -ENXIO, "Invalid proto %d\n", proto); - goto err_resources; - } - - if (desc && desc->no_dma_support) { - fifo_disable = false; - gi2c->no_dma = true; - } else { - fifo_disable = readl_relaxed(gi2c->se.base + GENI_IF_DISABLE_RO) & FIFO_IF_DISABLE; - } - - if (fifo_disable) { - /* FIFO is disabled, so we can only use GPI DMA */ - gi2c->gpi_mode = true; - ret = setup_gpi_dma(gi2c); - if (ret) - goto err_resources; - - dev_dbg(dev, "Using GPI DMA mode for I2C\n"); - } else { - gi2c->gpi_mode = false; - tx_depth = geni_se_get_tx_fifo_depth(&gi2c->se); - - /* I2C Master Hub Serial Elements doesn't have the HW_PARAM_0 register */ - if (!tx_depth && desc) - tx_depth = desc->tx_fifo_depth; - - if (!tx_depth) { - ret = dev_err_probe(dev, -EINVAL, - "Invalid TX FIFO depth\n"); - goto err_resources; - } - - gi2c->tx_wm = tx_depth - 1; - geni_se_init(&gi2c->se, gi2c->tx_wm, tx_depth); - geni_se_config_packing(&gi2c->se, BITS_PER_BYTE, - PACKING_BYTES_PW, true, true, true); - - dev_dbg(dev, "i2c fifo/se-dma mode. fifo depth:%d\n", tx_depth); - } - - clk_disable_unprepare(gi2c->core_clk); - ret = geni_se_resources_off(&gi2c->se); - if (ret) { - dev_err_probe(dev, ret, "Error turning off resources\n"); - goto err_dma; - } - - ret = geni_icc_disable(&gi2c->se); - if (ret) - goto err_dma; - gi2c->suspended = 1; pm_runtime_set_suspended(gi2c->se.dev); pm_runtime_set_autosuspend_delay(gi2c->se.dev, I2C_AUTO_SUSPEND_DELAY); pm_runtime_use_autosuspend(gi2c->se.dev); pm_runtime_enable(gi2c->se.dev); + ret = geni_i2c_init(gi2c); + if (ret < 0) { + pm_runtime_disable(gi2c->se.dev); + return ret; + } + ret = i2c_add_adapter(&gi2c->adap); if (ret) { dev_err_probe(dev, ret, "Error adding i2c adapter\n"); pm_runtime_disable(gi2c->se.dev); - goto err_dma; + return ret; } dev_dbg(dev, "Geni-I2C adaptor successfully added\n"); - return ret; - -err_resources: - geni_se_resources_off(&gi2c->se); -err_clk: - clk_disable_unprepare(gi2c->core_clk); - - return ret; - -err_dma: - release_gpi_dma(gi2c); - return ret; } -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:18 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
Refactor the resource initialization in geni_i2c_probe() by introducing a new geni_i2c_resources_init() function and utilizing the common geni_se_resources_init() framework and clock frequency mapping, making the probe function cleaner. Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4: - Added Acked-by tag. v1->v2: - Updated commit text. --- drivers/i2c/busses/i2c-qcom-geni.c | 53 ++++++++++++------------------ 1 file changed, 21 insertions(+), 32 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index 81ed1596ac9f..56eebefda75f 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -1045,6 +1045,23 @@ static int geni_i2c_init(struct geni_i2c_dev *gi2c) return ret; } +static int geni_i2c_resources_init(struct geni_i2c_dev *gi2c) +{ + int ret; + + ret = geni_se_resources_init(&gi2c->se); + if (ret) + return ret; + + ret = geni_i2c_clk_map_idx(gi2c); + if (ret) + return dev_err_probe(gi2c->se.dev, ret, "Invalid clk frequency %d Hz\n", + gi2c->clk_freq_out); + + return geni_icc_set_bw_ab(&gi2c->se, GENI_DEFAULT_BW, GENI_DEFAULT_BW, + Bps_to_icc(gi2c->clk_freq_out)); +} + static int geni_i2c_probe(struct platform_device *pdev) { struct geni_i2c_dev *gi2c; @@ -1064,16 +1081,6 @@ static int geni_i2c_probe(struct platform_device *pdev) desc = device_get_match_data(&pdev->dev); - if (desc && desc->has_core_clk) { - gi2c->core_clk = devm_clk_get(dev, "core"); - if (IS_ERR(gi2c->core_clk)) - return PTR_ERR(gi2c->core_clk); - } - - gi2c->se.clk = devm_clk_get(dev, "se"); - if (IS_ERR(gi2c->se.clk) && !has_acpi_companion(dev)) - return PTR_ERR(gi2c->se.clk); - ret = device_property_read_u32(dev, "clock-frequency", &gi2c->clk_freq_out); if (ret) { @@ -1088,16 +1095,15 @@ static int geni_i2c_probe(struct platform_device *pdev) if (gi2c->irq < 0) return gi2c->irq; - ret = geni_i2c_clk_map_idx(gi2c); - if (ret) - return dev_err_probe(dev, ret, "Invalid clk frequency %d Hz\n", - gi2c->clk_freq_out); - gi2c->adap.algo = &geni_i2c_algo; init_completion(&gi2c->done); spin_lock_init(&gi2c->lock); platform_set_drvdata(pdev, gi2c); + ret = geni_i2c_resources_init(gi2c); + if (ret) + return ret; + /* Keep interrupts disabled initially to allow for low-power modes */ ret = devm_request_irq(dev, gi2c->irq, geni_i2c_irq, IRQF_NO_AUTOEN, dev_name(dev), gi2c); @@ -1110,23 +1116,6 @@ static int geni_i2c_probe(struct platform_device *pdev) gi2c->adap.dev.of_node = dev->of_node; strscpy(gi2c->adap.name, "Geni-I2C", sizeof(gi2c->adap.name)); - ret = geni_icc_get(&gi2c->se, desc ? desc->icc_ddr : "qup-memory"); - if (ret) - return ret; - /* - * Set the bus quota for core and cpu to a reasonable value for - * register access. - * Set quota for DDR based on bus speed. - */ - gi2c->se.icc_paths[GENI_TO_CORE].avg_bw = GENI_DEFAULT_BW; - gi2c->se.icc_paths[CPU_TO_GENI].avg_bw = GENI_DEFAULT_BW; - if (!desc || desc->icc_ddr) - gi2c->se.icc_paths[GENI_TO_DDR].avg_bw = Bps_to_icc(gi2c->clk_freq_out); - - ret = geni_icc_set_bw(&gi2c->se); - if (ret) - return ret; - gi2c->suspended = 1; pm_runtime_set_suspended(gi2c->se.dev); pm_runtime_set_autosuspend_delay(gi2c->se.dev, I2C_AUTO_SUSPEND_DELAY); -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:19 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
To manage GENI serial engine resources during runtime power management, drivers currently need to call functions for ICC, clock, and SE resource operations in both suspend and resume paths, resulting in code duplication across drivers. The new geni_se_resources_activate() and geni_se_resources_deactivate() helper APIs addresses this issue by providing a streamlined method to enable or disable all resources based, thereby eliminating redundancy across drivers. Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4: - Added Acked-by tag. v1->v2: Bjorn: - Remove geni_se_resources_state() API. - Used geni_se_resources_activate() and geni_se_resources_deactivate() to enable/disable resources. --- drivers/i2c/busses/i2c-qcom-geni.c | 28 +++++----------------------- 1 file changed, 5 insertions(+), 23 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index 56eebefda75f..4ff84bb0fff5 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -1163,18 +1163,15 @@ static int __maybe_unused geni_i2c_runtime_suspend(struct device *dev) struct geni_i2c_dev *gi2c = dev_get_drvdata(dev); disable_irq(gi2c->irq); - ret = geni_se_resources_off(&gi2c->se); + + ret = geni_se_resources_deactivate(&gi2c->se); if (ret) { enable_irq(gi2c->irq); return ret; - - } else { - gi2c->suspended = 1; } - clk_disable_unprepare(gi2c->core_clk); - - return geni_icc_disable(&gi2c->se); + gi2c->suspended = 1; + return ret; } static int __maybe_unused geni_i2c_runtime_resume(struct device *dev) @@ -1182,28 +1179,13 @@ static int __maybe_unused geni_i2c_runtime_resume(struct device *dev) int ret; struct geni_i2c_dev *gi2c = dev_get_drvdata(dev); - ret = geni_icc_enable(&gi2c->se); + ret = geni_se_resources_activate(&gi2c->se); if (ret) return ret; - ret = clk_prepare_enable(gi2c->core_clk); - if (ret) - goto out_icc_disable; - - ret = geni_se_resources_on(&gi2c->se); - if (ret) - goto out_clk_disable; - enable_irq(gi2c->irq); gi2c->suspended = 0; - return 0; - -out_clk_disable: - clk_disable_unprepare(gi2c->core_clk); -out_icc_disable: - geni_icc_disable(&gi2c->se); - return ret; } -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:20 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
To avoid repeatedly fetching and checking platform data across various functions, store the struct of_device_id data directly in the i2c private structure. This change enhances code maintainability and reduces redundancy. Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4 - Added Acked-by tag. Konrad - Removed icc_ddr from platfrom data struct --- drivers/i2c/busses/i2c-qcom-geni.c | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index 4ff84bb0fff5..8fd62d659c2a 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -77,6 +77,12 @@ enum geni_i2c_err_code { #define XFER_TIMEOUT HZ #define RST_TIMEOUT HZ +struct geni_i2c_desc { + bool has_core_clk; + bool no_dma_support; + unsigned int tx_fifo_depth; +}; + #define QCOM_I2C_MIN_NUM_OF_MSGS_MULTI_DESC 2 /** @@ -122,13 +128,7 @@ struct geni_i2c_dev { bool is_tx_multi_desc_xfer; u32 num_msgs; struct geni_i2c_gpi_multi_desc_xfer i2c_multi_desc_config; -}; - -struct geni_i2c_desc { - bool has_core_clk; - char *icc_ddr; - bool no_dma_support; - unsigned int tx_fifo_depth; + const struct geni_i2c_desc *dev_data; }; struct geni_i2c_err_log { @@ -979,7 +979,6 @@ static int setup_gpi_dma(struct geni_i2c_dev *gi2c) static int geni_i2c_init(struct geni_i2c_dev *gi2c) { - const struct geni_i2c_desc *desc = NULL; u32 proto, tx_depth; bool fifo_disable; int ret; @@ -1002,8 +1001,7 @@ static int geni_i2c_init(struct geni_i2c_dev *gi2c) goto err; } - desc = device_get_match_data(gi2c->se.dev); - if (desc && desc->no_dma_support) { + if (gi2c->dev_data->no_dma_support) { fifo_disable = false; gi2c->no_dma = true; } else { @@ -1023,8 +1021,8 @@ static int geni_i2c_init(struct geni_i2c_dev *gi2c) tx_depth = geni_se_get_tx_fifo_depth(&gi2c->se); /* I2C Master Hub Serial Elements doesn't have the HW_PARAM_0 register */ - if (!tx_depth && desc) - tx_depth = desc->tx_fifo_depth; + if (!tx_depth && gi2c->dev_data->has_core_clk) + tx_depth = gi2c->dev_data->tx_fifo_depth; if (!tx_depth) { ret = dev_err_probe(gi2c->se.dev, -EINVAL, @@ -1067,7 +1065,6 @@ static int geni_i2c_probe(struct platform_device *pdev) struct geni_i2c_dev *gi2c; int ret; struct device *dev = &pdev->dev; - const struct geni_i2c_desc *desc = NULL; gi2c = devm_kzalloc(dev, sizeof(*gi2c), GFP_KERNEL); if (!gi2c) @@ -1079,7 +1076,7 @@ static int geni_i2c_probe(struct platform_device *pdev) if (IS_ERR(gi2c->se.base)) return PTR_ERR(gi2c->se.base); - desc = device_get_match_data(&pdev->dev); + gi2c->dev_data = device_get_match_data(&pdev->dev); ret = device_property_read_u32(dev, "clock-frequency", &gi2c->clk_freq_out); @@ -1218,15 +1215,16 @@ static const struct dev_pm_ops geni_i2c_pm_ops = { NULL) }; +static const struct geni_i2c_desc geni_i2c = {}; + static const struct geni_i2c_desc i2c_master_hub = { .has_core_clk = true, - .icc_ddr = NULL, .no_dma_support = true, .tx_fifo_depth = 16, }; static const struct of_device_id geni_i2c_dt_match[] = { - { .compatible = "qcom,geni-i2c" }, + { .compatible = "qcom,geni-i2c", .data = &geni_i2c }, { .compatible = "qcom,geni-i2c-master-hub", .data = &i2c_master_hub }, {} }; -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:21 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 00/13] Enable I2C on SA8255p Qualcomm platforms
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power states(on/off). The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Praveen Talari (13): soc: qcom: geni-se: Refactor geni_icc_get() and make qup-memory ICC path optional soc: qcom: geni-se: Add geni_icc_set_bw_ab() function soc: qcom: geni-se: Introduce helper API for resource initialization soc: qcom: geni-se: Handle core clk in geni_se_clks_off() and geni_se_clks_on() soc: qcom: geni-se: Add resources activation/deactivation helpers soc: qcom: geni-se: Introduce helper API for attaching power domains soc: qcom: geni-se: Introduce helper APIs for performance control dt-bindings: i2c: Describe SA8255p i2c: qcom-geni: Isolate serial engine setup i2c: qcom-geni: Move resource initialization to separate function i2c: qcom-geni: Use resources helper APIs in runtime PM functions i2c: qcom-geni: Store of_device_id data in driver private struct i2c: qcom-geni: Enable I2C on SA8255p Qualcomm platforms --- v3->v4 - Added a new patch(4/13) to handle core clk as part of geni_se_clks_off/on(). --- .../bindings/i2c/qcom,sa8255p-geni-i2c.yaml | 64 ++++ drivers/i2c/busses/i2c-qcom-geni.c | 303 +++++++++--------- drivers/soc/qcom/qcom-geni-se.c | 265 +++++++++++++-- include/linux/soc/qcom/geni-se.h | 19 ++ 4 files changed, 476 insertions(+), 175 deletions(-) create mode 100644 Documentation/devicetree/bindings/i2c/qcom,sa8255p-geni-i2c.yaml base-commit: 193579fe01389bc21aff0051d13f24e8ea95b47d -- 2.34.1
The Qualcomm automotive SA8255p SoC relies on firmware to configure platform resources, including clocks, interconnects and TLMM. The driver requests resources operations over SCMI using power and performance protocols. The SCMI power protocol enables or disables resources like clocks, interconnect paths, and TLMM (GPIOs) using runtime PM framework APIs, such as resume/suspend, to control power on/off. The SCMI performance protocol manages I2C frequency, with each frequency rate represented by a performance level. The driver uses geni_se_set_perf_opp() API to request the desired frequency rate.. As part of geni_se_set_perf_opp(), the OPP for the requested frequency is obtained using dev_pm_opp_find_freq_floor() and the performance level is set using dev_pm_opp_set_opp(). Acked-by: Viken Dadhaniya <viken.dadhaniya@oss.qualcomm.com> Signed-off-by: Praveen Talari <praveen.talari@oss.qualcomm.com> --- v3->v4: - Added Acked-by tag. V1->v2: - Initialized ret to "0" in resume/suspend callbacks. Bjorn: - Used seperate APIs for the resouces enable/disable. --- drivers/i2c/busses/i2c-qcom-geni.c | 56 ++++++++++++++++++++++-------- 1 file changed, 42 insertions(+), 14 deletions(-) diff --git a/drivers/i2c/busses/i2c-qcom-geni.c b/drivers/i2c/busses/i2c-qcom-geni.c index 8fd62d659c2a..2ad31e412b96 100644 --- a/drivers/i2c/busses/i2c-qcom-geni.c +++ b/drivers/i2c/busses/i2c-qcom-geni.c @@ -81,6 +81,10 @@ struct geni_i2c_desc { bool has_core_clk; bool no_dma_support; unsigned int tx_fifo_depth; + int (*resources_init)(struct geni_se *se); + int (*set_rate)(struct geni_se *se, unsigned long freq); + int (*power_on)(struct geni_se *se); + int (*power_off)(struct geni_se *se); }; #define QCOM_I2C_MIN_NUM_OF_MSGS_MULTI_DESC 2 @@ -203,8 +207,9 @@ static int geni_i2c_clk_map_idx(struct geni_i2c_dev *gi2c) return -EINVAL; } -static void qcom_geni_i2c_conf(struct geni_i2c_dev *gi2c) +static int qcom_geni_i2c_conf(struct geni_se *se, unsigned long freq) { + struct geni_i2c_dev *gi2c = dev_get_drvdata(se->dev); const struct geni_i2c_clk_fld *itr = gi2c->clk_fld; u32 val; @@ -217,6 +222,7 @@ static void qcom_geni_i2c_conf(struct geni_i2c_dev *gi2c) val |= itr->t_low_cnt << LOW_COUNTER_SHFT; val |= itr->t_cycle_cnt; writel_relaxed(val, gi2c->se.base + SE_I2C_SCL_COUNTERS); + return 0; } static void geni_i2c_err_misc(struct geni_i2c_dev *gi2c) @@ -908,7 +914,9 @@ static int geni_i2c_xfer(struct i2c_adapter *adap, return ret; } - qcom_geni_i2c_conf(gi2c); + ret = gi2c->dev_data->set_rate(&gi2c->se, gi2c->clk_freq_out); + if (ret) + return ret; if (gi2c->gpi_mode) ret = geni_i2c_gpi_xfer(gi2c, msgs, num); @@ -1043,8 +1051,9 @@ static int geni_i2c_init(struct geni_i2c_dev *gi2c) return ret; } -static int geni_i2c_resources_init(struct geni_i2c_dev *gi2c) +static int geni_i2c_resources_init(struct geni_se *se) { + struct geni_i2c_dev *gi2c = dev_get_drvdata(se->dev); int ret; ret = geni_se_resources_init(&gi2c->se); @@ -1097,7 +1106,7 @@ static int geni_i2c_probe(struct platform_device *pdev) spin_lock_init(&gi2c->lock); platform_set_drvdata(pdev, gi2c); - ret = geni_i2c_resources_init(gi2c); + ret = gi2c->dev_data->resources_init(&gi2c->se); if (ret) return ret; @@ -1156,15 +1165,17 @@ static void geni_i2c_shutdown(struct platform_device *pdev) static int __maybe_unused geni_i2c_runtime_suspend(struct device *dev) { - int ret; + int ret = 0; struct geni_i2c_dev *gi2c = dev_get_drvdata(dev); disable_irq(gi2c->irq); - ret = geni_se_resources_deactivate(&gi2c->se); - if (ret) { - enable_irq(gi2c->irq); - return ret; + if (gi2c->dev_data->power_off) { + ret = gi2c->dev_data->power_off(&gi2c->se); + if (ret) { + enable_irq(gi2c->irq); + return ret; + } } gi2c->suspended = 1; @@ -1173,12 +1184,14 @@ static int __maybe_unused geni_i2c_runtime_suspend(struct device *dev) static int __maybe_unused geni_i2c_runtime_resume(struct device *dev) { - int ret; + int ret = 0; struct geni_i2c_dev *gi2c = dev_get_drvdata(dev); - ret = geni_se_resources_activate(&gi2c->se); - if (ret) - return ret; + if (gi2c->dev_data->power_on) { + ret = gi2c->dev_data->power_on(&gi2c->se); + if (ret) + return ret; + } enable_irq(gi2c->irq); gi2c->suspended = 0; @@ -1215,17 +1228,32 @@ static const struct dev_pm_ops geni_i2c_pm_ops = { NULL) }; -static const struct geni_i2c_desc geni_i2c = {}; +static const struct geni_i2c_desc geni_i2c = { + .resources_init = geni_i2c_resources_init, + .set_rate = qcom_geni_i2c_conf, + .power_on = geni_se_resources_activate, + .power_off = geni_se_resources_deactivate, +}; static const struct geni_i2c_desc i2c_master_hub = { .has_core_clk = true, .no_dma_support = true, .tx_fifo_depth = 16, + .resources_init = geni_i2c_resources_init, + .set_rate = qcom_geni_i2c_conf, + .power_on = geni_se_resources_activate, + .power_off = geni_se_resources_deactivate, +}; + +static const struct geni_i2c_desc sa8255p_geni_i2c = { + .resources_init = geni_se_domain_attach, + .set_rate = geni_se_set_perf_opp, }; static const struct of_device_id geni_i2c_dt_match[] = { { .compatible = "qcom,geni-i2c", .data = &geni_i2c }, { .compatible = "qcom,geni-i2c-master-hub", .data = &i2c_master_hub }, + { .compatible = "qcom,sa8255p-geni-i2c", .data = &sa8255p_geni_i2c }, {} }; MODULE_DEVICE_TABLE(of, geni_i2c_dt_match); -- 2.34.1
{ "author": "Praveen Talari <praveen.talari@oss.qualcomm.com>", "date": "Mon, 2 Feb 2026 23:39:22 +0530", "thread_id": "20260202180922.1692428-4-praveen.talari@oss.qualcomm.com.mbox.gz" }
lkml
[PATCH v4 0/2] soundwire: amd: clock related changes
Refactor clock init sequence to support different bus clock frequencies other than 12Mhz. Modify the bandwidth calculation logic to support 12Mhz, 6Mhz with different frame sizes. Vijendar Mukunda (2): soundwire: amd: add clock init control function soundwire: amd: refactor bandwidth calculation logic Changes since v3: - drop unnecessary debug logs. Changes since v2: - Update commit message - add comments in the code. Changes since v1: - Update Cover letter title. - Fix typo error in commit message. - drop unnecessary condition check in compute params callback. drivers/soundwire/amd_manager.c | 109 +++++++++++++++++++++++++++--- drivers/soundwire/amd_manager.h | 4 -- include/linux/soundwire/sdw_amd.h | 4 ++ 3 files changed, 102 insertions(+), 15 deletions(-) -- 2.45.2
Add generic SoundWire clock initialization sequence to support different SoundWire bus clock frequencies for ACP6.3/7.0/7.1/7.2 platforms and remove hard coding initializations for 12Mhz bus clock frequency. Signed-off-by: Vijendar Mukunda <Vijendar.Mukunda@amd.com> --- drivers/soundwire/amd_manager.c | 52 ++++++++++++++++++++++++++++----- drivers/soundwire/amd_manager.h | 4 --- 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/drivers/soundwire/amd_manager.c b/drivers/soundwire/amd_manager.c index 5fd311ee4107..b53f781e4e74 100644 --- a/drivers/soundwire/amd_manager.c +++ b/drivers/soundwire/amd_manager.c @@ -27,6 +27,45 @@ #define to_amd_sdw(b) container_of(b, struct amd_sdw_manager, bus) +static int amd_sdw_clk_init_ctrl(struct amd_sdw_manager *amd_manager) +{ + struct sdw_bus *bus = &amd_manager->bus; + struct sdw_master_prop *prop = &bus->prop; + u32 val; + int divider; + + dev_dbg(amd_manager->dev, "mclk %d max %d row %d col %d frame_rate:%d\n", + prop->mclk_freq, prop->max_clk_freq, prop->default_row, + prop->default_col, prop->default_frame_rate); + + if (!prop->default_frame_rate || !prop->default_row) { + dev_err(amd_manager->dev, "Default frame_rate %d or row %d is invalid\n", + prop->default_frame_rate, prop->default_row); + return -EINVAL; + } + + /* Set clock divider */ + dev_dbg(amd_manager->dev, "bus params curr_dr_freq: %d\n", + bus->params.curr_dr_freq); + divider = (prop->mclk_freq / bus->params.curr_dr_freq); + + writel(divider, amd_manager->mmio + ACP_SW_CLK_FREQUENCY_CTRL); + val = readl(amd_manager->mmio + ACP_SW_CLK_FREQUENCY_CTRL); + dev_dbg(amd_manager->dev, "ACP_SW_CLK_FREQUENCY_CTRL:0x%x\n", val); + + /* Set frame shape base on the actual bus frequency. */ + prop->default_col = bus->params.curr_dr_freq / + prop->default_frame_rate / prop->default_row; + + dev_dbg(amd_manager->dev, "default_frame_rate:%d default_row: %d default_col: %d\n", + prop->default_frame_rate, prop->default_row, prop->default_col); + amd_manager->cols_index = sdw_find_col_index(prop->default_col); + amd_manager->rows_index = sdw_find_row_index(prop->default_row); + bus->params.col = prop->default_col; + bus->params.row = prop->default_row; + return 0; +} + static int amd_init_sdw_manager(struct amd_sdw_manager *amd_manager) { u32 val; @@ -961,6 +1000,9 @@ int amd_sdw_manager_start(struct amd_sdw_manager *amd_manager) prop = &amd_manager->bus.prop; if (!prop->hw_disabled) { + ret = amd_sdw_clk_init_ctrl(amd_manager); + if (ret) + return ret; ret = amd_init_sdw_manager(amd_manager); if (ret) return ret; @@ -985,7 +1027,6 @@ static int amd_sdw_manager_probe(struct platform_device *pdev) struct resource *res; struct device *dev = &pdev->dev; struct sdw_master_prop *prop; - struct sdw_bus_params *params; struct amd_sdw_manager *amd_manager; int ret; @@ -1049,14 +1090,8 @@ static int amd_sdw_manager_probe(struct platform_device *pdev) return -EINVAL; } - params = &amd_manager->bus.params; - - params->col = AMD_SDW_DEFAULT_COLUMNS; - params->row = AMD_SDW_DEFAULT_ROWS; prop = &amd_manager->bus.prop; - prop->clk_freq = &amd_sdw_freq_tbl[0]; prop->mclk_freq = AMD_SDW_BUS_BASE_FREQ; - prop->max_clk_freq = AMD_SDW_DEFAULT_CLK_FREQ; ret = sdw_bus_master_add(&amd_manager->bus, dev, dev->fwnode); if (ret) { @@ -1348,6 +1383,9 @@ static int __maybe_unused amd_resume_runtime(struct device *dev) } } sdw_clear_slave_status(bus, SDW_UNATTACH_REQUEST_MASTER_RESET); + ret = amd_sdw_clk_init_ctrl(amd_manager); + if (ret) + return ret; amd_init_sdw_manager(amd_manager); amd_enable_sdw_interrupts(amd_manager); ret = amd_enable_sdw_manager(amd_manager); diff --git a/drivers/soundwire/amd_manager.h b/drivers/soundwire/amd_manager.h index 6cc916b0c820..88cf8a426a0c 100644 --- a/drivers/soundwire/amd_manager.h +++ b/drivers/soundwire/amd_manager.h @@ -203,10 +203,6 @@ #define AMD_SDW_DEVICE_STATE_D3 3 #define ACP_PME_EN 0x0001400 -static u32 amd_sdw_freq_tbl[AMD_SDW_MAX_FREQ_NUM] = { - AMD_SDW_DEFAULT_CLK_FREQ, -}; - struct sdw_manager_dp_reg { u32 frame_fmt_reg; u32 sample_int_reg; -- 2.45.2
{ "author": "Vijendar Mukunda <Vijendar.Mukunda@amd.com>", "date": "Thu, 29 Jan 2026 11:44:11 +0530", "thread_id": "20260129061517.38985-1-Vijendar.Mukunda@amd.com.mbox.gz" }
lkml
[PATCH v4 0/2] soundwire: amd: clock related changes
Refactor clock init sequence to support different bus clock frequencies other than 12Mhz. Modify the bandwidth calculation logic to support 12Mhz, 6Mhz with different frame sizes. Vijendar Mukunda (2): soundwire: amd: add clock init control function soundwire: amd: refactor bandwidth calculation logic Changes since v3: - drop unnecessary debug logs. Changes since v2: - Update commit message - add comments in the code. Changes since v1: - Update Cover letter title. - Fix typo error in commit message. - drop unnecessary condition check in compute params callback. drivers/soundwire/amd_manager.c | 109 +++++++++++++++++++++++++++--- drivers/soundwire/amd_manager.h | 4 -- include/linux/soundwire/sdw_amd.h | 4 ++ 3 files changed, 102 insertions(+), 15 deletions(-) -- 2.45.2
For current platforms(ACP6.3/ACP7.0/ACP7.1/ACP7.2), AMD SoundWire manager doesn't have banked registers for data port programming on Manager's side. Need to use fixed block offsets, hstart & hstop for manager ports. Earlier amd manager driver has support for 12MHz as a bus clock frequency with frame size as 50 x 10 with fixed block offset mapping based on port number. Got a requirement to support 6MHz bus clock frequency with different frame shapes 50 x 10 and 125 x 2. For current platforms, amd manager driver supports only two bus clock frequencies(12MHz & 6MHz). Refactor bandwidth logic to support different bus clock frequencies. Signed-off-by: Vijendar Mukunda <Vijendar.Mukunda@amd.com> --- drivers/soundwire/amd_manager.c | 57 ++++++++++++++++++++++++++++--- include/linux/soundwire/sdw_amd.h | 4 +++ 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/drivers/soundwire/amd_manager.c b/drivers/soundwire/amd_manager.c index b53f781e4e74..7cd95a907f67 100644 --- a/drivers/soundwire/amd_manager.c +++ b/drivers/soundwire/amd_manager.c @@ -476,12 +476,16 @@ static u32 amd_sdw_read_ping_status(struct sdw_bus *bus) static int amd_sdw_compute_params(struct sdw_bus *bus, struct sdw_stream_runtime *stream) { + struct amd_sdw_manager *amd_manager = to_amd_sdw(bus); struct sdw_transport_data t_data = {0}; struct sdw_master_runtime *m_rt; struct sdw_port_runtime *p_rt; struct sdw_bus_params *b_params = &bus->params; int port_bo, hstart, hstop, sample_int; - unsigned int rate, bps; + unsigned int rate, bps, channels; + int stream_slot_size, max_slots; + static int next_offset[AMD_SDW_MAX_MANAGER_COUNT] = {1}; + unsigned int inst_id = amd_manager->instance; port_bo = 0; hstart = 1; @@ -492,11 +496,51 @@ static int amd_sdw_compute_params(struct sdw_bus *bus, struct sdw_stream_runtime list_for_each_entry(m_rt, &bus->m_rt_list, bus_node) { rate = m_rt->stream->params.rate; bps = m_rt->stream->params.bps; + channels = m_rt->stream->params.ch_count; sample_int = (bus->params.curr_dr_freq / rate); + + /* Compute slots required for this stream dynamically */ + stream_slot_size = bps * channels; + list_for_each_entry(p_rt, &m_rt->port_list, port_node) { - port_bo = (p_rt->num * 64) + 1; - dev_dbg(bus->dev, "p_rt->num=%d hstart=%d hstop=%d port_bo=%d\n", - p_rt->num, hstart, hstop, port_bo); + if (p_rt->num >= amd_manager->max_ports) { + dev_err(bus->dev, "Port %d exceeds max ports %d\n", + p_rt->num, amd_manager->max_ports); + return -EINVAL; + } + + if (!amd_manager->port_offset_map[p_rt->num]) { + /* + * port block offset calculation for 6MHz bus clock frequency with + * different frame sizes 50 x 10 and 125 x 2 + */ + if (bus->params.curr_dr_freq == 12000000) { + max_slots = bus->params.row * (bus->params.col - 1); + if (next_offset[inst_id] + stream_slot_size <= + (max_slots - 1)) { + amd_manager->port_offset_map[p_rt->num] = + next_offset[inst_id]; + next_offset[inst_id] += stream_slot_size; + } else { + dev_err(bus->dev, + "No space for port %d\n", p_rt->num); + return -ENOMEM; + } + } else { + /* + * port block offset calculation for 12MHz bus clock + * frequency + */ + amd_manager->port_offset_map[p_rt->num] = + (p_rt->num * 64) + 1; + } + } + port_bo = amd_manager->port_offset_map[p_rt->num]; + dev_dbg(bus->dev, + "Port=%d hstart=%d hstop=%d port_bo=%d slots=%d max_ports=%d\n", + p_rt->num, hstart, hstop, port_bo, stream_slot_size, + amd_manager->max_ports); + sdw_fill_xport_params(&p_rt->transport_params, p_rt->num, false, SDW_BLK_GRP_CNT_1, sample_int, port_bo, port_bo >> 8, hstart, hstop, @@ -1089,6 +1133,11 @@ static int amd_sdw_manager_probe(struct platform_device *pdev) default: return -EINVAL; } + amd_manager->max_ports = amd_manager->num_dout_ports + amd_manager->num_din_ports; + amd_manager->port_offset_map = devm_kcalloc(dev, amd_manager->max_ports, + sizeof(int), GFP_KERNEL); + if (!amd_manager->port_offset_map) + return -ENOMEM; prop = &amd_manager->bus.prop; prop->mclk_freq = AMD_SDW_BUS_BASE_FREQ; diff --git a/include/linux/soundwire/sdw_amd.h b/include/linux/soundwire/sdw_amd.h index fe31773d5210..470360a2723c 100644 --- a/include/linux/soundwire/sdw_amd.h +++ b/include/linux/soundwire/sdw_amd.h @@ -66,8 +66,10 @@ struct sdw_amd_dai_runtime { * @status: peripheral devices status array * @num_din_ports: number of input ports * @num_dout_ports: number of output ports + * @max_ports: total number of input ports and output ports * @cols_index: Column index in frame shape * @rows_index: Rows index in frame shape + * @port_offset_map: dynamic array to map port block offset * @instance: SoundWire manager instance * @quirks: SoundWire manager quirks * @wake_en_mask: wake enable mask per SoundWire manager @@ -92,10 +94,12 @@ struct amd_sdw_manager { int num_din_ports; int num_dout_ports; + int max_ports; int cols_index; int rows_index; + int *port_offset_map; u32 instance; u32 quirks; u32 wake_en_mask; -- 2.45.2
{ "author": "Vijendar Mukunda <Vijendar.Mukunda@amd.com>", "date": "Thu, 29 Jan 2026 11:44:12 +0530", "thread_id": "20260129061517.38985-1-Vijendar.Mukunda@amd.com.mbox.gz" }
lkml
[PATCH v4 0/2] soundwire: amd: clock related changes
Refactor clock init sequence to support different bus clock frequencies other than 12Mhz. Modify the bandwidth calculation logic to support 12Mhz, 6Mhz with different frame sizes. Vijendar Mukunda (2): soundwire: amd: add clock init control function soundwire: amd: refactor bandwidth calculation logic Changes since v3: - drop unnecessary debug logs. Changes since v2: - Update commit message - add comments in the code. Changes since v1: - Update Cover letter title. - Fix typo error in commit message. - drop unnecessary condition check in compute params callback. drivers/soundwire/amd_manager.c | 109 +++++++++++++++++++++++++++--- drivers/soundwire/amd_manager.h | 4 -- include/linux/soundwire/sdw_amd.h | 4 ++ 3 files changed, 102 insertions(+), 15 deletions(-) -- 2.45.2
On 1/29/26 12:14 AM, Vijendar Mukunda wrote: Reviewed-by: Mario Limonciello (AMD) <superm1@kernel.org>
{ "author": "Mario Limonciello <superm1@kernel.org>", "date": "Thu, 29 Jan 2026 13:34:01 -0600", "thread_id": "20260129061517.38985-1-Vijendar.Mukunda@amd.com.mbox.gz" }
lkml
[PATCH v4 0/2] soundwire: amd: clock related changes
Refactor clock init sequence to support different bus clock frequencies other than 12Mhz. Modify the bandwidth calculation logic to support 12Mhz, 6Mhz with different frame sizes. Vijendar Mukunda (2): soundwire: amd: add clock init control function soundwire: amd: refactor bandwidth calculation logic Changes since v3: - drop unnecessary debug logs. Changes since v2: - Update commit message - add comments in the code. Changes since v1: - Update Cover letter title. - Fix typo error in commit message. - drop unnecessary condition check in compute params callback. drivers/soundwire/amd_manager.c | 109 +++++++++++++++++++++++++++--- drivers/soundwire/amd_manager.h | 4 -- include/linux/soundwire/sdw_amd.h | 4 ++ 3 files changed, 102 insertions(+), 15 deletions(-) -- 2.45.2
On 1/29/26 07:14, Vijendar Mukunda wrote: the two frame shapes don't carry the same number of bits (500 v. 250). There's probably an additional variable at play, maybe frame rate? Or is 50x10 for 12 MHz and 125x2 for 6 MHz?
{ "author": "Pierre-Louis Bossart <pierre-louis.bossart@linux.dev>", "date": "Mon, 2 Feb 2026 18:05:33 +0100", "thread_id": "20260129061517.38985-1-Vijendar.Mukunda@amd.com.mbox.gz" }
lkml
[PATCH v4 0/2] soundwire: amd: clock related changes
Refactor clock init sequence to support different bus clock frequencies other than 12Mhz. Modify the bandwidth calculation logic to support 12Mhz, 6Mhz with different frame sizes. Vijendar Mukunda (2): soundwire: amd: add clock init control function soundwire: amd: refactor bandwidth calculation logic Changes since v3: - drop unnecessary debug logs. Changes since v2: - Update commit message - add comments in the code. Changes since v1: - Update Cover letter title. - Fix typo error in commit message. - drop unnecessary condition check in compute params callback. drivers/soundwire/amd_manager.c | 109 +++++++++++++++++++++++++++--- drivers/soundwire/amd_manager.h | 4 -- include/linux/soundwire/sdw_amd.h | 4 ++ 3 files changed, 102 insertions(+), 15 deletions(-) -- 2.45.2
On 02/02/26 22:35, Pierre-Louis Bossart wrote: We need to support 12Mhz as bus clock frequency where frame rate is 48000 and number of bits is 500, frame shape as 50 x 10. For 6Mhz bus clock frequency we need to support two different frame shapes i.e number of bits as 250 with frame rate as 48000 and frame shape as 125 x 2 and For second combination number of bits as 500 where frame rate as 24000 and frame size as 50 x10. Few SoundWire peripherals doesn't support 125 x2 frame shape for 6Mhz bus clock frequency.   They have explicit requirement for the frame shape. In this scenario, we will use 50 x 10 as frame shape where frame rate as  24000. Based on the platform and SoundWire topology for 6Mhz support frame shape will be decided which is part of SoundWire manager DisCo tables.
{ "author": "\"Mukunda,Vijendar\" <vijendar.mukunda@amd.com>", "date": "Mon, 2 Feb 2026 22:55:01 +0530", "thread_id": "20260129061517.38985-1-Vijendar.Mukunda@amd.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> This file actually implements irq remapping, so rename to more appropriate hyperv-irq.c. A new file named hyperv-iommu.c will be introduced later. Also, move CONFIG_IRQ_REMAP out of the file and add to Makefile. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- MAINTAINERS | 2 +- drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/{hyperv-iommu.c => hyperv-irq.c} | 4 ---- 4 files changed, 3 insertions(+), 6 deletions(-) rename drivers/iommu/{hyperv-iommu.c => hyperv-irq.c} (99%) diff --git a/MAINTAINERS b/MAINTAINERS index 5b11839cba9d..381a0e086382 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11741,7 +11741,7 @@ F: drivers/hid/hid-hyperv.c F: drivers/hv/ F: drivers/infiniband/hw/mana/ F: drivers/input/serio/hyperv-keyboard.c -F: drivers/iommu/hyperv-iommu.c +F: drivers/iommu/hyperv-irq.c F: drivers/net/ethernet/microsoft/ F: drivers/net/hyperv/ F: drivers/pci/controller/pci-hyperv-intf.c diff --git a/drivers/iommu/Kconfig b/drivers/iommu/Kconfig index 99095645134f..b4cc2b42b338 100644 --- a/drivers/iommu/Kconfig +++ b/drivers/iommu/Kconfig @@ -355,6 +355,7 @@ config HYPERV_IOMMU bool "Hyper-V IRQ Handling" depends on HYPERV && X86 select IOMMU_API + select IRQ_REMAP default HYPERV help Stub IOMMU driver to handle IRQs to support Hyper-V Linux diff --git a/drivers/iommu/Makefile b/drivers/iommu/Makefile index 8e8843316c4b..598c39558e7d 100644 --- a/drivers/iommu/Makefile +++ b/drivers/iommu/Makefile @@ -30,7 +30,7 @@ obj-$(CONFIG_TEGRA_IOMMU_SMMU) += tegra-smmu.o obj-$(CONFIG_EXYNOS_IOMMU) += exynos-iommu.o obj-$(CONFIG_FSL_PAMU) += fsl_pamu.o fsl_pamu_domain.o obj-$(CONFIG_S390_IOMMU) += s390-iommu.o -obj-$(CONFIG_HYPERV_IOMMU) += hyperv-iommu.o +obj-$(CONFIG_HYPERV_IOMMU) += hyperv-irq.o obj-$(CONFIG_VIRTIO_IOMMU) += virtio-iommu.o obj-$(CONFIG_IOMMU_SVA) += iommu-sva.o obj-$(CONFIG_IOMMU_IOPF) += io-pgfault.o diff --git a/drivers/iommu/hyperv-iommu.c b/drivers/iommu/hyperv-irq.c similarity index 99% rename from drivers/iommu/hyperv-iommu.c rename to drivers/iommu/hyperv-irq.c index 0961ac805944..1944440a5004 100644 --- a/drivers/iommu/hyperv-iommu.c +++ b/drivers/iommu/hyperv-irq.c @@ -24,8 +24,6 @@ #include "irq_remapping.h" -#ifdef CONFIG_IRQ_REMAP - /* * According 82093AA IO-APIC spec , IO APIC has a 24-entry Interrupt * Redirection Table. Hyper-V exposes one single IO-APIC and so define @@ -330,5 +328,3 @@ static const struct irq_domain_ops hyperv_root_ir_domain_ops = { .alloc = hyperv_root_irq_remapping_alloc, .free = hyperv_root_irq_remapping_free, }; - -#endif -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:16 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Many PCI passthru related hypercalls require partition id of the target guest. Guests are actually managed by MSHV driver and the partition id is only maintained there. Add a field in the partition struct in MSHV driver to save the tgid of the VMM process creating the partition, and add a function there to retrieve partition id if valid VMM tgid. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- drivers/hv/mshv_root.h | 1 + drivers/hv/mshv_root_main.c | 35 +++++++++++++++++++++++++++------- include/asm-generic/mshyperv.h | 1 + 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/drivers/hv/mshv_root.h b/drivers/hv/mshv_root.h index 3c1d88b36741..c3753b009fd8 100644 --- a/drivers/hv/mshv_root.h +++ b/drivers/hv/mshv_root.h @@ -134,6 +134,7 @@ struct mshv_partition { struct mshv_girq_routing_table __rcu *pt_girq_tbl; u64 isolation_type; + pid_t pt_vmm_tgid; bool import_completed; bool pt_initialized; }; diff --git a/drivers/hv/mshv_root_main.c b/drivers/hv/mshv_root_main.c index 1134a82c7881..83c7bad269a0 100644 --- a/drivers/hv/mshv_root_main.c +++ b/drivers/hv/mshv_root_main.c @@ -1823,6 +1823,20 @@ mshv_partition_release(struct inode *inode, struct file *filp) return 0; } +/* Given a process tgid, return partition id if it is a VMM process */ +u64 mshv_pid_to_partid(pid_t tgid) +{ + struct mshv_partition *pt; + int i; + + hash_for_each_rcu(mshv_root.pt_htable, i, pt, pt_hnode) + if (pt->pt_vmm_tgid == tgid) + return pt->pt_id; + + return HV_PARTITION_ID_INVALID; +} +EXPORT_SYMBOL_GPL(mshv_pid_to_partid); + static int add_partition(struct mshv_partition *partition) { @@ -1987,13 +2001,20 @@ mshv_ioctl_create_partition(void __user *user_arg, struct device *module_dev) goto delete_partition; ret = mshv_init_async_handler(partition); - if (!ret) { - ret = FD_ADD(O_CLOEXEC, anon_inode_getfile("mshv_partition", - &mshv_partition_fops, - partition, O_RDWR)); - if (ret >= 0) - return ret; - } + if (ret) + goto rem_partition; + + ret = FD_ADD(O_CLOEXEC, anon_inode_getfile("mshv_partition", + &mshv_partition_fops, + partition, O_RDWR)); + if (ret < 0) + goto rem_partition; + + partition->pt_vmm_tgid = current->tgid; + + return ret; + +rem_partition: remove_partition(partition); delete_partition: hv_call_delete_partition(partition->pt_id); diff --git a/include/asm-generic/mshyperv.h b/include/asm-generic/mshyperv.h index ecedab554c80..e46a38916e76 100644 --- a/include/asm-generic/mshyperv.h +++ b/include/asm-generic/mshyperv.h @@ -211,6 +211,7 @@ void __init ms_hyperv_late_init(void); int hv_common_cpu_init(unsigned int cpu); int hv_common_cpu_die(unsigned int cpu); void hv_identify_partition_type(void); +u64 mshv_pid_to_partid(pid_t tgid); /** * hv_cpu_number_to_vp_number() - Map CPU to VP. -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:19 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Passthru exposes insufficient memory hypercall failure in the current map device interrupt hypercall. In case of such a failure, we must deposit more memory and redo the hypercall. Add support for that. Deposit memory needs partition id, make that a parameter to the map interrupt function. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- arch/x86/hyperv/irqdomain.c | 38 +++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/arch/x86/hyperv/irqdomain.c b/arch/x86/hyperv/irqdomain.c index f6b61483b3b8..ccbe5848a28f 100644 --- a/arch/x86/hyperv/irqdomain.c +++ b/arch/x86/hyperv/irqdomain.c @@ -13,8 +13,9 @@ #include <linux/irqchip/irq-msi-lib.h> #include <asm/mshyperv.h> -static int hv_map_interrupt(union hv_device_id hv_devid, bool level, - int cpu, int vector, struct hv_interrupt_entry *ret_entry) +static u64 hv_map_interrupt_hcall(u64 ptid, union hv_device_id hv_devid, + bool level, int cpu, int vector, + struct hv_interrupt_entry *ret_entry) { struct hv_input_map_device_interrupt *input; struct hv_output_map_device_interrupt *output; @@ -30,8 +31,10 @@ static int hv_map_interrupt(union hv_device_id hv_devid, bool level, intr_desc = &input->interrupt_descriptor; memset(input, 0, sizeof(*input)); - input->partition_id = hv_current_partition_id; + + input->partition_id = ptid; input->device_id = hv_devid.as_uint64; + intr_desc->interrupt_type = HV_X64_INTERRUPT_TYPE_FIXED; intr_desc->vector_count = 1; intr_desc->target.vector = vector; @@ -64,6 +67,28 @@ static int hv_map_interrupt(union hv_device_id hv_devid, bool level, local_irq_restore(flags); + return status; +} + +static int hv_map_interrupt(u64 ptid, union hv_device_id device_id, bool level, + int cpu, int vector, + struct hv_interrupt_entry *ret_entry) +{ + u64 status; + int rc, deposit_pgs = 16; /* don't loop forever */ + + while (deposit_pgs--) { + status = hv_map_interrupt_hcall(ptid, device_id, level, cpu, + vector, ret_entry); + + if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) + break; + + rc = hv_call_deposit_pages(NUMA_NO_NODE, ptid, 1); + if (rc) + break; + }; + if (!hv_result_success(status)) hv_status_err(status, "\n"); @@ -199,8 +224,8 @@ int hv_map_msi_interrupt(struct irq_data *data, hv_devid = hv_build_devid_type_pci(pdev); cpu = cpumask_first(irq_data_get_effective_affinity_mask(data)); - return hv_map_interrupt(hv_devid, false, cpu, cfg->vector, - out_entry ? out_entry : &dummy); + return hv_map_interrupt(hv_current_partition_id, hv_devid, false, cpu, + cfg->vector, out_entry ? out_entry : &dummy); } EXPORT_SYMBOL_GPL(hv_map_msi_interrupt); @@ -422,6 +447,7 @@ int hv_map_ioapic_interrupt(int ioapic_id, bool level, int cpu, int vector, hv_devid.device_type = HV_DEVICE_TYPE_IOAPIC; hv_devid.ioapic.ioapic_id = (u8)ioapic_id; - return hv_map_interrupt(hv_devid, level, cpu, vector, entry); + return hv_map_interrupt(hv_current_partition_id, hv_devid, level, cpu, + vector, entry); } EXPORT_SYMBOL_GPL(hv_map_ioapic_interrupt); -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:18 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Main change here is to rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg as we introduce hv_compose_msi_msg in upcoming patches that builds MSI messages for both VMBus and non-VMBus cases. VMBus is not used on baremetal root partition for example. While at it, replace spaces with tabs and fix some formatting involving excessive line wraps. There is no functional change. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- drivers/pci/controller/pci-hyperv.c | 95 +++++++++++++++-------------- 1 file changed, 48 insertions(+), 47 deletions(-) diff --git a/drivers/pci/controller/pci-hyperv.c b/drivers/pci/controller/pci-hyperv.c index 1e237d3538f9..8bc6a38c9b5a 100644 --- a/drivers/pci/controller/pci-hyperv.c +++ b/drivers/pci/controller/pci-hyperv.c @@ -30,7 +30,7 @@ * function's configuration space is zero. * * The rest of this driver mostly maps PCI concepts onto underlying Hyper-V - * facilities. For instance, the configuration space of a function exposed + * facilities. For instance, the configuration space of a function exposed * by Hyper-V is mapped into a single page of memory space, and the * read and write handlers for config space must be aware of this mechanism. * Similarly, device setup and teardown involves messages sent to and from @@ -109,33 +109,33 @@ enum pci_message_type { /* * Version 1.1 */ - PCI_MESSAGE_BASE = 0x42490000, - PCI_BUS_RELATIONS = PCI_MESSAGE_BASE + 0, - PCI_QUERY_BUS_RELATIONS = PCI_MESSAGE_BASE + 1, - PCI_POWER_STATE_CHANGE = PCI_MESSAGE_BASE + 4, + PCI_MESSAGE_BASE = 0x42490000, + PCI_BUS_RELATIONS = PCI_MESSAGE_BASE + 0, + PCI_QUERY_BUS_RELATIONS = PCI_MESSAGE_BASE + 1, + PCI_POWER_STATE_CHANGE = PCI_MESSAGE_BASE + 4, PCI_QUERY_RESOURCE_REQUIREMENTS = PCI_MESSAGE_BASE + 5, - PCI_QUERY_RESOURCE_RESOURCES = PCI_MESSAGE_BASE + 6, - PCI_BUS_D0ENTRY = PCI_MESSAGE_BASE + 7, - PCI_BUS_D0EXIT = PCI_MESSAGE_BASE + 8, - PCI_READ_BLOCK = PCI_MESSAGE_BASE + 9, - PCI_WRITE_BLOCK = PCI_MESSAGE_BASE + 0xA, - PCI_EJECT = PCI_MESSAGE_BASE + 0xB, - PCI_QUERY_STOP = PCI_MESSAGE_BASE + 0xC, - PCI_REENABLE = PCI_MESSAGE_BASE + 0xD, - PCI_QUERY_STOP_FAILED = PCI_MESSAGE_BASE + 0xE, - PCI_EJECTION_COMPLETE = PCI_MESSAGE_BASE + 0xF, - PCI_RESOURCES_ASSIGNED = PCI_MESSAGE_BASE + 0x10, - PCI_RESOURCES_RELEASED = PCI_MESSAGE_BASE + 0x11, - PCI_INVALIDATE_BLOCK = PCI_MESSAGE_BASE + 0x12, - PCI_QUERY_PROTOCOL_VERSION = PCI_MESSAGE_BASE + 0x13, - PCI_CREATE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x14, - PCI_DELETE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x15, + PCI_QUERY_RESOURCE_RESOURCES = PCI_MESSAGE_BASE + 6, + PCI_BUS_D0ENTRY = PCI_MESSAGE_BASE + 7, + PCI_BUS_D0EXIT = PCI_MESSAGE_BASE + 8, + PCI_READ_BLOCK = PCI_MESSAGE_BASE + 9, + PCI_WRITE_BLOCK = PCI_MESSAGE_BASE + 0xA, + PCI_EJECT = PCI_MESSAGE_BASE + 0xB, + PCI_QUERY_STOP = PCI_MESSAGE_BASE + 0xC, + PCI_REENABLE = PCI_MESSAGE_BASE + 0xD, + PCI_QUERY_STOP_FAILED = PCI_MESSAGE_BASE + 0xE, + PCI_EJECTION_COMPLETE = PCI_MESSAGE_BASE + 0xF, + PCI_RESOURCES_ASSIGNED = PCI_MESSAGE_BASE + 0x10, + PCI_RESOURCES_RELEASED = PCI_MESSAGE_BASE + 0x11, + PCI_INVALIDATE_BLOCK = PCI_MESSAGE_BASE + 0x12, + PCI_QUERY_PROTOCOL_VERSION = PCI_MESSAGE_BASE + 0x13, + PCI_CREATE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x14, + PCI_DELETE_INTERRUPT_MESSAGE = PCI_MESSAGE_BASE + 0x15, PCI_RESOURCES_ASSIGNED2 = PCI_MESSAGE_BASE + 0x16, PCI_CREATE_INTERRUPT_MESSAGE2 = PCI_MESSAGE_BASE + 0x17, PCI_DELETE_INTERRUPT_MESSAGE2 = PCI_MESSAGE_BASE + 0x18, /* unused */ PCI_BUS_RELATIONS2 = PCI_MESSAGE_BASE + 0x19, - PCI_RESOURCES_ASSIGNED3 = PCI_MESSAGE_BASE + 0x1A, - PCI_CREATE_INTERRUPT_MESSAGE3 = PCI_MESSAGE_BASE + 0x1B, + PCI_RESOURCES_ASSIGNED3 = PCI_MESSAGE_BASE + 0x1A, + PCI_CREATE_INTERRUPT_MESSAGE3 = PCI_MESSAGE_BASE + 0x1B, PCI_MESSAGE_MAXIMUM }; @@ -1775,20 +1775,21 @@ static u32 hv_compose_msi_req_v1( * via the HVCALL_RETARGET_INTERRUPT hypercall. But the choice of dummy vCPU is * not irrelevant because Hyper-V chooses the physical CPU to handle the * interrupts based on the vCPU specified in message sent to the vPCI VSP in - * hv_compose_msi_msg(). Hyper-V's choice of pCPU is not visible to the guest, - * but assigning too many vPCI device interrupts to the same pCPU can cause a - * performance bottleneck. So we spread out the dummy vCPUs to influence Hyper-V - * to spread out the pCPUs that it selects. + * hv_vmbus_compose_msi_msg(). Hyper-V's choice of pCPU is not visible to the + * guest, but assigning too many vPCI device interrupts to the same pCPU can + * cause a performance bottleneck. So we spread out the dummy vCPUs to influence + * Hyper-V to spread out the pCPUs that it selects. * * For the single-MSI and MSI-X cases, it's OK for hv_compose_msi_req_get_cpu() * to always return the same dummy vCPU, because a second call to - * hv_compose_msi_msg() contains the "real" vCPU, causing Hyper-V to choose a - * new pCPU for the interrupt. But for the multi-MSI case, the second call to - * hv_compose_msi_msg() exits without sending a message to the vPCI VSP, so the - * original dummy vCPU is used. This dummy vCPU must be round-robin'ed so that - * the pCPUs are spread out. All interrupts for a multi-MSI device end up using - * the same pCPU, even though the vCPUs will be spread out by later calls - * to hv_irq_unmask(), but that is the best we can do now. + * hv_vmbus_compose_msi_msg() contains the "real" vCPU, causing Hyper-V to + * choose a new pCPU for the interrupt. But for the multi-MSI case, the second + * call to hv_vmbus_compose_msi_msg() exits without sending a message to the + * vPCI VSP, so the original dummy vCPU is used. This dummy vCPU must be + * round-robin'ed so that the pCPUs are spread out. All interrupts for a + * multi-MSI device end up using the same pCPU, even though the vCPUs will be + * spread out by later calls to hv_irq_unmask(), but that is the best we can do + * now. * * With Hyper-V in Nov 2022, the HVCALL_RETARGET_INTERRUPT hypercall does *not* * cause Hyper-V to reselect the pCPU based on the specified vCPU. Such an @@ -1863,7 +1864,7 @@ static u32 hv_compose_msi_req_v3( } /** - * hv_compose_msi_msg() - Supplies a valid MSI address/data + * hv_vmbus_compose_msi_msg() - Supplies a valid MSI address/data * @data: Everything about this MSI * @msg: Buffer that is filled in by this function * @@ -1873,7 +1874,7 @@ static u32 hv_compose_msi_req_v3( * response supplies a data value and address to which that data * should be written to trigger that interrupt. */ -static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) +static void hv_vmbus_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) { struct hv_pcibus_device *hbus; struct vmbus_channel *channel; @@ -1955,7 +1956,7 @@ static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) return; } /* - * The vector we select here is a dummy value. The correct + * The vector we select here is a dummy value. The correct * value gets sent to the hypervisor in unmask(). This needs * to be aligned with the count, and also not zero. Multi-msi * is powers of 2 up to 32, so 32 will always work here. @@ -2047,7 +2048,7 @@ static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) /* * Make sure that the ring buffer data structure doesn't get - * freed while we dereference the ring buffer pointer. Test + * freed while we dereference the ring buffer pointer. Test * for the channel's onchannel_callback being NULL within a * sched_lock critical section. See also the inline comments * in vmbus_reset_channel_cb(). @@ -2147,7 +2148,7 @@ static const struct msi_parent_ops hv_pcie_msi_parent_ops = { /* HW Interrupt Chip Descriptor */ static struct irq_chip hv_msi_irq_chip = { .name = "Hyper-V PCIe MSI", - .irq_compose_msi_msg = hv_compose_msi_msg, + .irq_compose_msi_msg = hv_vmbus_compose_msi_msg, .irq_set_affinity = irq_chip_set_affinity_parent, .irq_ack = irq_chip_ack_parent, .irq_eoi = irq_chip_eoi_parent, @@ -2159,8 +2160,8 @@ static int hv_pcie_domain_alloc(struct irq_domain *d, unsigned int virq, unsigne void *arg) { /* - * TODO: Allocating and populating struct tran_int_desc in hv_compose_msi_msg() - * should be moved here. + * TODO: Allocating and populating struct tran_int_desc in + * hv_vmbus_compose_msi_msg() should be moved here. */ int ret; @@ -2227,7 +2228,7 @@ static int hv_pcie_init_irq_domain(struct hv_pcibus_device *hbus) /** * get_bar_size() - Get the address space consumed by a BAR * @bar_val: Value that a BAR returned after -1 was written - * to it. + * to it. * * This function returns the size of the BAR, rounded up to 1 * page. It has to be rounded up because the hypervisor's page @@ -2573,7 +2574,7 @@ static void q_resource_requirements(void *context, struct pci_response *resp, * new_pcichild_device() - Create a new child device * @hbus: The internal struct tracking this root PCI bus. * @desc: The information supplied so far from the host - * about the device. + * about the device. * * This function creates the tracking structure for a new child * device and kicks off the process of figuring out what it is. @@ -3100,7 +3101,7 @@ static void hv_pci_onchannelcallback(void *context) * sure that the packet pointer is still valid during the call: * here 'valid' means that there's a task still waiting for the * completion, and that the packet data is still on the waiting - * task's stack. Cf. hv_compose_msi_msg(). + * task's stack. Cf. hv_vmbus_compose_msi_msg(). */ comp_packet->completion_func(comp_packet->compl_ctxt, response, @@ -3417,7 +3418,7 @@ static int hv_allocate_config_window(struct hv_pcibus_device *hbus) * vmbus_allocate_mmio() gets used for allocating both device endpoint * resource claims (those which cannot be overlapped) and the ranges * which are valid for the children of this bus, which are intended - * to be overlapped by those children. Set the flag on this claim + * to be overlapped by those children. Set the flag on this claim * meaning that this region can't be overlapped. */ @@ -4066,7 +4067,7 @@ static int hv_pci_restore_msi_msg(struct pci_dev *pdev, void *arg) irq_data = irq_get_irq_data(entry->irq); if (WARN_ON_ONCE(!irq_data)) return -EINVAL; - hv_compose_msi_msg(irq_data, &entry->msg); + hv_vmbus_compose_msi_msg(irq_data, &entry->msg); } return 0; } @@ -4074,7 +4075,7 @@ static int hv_pci_restore_msi_msg(struct pci_dev *pdev, void *arg) /* * Upon resume, pci_restore_msi_state() -> ... -> __pci_write_msi_msg() * directly writes the MSI/MSI-X registers via MMIO, but since Hyper-V - * doesn't trap and emulate the MMIO accesses, here hv_compose_msi_msg() + * doesn't trap and emulate the MMIO accesses, here hv_vmbus_compose_msi_msg() * must be used to ask Hyper-V to re-create the IOMMU Interrupt Remapping * Table entries. */ -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:23 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Add ioctl support for creating MSHV devices for a paritition. At present only VFIO device types are supported, but more could be added. At a high level, a partition ioctl to create device verifies it is of type VFIO and does some setup for bridge code in mshv_vfio.c. Adapted from KVM device ioctls. Credits: Original author: Wei Liu <wei.liu@kernel.org> NB: Slightly modified from the original version. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- drivers/hv/mshv_root_main.c | 126 ++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) diff --git a/drivers/hv/mshv_root_main.c b/drivers/hv/mshv_root_main.c index 83c7bad269a0..27313419828d 100644 --- a/drivers/hv/mshv_root_main.c +++ b/drivers/hv/mshv_root_main.c @@ -1551,6 +1551,129 @@ mshv_partition_ioctl_initialize(struct mshv_partition *partition) return ret; } +static long mshv_device_attr_ioctl(struct mshv_device *mshv_dev, int cmd, + ulong uarg) +{ + struct mshv_device_attr attr; + const struct mshv_device_ops *devops = mshv_dev->device_ops; + + if (copy_from_user(&attr, (void __user *)uarg, sizeof(attr))) + return -EFAULT; + + switch (cmd) { + case MSHV_SET_DEVICE_ATTR: + if (devops->device_set_attr) + return devops->device_set_attr(mshv_dev, &attr); + break; + case MSHV_HAS_DEVICE_ATTR: + if (devops->device_has_attr) + return devops->device_has_attr(mshv_dev, &attr); + break; + } + + return -EPERM; +} + +static long mshv_device_fop_ioctl(struct file *filp, unsigned int cmd, + ulong uarg) +{ + struct mshv_device *mshv_dev = filp->private_data; + + switch (cmd) { + case MSHV_SET_DEVICE_ATTR: + case MSHV_HAS_DEVICE_ATTR: + return mshv_device_attr_ioctl(mshv_dev, cmd, uarg); + } + + return -ENOTTY; +} + +static int mshv_device_fop_release(struct inode *inode, struct file *filp) +{ + struct mshv_device *mshv_dev = filp->private_data; + struct mshv_partition *partition = mshv_dev->device_pt; + + if (mshv_dev->device_ops->device_release) { + mutex_lock(&partition->pt_mutex); + hlist_del(&mshv_dev->device_ptnode); + mshv_dev->device_ops->device_release(mshv_dev); + mutex_unlock(&partition->pt_mutex); + } + + mshv_partition_put(partition); + return 0; +} + +static const struct file_operations mshv_device_fops = { + .owner = THIS_MODULE, + .unlocked_ioctl = mshv_device_fop_ioctl, + .release = mshv_device_fop_release, +}; + +long mshv_partition_ioctl_create_device(struct mshv_partition *partition, + void __user *uarg) +{ + long rc; + struct mshv_create_device devargk; + struct mshv_device *mshv_dev; + const struct mshv_device_ops *vfio_ops; + int type; + + if (copy_from_user(&devargk, uarg, sizeof(devargk))) { + rc = -EFAULT; + goto out; + } + + /* At present, only VFIO is supported */ + if (devargk.type != MSHV_DEV_TYPE_VFIO) { + rc = -ENODEV; + goto out; + } + + if (devargk.flags & MSHV_CREATE_DEVICE_TEST) { + rc = 0; + goto out; + } + + mshv_dev = kzalloc(sizeof(*mshv_dev), GFP_KERNEL_ACCOUNT); + if (mshv_dev == NULL) { + rc = -ENOMEM; + goto out; + } + + vfio_ops = &mshv_vfio_device_ops; + mshv_dev->device_ops = vfio_ops; + mshv_dev->device_pt = partition; + + rc = vfio_ops->device_create(mshv_dev, type); + if (rc < 0) { + kfree(mshv_dev); + goto out; + } + + hlist_add_head(&mshv_dev->device_ptnode, &partition->pt_devices); + + mshv_partition_get(partition); + rc = anon_inode_getfd(vfio_ops->device_name, &mshv_device_fops, + mshv_dev, O_RDWR | O_CLOEXEC); + if (rc < 0) { + mshv_partition_put(partition); + hlist_del(&mshv_dev->device_ptnode); + vfio_ops->device_release(mshv_dev); + goto out; + } + + devargk.fd = rc; + rc = 0; + + if (copy_to_user(uarg, &devargk, sizeof(devargk))) { + rc = -EFAULT; + goto out; + } +out: + return rc; +} + static long mshv_partition_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { @@ -1587,6 +1710,9 @@ mshv_partition_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) case MSHV_ROOT_HVCALL: ret = mshv_ioctl_passthru_hvcall(partition, true, uarg); break; + case MSHV_CREATE_DEVICE: + ret = mshv_partition_ioctl_create_device(partition, uarg); + break; default: ret = -ENOTTY; } -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:22 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Add data structs needed by the subsequent patch that introduces a new module to implement VFIO-MSHV pseudo device. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- drivers/hv/mshv_root.h | 23 +++++++++++++++++++++++ include/uapi/linux/mshv.h | 31 +++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/drivers/hv/mshv_root.h b/drivers/hv/mshv_root.h index c3753b009fd8..42e1da1d545b 100644 --- a/drivers/hv/mshv_root.h +++ b/drivers/hv/mshv_root.h @@ -220,6 +220,29 @@ struct port_table_info { }; }; +struct mshv_device { + const struct mshv_device_ops *device_ops; + struct mshv_partition *device_pt; + void *device_private; + struct hlist_node device_ptnode; +}; + +struct mshv_device_ops { + const char *device_name; + long (*device_create)(struct mshv_device *dev, u32 type); + void (*device_release)(struct mshv_device *dev); + long (*device_set_attr)(struct mshv_device *dev, + struct mshv_device_attr *attr); + long (*device_has_attr)(struct mshv_device *dev, + struct mshv_device_attr *attr); +}; + +extern struct mshv_device_ops mshv_vfio_device_ops; +int mshv_vfio_ops_init(void); +void mshv_vfio_ops_exit(void); +long mshv_partition_ioctl_create_device(struct mshv_partition *partition, + void __user *user_args); + int mshv_update_routing_table(struct mshv_partition *partition, const struct mshv_user_irq_entry *entries, unsigned int numents); diff --git a/include/uapi/linux/mshv.h b/include/uapi/linux/mshv.h index dee3ece28ce5..b7b10f9e2896 100644 --- a/include/uapi/linux/mshv.h +++ b/include/uapi/linux/mshv.h @@ -252,6 +252,7 @@ struct mshv_root_hvcall { #define MSHV_GET_GPAP_ACCESS_BITMAP _IOWR(MSHV_IOCTL, 0x06, struct mshv_gpap_access_bitmap) /* Generic hypercall */ #define MSHV_ROOT_HVCALL _IOWR(MSHV_IOCTL, 0x07, struct mshv_root_hvcall) +#define MSHV_CREATE_DEVICE _IOWR(MSHV_IOCTL, 0x08, struct mshv_create_device) /* ******************************** @@ -402,4 +403,34 @@ struct mshv_sint_mask { /* hv_hvcall device */ #define MSHV_HVCALL_SETUP _IOW(MSHV_IOCTL, 0x1E, struct mshv_vtl_hvcall_setup) #define MSHV_HVCALL _IOWR(MSHV_IOCTL, 0x1F, struct mshv_vtl_hvcall) + +/* device passhthru */ +#define MSHV_CREATE_DEVICE_TEST 1 + +enum { + MSHV_DEV_TYPE_VFIO, + MSHV_DEV_TYPE_MAX, +}; + +struct mshv_create_device { + __u32 type; /* in: MSHV_DEV_TYPE_xxx */ + __u32 fd; /* out: device handle */ + __u32 flags; /* in: MSHV_CREATE_DEVICE_xxx */ +}; + +#define MSHV_DEV_VFIO_FILE 1 +#define MSHV_DEV_VFIO_FILE_ADD 1 +#define MSHV_DEV_VFIO_FILE_DEL 2 + +struct mshv_device_attr { + __u32 flags; /* no flags currently defined */ + __u32 group; /* device-defined */ + __u64 attr; /* group-defined */ + __u64 addr; /* userspace address of attr data */ +}; + +/* Device fds created with MSHV_CREATE_DEVICE */ +#define MSHV_SET_DEVICE_ATTR _IOW(MSHV_IOCTL, 0x00, struct mshv_device_attr) +#define MSHV_HAS_DEVICE_ATTR _IOW(MSHV_IOCTL, 0x01, struct mshv_device_attr) + #endif -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:20 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Make cosmetic changes: o Rename struct pci_dev *dev to *pdev since there are cases of struct device *dev in the file and all over the kernel o Rename hv_build_pci_dev_id to hv_build_devid_type_pci in anticipation of building different types of device ids o Fix checkpatch.pl issues with return and extraneous printk o Replace spaces with tabs o Rename struct hv_devid *xxx to struct hv_devid *hv_devid given code paths involve many types of device ids o Fix indentation in a large if block by using goto. There are no functional changes. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- arch/x86/hyperv/irqdomain.c | 197 +++++++++++++++++++----------------- 1 file changed, 103 insertions(+), 94 deletions(-) diff --git a/arch/x86/hyperv/irqdomain.c b/arch/x86/hyperv/irqdomain.c index c3ba12b1bc07..f6b61483b3b8 100644 --- a/arch/x86/hyperv/irqdomain.c +++ b/arch/x86/hyperv/irqdomain.c @@ -1,5 +1,4 @@ // SPDX-License-Identifier: GPL-2.0 - /* * Irqdomain for Linux to run as the root partition on Microsoft Hypervisor. * @@ -14,8 +13,8 @@ #include <linux/irqchip/irq-msi-lib.h> #include <asm/mshyperv.h> -static int hv_map_interrupt(union hv_device_id device_id, bool level, - int cpu, int vector, struct hv_interrupt_entry *entry) +static int hv_map_interrupt(union hv_device_id hv_devid, bool level, + int cpu, int vector, struct hv_interrupt_entry *ret_entry) { struct hv_input_map_device_interrupt *input; struct hv_output_map_device_interrupt *output; @@ -32,7 +31,7 @@ static int hv_map_interrupt(union hv_device_id device_id, bool level, intr_desc = &input->interrupt_descriptor; memset(input, 0, sizeof(*input)); input->partition_id = hv_current_partition_id; - input->device_id = device_id.as_uint64; + input->device_id = hv_devid.as_uint64; intr_desc->interrupt_type = HV_X64_INTERRUPT_TYPE_FIXED; intr_desc->vector_count = 1; intr_desc->target.vector = vector; @@ -44,7 +43,7 @@ static int hv_map_interrupt(union hv_device_id device_id, bool level, intr_desc->target.vp_set.valid_bank_mask = 0; intr_desc->target.vp_set.format = HV_GENERIC_SET_SPARSE_4K; - nr_bank = cpumask_to_vpset(&(intr_desc->target.vp_set), cpumask_of(cpu)); + nr_bank = cpumask_to_vpset(&intr_desc->target.vp_set, cpumask_of(cpu)); if (nr_bank < 0) { local_irq_restore(flags); pr_err("%s: unable to generate VP set\n", __func__); @@ -61,7 +60,7 @@ static int hv_map_interrupt(union hv_device_id device_id, bool level, status = hv_do_rep_hypercall(HVCALL_MAP_DEVICE_INTERRUPT, 0, var_size, input, output); - *entry = output->interrupt_entry; + *ret_entry = output->interrupt_entry; local_irq_restore(flags); @@ -71,21 +70,19 @@ static int hv_map_interrupt(union hv_device_id device_id, bool level, return hv_result_to_errno(status); } -static int hv_unmap_interrupt(u64 id, struct hv_interrupt_entry *old_entry) +static int hv_unmap_interrupt(u64 id, struct hv_interrupt_entry *irq_entry) { unsigned long flags; struct hv_input_unmap_device_interrupt *input; - struct hv_interrupt_entry *intr_entry; u64 status; local_irq_save(flags); input = *this_cpu_ptr(hyperv_pcpu_input_arg); memset(input, 0, sizeof(*input)); - intr_entry = &input->interrupt_entry; input->partition_id = hv_current_partition_id; input->device_id = id; - *intr_entry = *old_entry; + input->interrupt_entry = *irq_entry; status = hv_do_hypercall(HVCALL_UNMAP_DEVICE_INTERRUPT, input, NULL); local_irq_restore(flags); @@ -115,67 +112,71 @@ static int get_rid_cb(struct pci_dev *pdev, u16 alias, void *data) return 0; } -static union hv_device_id hv_build_pci_dev_id(struct pci_dev *dev) +static union hv_device_id hv_build_devid_type_pci(struct pci_dev *pdev) { - union hv_device_id dev_id; + int pos; + union hv_device_id hv_devid; struct rid_data data = { .bridge = NULL, - .rid = PCI_DEVID(dev->bus->number, dev->devfn) + .rid = PCI_DEVID(pdev->bus->number, pdev->devfn) }; - pci_for_each_dma_alias(dev, get_rid_cb, &data); + pci_for_each_dma_alias(pdev, get_rid_cb, &data); - dev_id.as_uint64 = 0; - dev_id.device_type = HV_DEVICE_TYPE_PCI; - dev_id.pci.segment = pci_domain_nr(dev->bus); + hv_devid.as_uint64 = 0; + hv_devid.device_type = HV_DEVICE_TYPE_PCI; + hv_devid.pci.segment = pci_domain_nr(pdev->bus); - dev_id.pci.bdf.bus = PCI_BUS_NUM(data.rid); - dev_id.pci.bdf.device = PCI_SLOT(data.rid); - dev_id.pci.bdf.function = PCI_FUNC(data.rid); - dev_id.pci.source_shadow = HV_SOURCE_SHADOW_NONE; + hv_devid.pci.bdf.bus = PCI_BUS_NUM(data.rid); + hv_devid.pci.bdf.device = PCI_SLOT(data.rid); + hv_devid.pci.bdf.function = PCI_FUNC(data.rid); + hv_devid.pci.source_shadow = HV_SOURCE_SHADOW_NONE; - if (data.bridge) { - int pos; + if (data.bridge == NULL) + goto out; - /* - * Microsoft Hypervisor requires a bus range when the bridge is - * running in PCI-X mode. - * - * To distinguish conventional vs PCI-X bridge, we can check - * the bridge's PCI-X Secondary Status Register, Secondary Bus - * Mode and Frequency bits. See PCI Express to PCI/PCI-X Bridge - * Specification Revision 1.0 5.2.2.1.3. - * - * Value zero means it is in conventional mode, otherwise it is - * in PCI-X mode. - */ + /* + * Microsoft Hypervisor requires a bus range when the bridge is + * running in PCI-X mode. + * + * To distinguish conventional vs PCI-X bridge, we can check + * the bridge's PCI-X Secondary Status Register, Secondary Bus + * Mode and Frequency bits. See PCI Express to PCI/PCI-X Bridge + * Specification Revision 1.0 5.2.2.1.3. + * + * Value zero means it is in conventional mode, otherwise it is + * in PCI-X mode. + */ - pos = pci_find_capability(data.bridge, PCI_CAP_ID_PCIX); - if (pos) { - u16 status; + pos = pci_find_capability(data.bridge, PCI_CAP_ID_PCIX); + if (pos) { + u16 status; - pci_read_config_word(data.bridge, pos + - PCI_X_BRIDGE_SSTATUS, &status); + pci_read_config_word(data.bridge, pos + PCI_X_BRIDGE_SSTATUS, + &status); - if (status & PCI_X_SSTATUS_FREQ) { - /* Non-zero, PCI-X mode */ - u8 sec_bus, sub_bus; + if (status & PCI_X_SSTATUS_FREQ) { + /* Non-zero, PCI-X mode */ + u8 sec_bus, sub_bus; - dev_id.pci.source_shadow = HV_SOURCE_SHADOW_BRIDGE_BUS_RANGE; + hv_devid.pci.source_shadow = + HV_SOURCE_SHADOW_BRIDGE_BUS_RANGE; - pci_read_config_byte(data.bridge, PCI_SECONDARY_BUS, &sec_bus); - dev_id.pci.shadow_bus_range.secondary_bus = sec_bus; - pci_read_config_byte(data.bridge, PCI_SUBORDINATE_BUS, &sub_bus); - dev_id.pci.shadow_bus_range.subordinate_bus = sub_bus; - } + pci_read_config_byte(data.bridge, PCI_SECONDARY_BUS, + &sec_bus); + hv_devid.pci.shadow_bus_range.secondary_bus = sec_bus; + pci_read_config_byte(data.bridge, PCI_SUBORDINATE_BUS, + &sub_bus); + hv_devid.pci.shadow_bus_range.subordinate_bus = sub_bus; } } - return dev_id; +out: + return hv_devid; } -/** - * hv_map_msi_interrupt() - "Map" the MSI IRQ in the hypervisor. +/* + * hv_map_msi_interrupt() - Map the MSI IRQ in the hypervisor. * @data: Describes the IRQ * @out_entry: Hypervisor (MSI) interrupt entry (can be NULL) * @@ -188,22 +189,23 @@ int hv_map_msi_interrupt(struct irq_data *data, { struct irq_cfg *cfg = irqd_cfg(data); struct hv_interrupt_entry dummy; - union hv_device_id device_id; + union hv_device_id hv_devid; struct msi_desc *msidesc; - struct pci_dev *dev; + struct pci_dev *pdev; int cpu; msidesc = irq_data_get_msi_desc(data); - dev = msi_desc_to_pci_dev(msidesc); - device_id = hv_build_pci_dev_id(dev); + pdev = msi_desc_to_pci_dev(msidesc); + hv_devid = hv_build_devid_type_pci(pdev); cpu = cpumask_first(irq_data_get_effective_affinity_mask(data)); - return hv_map_interrupt(device_id, false, cpu, cfg->vector, + return hv_map_interrupt(hv_devid, false, cpu, cfg->vector, out_entry ? out_entry : &dummy); } EXPORT_SYMBOL_GPL(hv_map_msi_interrupt); -static inline void entry_to_msi_msg(struct hv_interrupt_entry *entry, struct msi_msg *msg) +static void entry_to_msi_msg(struct hv_interrupt_entry *entry, + struct msi_msg *msg) { /* High address is always 0 */ msg->address_hi = 0; @@ -211,17 +213,19 @@ static inline void entry_to_msi_msg(struct hv_interrupt_entry *entry, struct msi msg->data = entry->msi_entry.data.as_uint32; } -static int hv_unmap_msi_interrupt(struct pci_dev *dev, struct hv_interrupt_entry *old_entry); +static int hv_unmap_msi_interrupt(struct pci_dev *pdev, + struct hv_interrupt_entry *irq_entry); + static void hv_irq_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) { struct hv_interrupt_entry *stored_entry; struct irq_cfg *cfg = irqd_cfg(data); struct msi_desc *msidesc; - struct pci_dev *dev; + struct pci_dev *pdev; int ret; msidesc = irq_data_get_msi_desc(data); - dev = msi_desc_to_pci_dev(msidesc); + pdev = msi_desc_to_pci_dev(msidesc); if (!cfg) { pr_debug("%s: cfg is NULL", __func__); @@ -240,7 +244,7 @@ static void hv_irq_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) stored_entry = data->chip_data; data->chip_data = NULL; - ret = hv_unmap_msi_interrupt(dev, stored_entry); + ret = hv_unmap_msi_interrupt(pdev, stored_entry); kfree(stored_entry); @@ -249,10 +253,8 @@ static void hv_irq_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) } stored_entry = kzalloc(sizeof(*stored_entry), GFP_ATOMIC); - if (!stored_entry) { - pr_debug("%s: failed to allocate chip data\n", __func__); + if (!stored_entry) return; - } ret = hv_map_msi_interrupt(data, stored_entry); if (ret) { @@ -262,18 +264,21 @@ static void hv_irq_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) data->chip_data = stored_entry; entry_to_msi_msg(data->chip_data, msg); - - return; } -static int hv_unmap_msi_interrupt(struct pci_dev *dev, struct hv_interrupt_entry *old_entry) +static int hv_unmap_msi_interrupt(struct pci_dev *pdev, + struct hv_interrupt_entry *irq_entry) { - return hv_unmap_interrupt(hv_build_pci_dev_id(dev).as_uint64, old_entry); + union hv_device_id hv_devid; + + hv_devid = hv_build_devid_type_pci(pdev); + return hv_unmap_interrupt(hv_devid.as_uint64, irq_entry); } -static void hv_teardown_msi_irq(struct pci_dev *dev, struct irq_data *irqd) +/* NB: during map, hv_interrupt_entry is saved via data->chip_data */ +static void hv_teardown_msi_irq(struct pci_dev *pdev, struct irq_data *irqd) { - struct hv_interrupt_entry old_entry; + struct hv_interrupt_entry irq_entry; struct msi_msg msg; if (!irqd->chip_data) { @@ -281,13 +286,13 @@ static void hv_teardown_msi_irq(struct pci_dev *dev, struct irq_data *irqd) return; } - old_entry = *(struct hv_interrupt_entry *)irqd->chip_data; - entry_to_msi_msg(&old_entry, &msg); + irq_entry = *(struct hv_interrupt_entry *)irqd->chip_data; + entry_to_msi_msg(&irq_entry, &msg); kfree(irqd->chip_data); irqd->chip_data = NULL; - (void)hv_unmap_msi_interrupt(dev, &old_entry); + (void)hv_unmap_msi_interrupt(pdev, &irq_entry); } /* @@ -302,7 +307,8 @@ static struct irq_chip hv_pci_msi_controller = { }; static bool hv_init_dev_msi_info(struct device *dev, struct irq_domain *domain, - struct irq_domain *real_parent, struct msi_domain_info *info) + struct irq_domain *real_parent, + struct msi_domain_info *info) { struct irq_chip *chip = info->chip; @@ -317,7 +323,8 @@ static bool hv_init_dev_msi_info(struct device *dev, struct irq_domain *domain, } #define HV_MSI_FLAGS_SUPPORTED (MSI_GENERIC_FLAGS_MASK | MSI_FLAG_PCI_MSIX) -#define HV_MSI_FLAGS_REQUIRED (MSI_FLAG_USE_DEF_DOM_OPS | MSI_FLAG_USE_DEF_CHIP_OPS) +#define HV_MSI_FLAGS_REQUIRED (MSI_FLAG_USE_DEF_DOM_OPS | \ + MSI_FLAG_USE_DEF_CHIP_OPS) static struct msi_parent_ops hv_msi_parent_ops = { .supported_flags = HV_MSI_FLAGS_SUPPORTED, @@ -329,14 +336,13 @@ static struct msi_parent_ops hv_msi_parent_ops = { .init_dev_msi_info = hv_init_dev_msi_info, }; -static int hv_msi_domain_alloc(struct irq_domain *d, unsigned int virq, unsigned int nr_irqs, - void *arg) +static int hv_msi_domain_alloc(struct irq_domain *d, unsigned int virq, + unsigned int nr_irqs, void *arg) { /* - * TODO: The allocation bits of hv_irq_compose_msi_msg(), i.e. everything except - * entry_to_msi_msg() should be in here. + * TODO: The allocation bits of hv_irq_compose_msi_msg(), i.e. + * everything except entry_to_msi_msg() should be in here. */ - int ret; ret = irq_domain_alloc_irqs_parent(d, virq, nr_irqs, arg); @@ -344,13 +350,15 @@ static int hv_msi_domain_alloc(struct irq_domain *d, unsigned int virq, unsigned return ret; for (int i = 0; i < nr_irqs; ++i) { - irq_domain_set_info(d, virq + i, 0, &hv_pci_msi_controller, NULL, - handle_edge_irq, NULL, "edge"); + irq_domain_set_info(d, virq + i, 0, &hv_pci_msi_controller, + NULL, handle_edge_irq, NULL, "edge"); } + return 0; } -static void hv_msi_domain_free(struct irq_domain *d, unsigned int virq, unsigned int nr_irqs) +static void hv_msi_domain_free(struct irq_domain *d, unsigned int virq, + unsigned int nr_irqs) { for (int i = 0; i < nr_irqs; ++i) { struct irq_data *irqd = irq_domain_get_irq_data(d, virq); @@ -362,6 +370,7 @@ static void hv_msi_domain_free(struct irq_domain *d, unsigned int virq, unsigned hv_teardown_msi_irq(to_pci_dev(desc->dev), irqd); } + irq_domain_free_irqs_top(d, virq, nr_irqs); } @@ -394,25 +403,25 @@ struct irq_domain * __init hv_create_pci_msi_domain(void) int hv_unmap_ioapic_interrupt(int ioapic_id, struct hv_interrupt_entry *entry) { - union hv_device_id device_id; + union hv_device_id hv_devid; - device_id.as_uint64 = 0; - device_id.device_type = HV_DEVICE_TYPE_IOAPIC; - device_id.ioapic.ioapic_id = (u8)ioapic_id; + hv_devid.as_uint64 = 0; + hv_devid.device_type = HV_DEVICE_TYPE_IOAPIC; + hv_devid.ioapic.ioapic_id = (u8)ioapic_id; - return hv_unmap_interrupt(device_id.as_uint64, entry); + return hv_unmap_interrupt(hv_devid.as_uint64, entry); } EXPORT_SYMBOL_GPL(hv_unmap_ioapic_interrupt); int hv_map_ioapic_interrupt(int ioapic_id, bool level, int cpu, int vector, struct hv_interrupt_entry *entry) { - union hv_device_id device_id; + union hv_device_id hv_devid; - device_id.as_uint64 = 0; - device_id.device_type = HV_DEVICE_TYPE_IOAPIC; - device_id.ioapic.ioapic_id = (u8)ioapic_id; + hv_devid.as_uint64 = 0; + hv_devid.device_type = HV_DEVICE_TYPE_IOAPIC; + hv_devid.ioapic.ioapic_id = (u8)ioapic_id; - return hv_map_interrupt(device_id, level, cpu, vector, entry); + return hv_map_interrupt(hv_devid, level, cpu, vector, entry); } EXPORT_SYMBOL_GPL(hv_map_ioapic_interrupt); -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:17 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Add a new file to implement VFIO-MSHV bridge pseudo device. These functions are called in the VFIO framework, and credits to kvm/vfio.c as this file was adapted from it. Original author: Wei Liu <wei.liu@kernel.org> (Slightly modified from the original version). Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- drivers/hv/Makefile | 3 +- drivers/hv/mshv_vfio.c | 210 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 drivers/hv/mshv_vfio.c diff --git a/drivers/hv/Makefile b/drivers/hv/Makefile index a49f93c2d245..eae003c4cb8f 100644 --- a/drivers/hv/Makefile +++ b/drivers/hv/Makefile @@ -14,7 +14,8 @@ hv_vmbus-y := vmbus_drv.o \ hv_vmbus-$(CONFIG_HYPERV_TESTING) += hv_debugfs.o hv_utils-y := hv_util.o hv_kvp.o hv_snapshot.o hv_utils_transport.o mshv_root-y := mshv_root_main.o mshv_synic.o mshv_eventfd.o mshv_irq.o \ - mshv_root_hv_call.o mshv_portid_table.o mshv_regions.o + mshv_root_hv_call.o mshv_portid_table.o mshv_regions.o \ + mshv_vfio.o mshv_vtl-y := mshv_vtl_main.o # Code that must be built-in diff --git a/drivers/hv/mshv_vfio.c b/drivers/hv/mshv_vfio.c new file mode 100644 index 000000000000..6ea4d99a3bd2 --- /dev/null +++ b/drivers/hv/mshv_vfio.c @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * VFIO-MSHV bridge pseudo device + * + * Heavily inspired by the VFIO-KVM bridge pseudo device. + */ +#include <linux/errno.h> +#include <linux/file.h> +#include <linux/list.h> +#include <linux/module.h> +#include <linux/mutex.h> +#include <linux/slab.h> +#include <linux/vfio.h> + +#include "mshv.h" +#include "mshv_root.h" + +struct mshv_vfio_file { + struct list_head node; + struct file *file; /* list of struct mshv_vfio_file */ +}; + +struct mshv_vfio { + struct list_head file_list; + struct mutex lock; +}; + +static bool mshv_vfio_file_is_valid(struct file *file) +{ + bool (*fn)(struct file *file); + bool ret; + + fn = symbol_get(vfio_file_is_valid); + if (!fn) + return false; + + ret = fn(file); + + symbol_put(vfio_file_is_valid); + + return ret; +} + +static long mshv_vfio_file_add(struct mshv_device *mshvdev, unsigned int fd) +{ + struct mshv_vfio *mshv_vfio = mshvdev->device_private; + struct mshv_vfio_file *mvf; + struct file *filp; + long ret = 0; + + filp = fget(fd); + if (!filp) + return -EBADF; + + /* Ensure the FD is a vfio FD. */ + if (!mshv_vfio_file_is_valid(filp)) { + ret = -EINVAL; + goto out_fput; + } + + mutex_lock(&mshv_vfio->lock); + + list_for_each_entry(mvf, &mshv_vfio->file_list, node) { + if (mvf->file == filp) { + ret = -EEXIST; + goto out_unlock; + } + } + + mvf = kzalloc(sizeof(*mvf), GFP_KERNEL_ACCOUNT); + if (!mvf) { + ret = -ENOMEM; + goto out_unlock; + } + + mvf->file = get_file(filp); + list_add_tail(&mvf->node, &mshv_vfio->file_list); + +out_unlock: + mutex_unlock(&mshv_vfio->lock); +out_fput: + fput(filp); + return ret; +} + +static long mshv_vfio_file_del(struct mshv_device *mshvdev, unsigned int fd) +{ + struct mshv_vfio *mshv_vfio = mshvdev->device_private; + struct mshv_vfio_file *mvf; + long ret; + + CLASS(fd, f)(fd); + + if (fd_empty(f)) + return -EBADF; + + ret = -ENOENT; + mutex_lock(&mshv_vfio->lock); + + list_for_each_entry(mvf, &mshv_vfio->file_list, node) { + if (mvf->file != fd_file(f)) + continue; + + list_del(&mvf->node); + fput(mvf->file); + kfree(mvf); + ret = 0; + break; + } + + mutex_unlock(&mshv_vfio->lock); + return ret; +} + +static long mshv_vfio_set_file(struct mshv_device *mshvdev, long attr, + void __user *arg) +{ + int32_t __user *argp = arg; + int32_t fd; + + switch (attr) { + case MSHV_DEV_VFIO_FILE_ADD: + if (get_user(fd, argp)) + return -EFAULT; + return mshv_vfio_file_add(mshvdev, fd); + + case MSHV_DEV_VFIO_FILE_DEL: + if (get_user(fd, argp)) + return -EFAULT; + return mshv_vfio_file_del(mshvdev, fd); + } + + return -ENXIO; +} + +static long mshv_vfio_set_attr(struct mshv_device *mshvdev, + struct mshv_device_attr *attr) +{ + switch (attr->group) { + case MSHV_DEV_VFIO_FILE: + return mshv_vfio_set_file(mshvdev, attr->attr, + u64_to_user_ptr(attr->addr)); + } + + return -ENXIO; +} + +static long mshv_vfio_has_attr(struct mshv_device *mshvdev, + struct mshv_device_attr *attr) +{ + switch (attr->group) { + case MSHV_DEV_VFIO_FILE: + switch (attr->attr) { + case MSHV_DEV_VFIO_FILE_ADD: + case MSHV_DEV_VFIO_FILE_DEL: + return 0; + } + + break; + } + + return -ENXIO; +} + +static long mshv_vfio_create_device(struct mshv_device *mshvdev, u32 type) +{ + struct mshv_device *tmp; + struct mshv_vfio *mshv_vfio; + + /* Only one VFIO "device" per VM */ + hlist_for_each_entry(tmp, &mshvdev->device_pt->pt_devices, + device_ptnode) + if (tmp->device_ops == &mshv_vfio_device_ops) + return -EBUSY; + + mshv_vfio = kzalloc(sizeof(*mshv_vfio), GFP_KERNEL_ACCOUNT); + if (mshv_vfio == NULL) + return -ENOMEM; + + INIT_LIST_HEAD(&mshv_vfio->file_list); + mutex_init(&mshv_vfio->lock); + + mshvdev->device_private = mshv_vfio; + + return 0; +} + +/* This is called from mshv_device_fop_release() */ +static void mshv_vfio_release_device(struct mshv_device *mshvdev) +{ + struct mshv_vfio *mv = mshvdev->device_private; + struct mshv_vfio_file *mvf, *tmp; + + list_for_each_entry_safe(mvf, tmp, &mv->file_list, node) { + fput(mvf->file); + list_del(&mvf->node); + kfree(mvf); + } + + kfree(mv); + kfree(mshvdev); +} + +struct mshv_device_ops mshv_vfio_device_ops = { + .device_name = "mshv-vfio", + .device_create = mshv_vfio_create_device, + .device_release = mshv_vfio_release_device, + .device_set_attr = mshv_vfio_set_attr, + .device_has_attr = mshv_vfio_has_attr, +}; -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:21 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> As mentioned previously, a direct attached device must be referenced via logical device id which is formed in the initial attach hypercall. Interrupt mapping paths for direct attached devices are almost same, except we must use logical device ids instead of the PCI device ids. L1VH only supports direct attaches for passing thru devices to its guests, and devices on L1VH are VMBus based. However, the interrupts are mapped via the map interrupt hypercall and not the traditional method of VMBus messages. Partition id for the relevant hypercalls is tricky. This because a device could be moving from root to guest and then back to the root. In case of L1VH, it could be moving from system host to L1VH root to a guest, then back to the L1VH root. So, it is carefully crafted by keeping track of whether the call is on behalf of a VMM process, whether the device is attached device (as opposed to mapped), and whether we are in an L1VH root/parent. If VMM process, we assume it is on behalf of a guest. Otherwise, the device is being attached or detached during boot or shutdown of the privileged partition. Lastly, a dummy cpu and vector is used to map interrupt for a direct attached device. This because, once a device is marked for direct attach, hypervisor will not let any interrupts be mapped to host. So it is mapped to guest dummy cpu and dummy vector. This is then correctly mapped during guest boot via the retarget paths. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- arch/arm64/include/asm/mshyperv.h | 15 +++++ arch/x86/hyperv/irqdomain.c | 57 +++++++++++++----- arch/x86/include/asm/mshyperv.h | 4 ++ drivers/pci/controller/pci-hyperv.c | 91 +++++++++++++++++++++++++---- 4 files changed, 142 insertions(+), 25 deletions(-) diff --git a/arch/arm64/include/asm/mshyperv.h b/arch/arm64/include/asm/mshyperv.h index b721d3134ab6..27da480f94f6 100644 --- a/arch/arm64/include/asm/mshyperv.h +++ b/arch/arm64/include/asm/mshyperv.h @@ -53,6 +53,21 @@ static inline u64 hv_get_non_nested_msr(unsigned int reg) return hv_get_msr(reg); } +struct irq_data; +struct msi_msg; +struct pci_dev; +static inline void hv_irq_compose_msi_msg(struct irq_data *data, + struct msi_msg *msg) {}; +static inline int hv_unmap_msi_interrupt(struct pci_dev *pdev, + struct hv_interrupt_entry *hvirqe) +{ + return -EOPNOTSUPP; +} +static inline bool hv_pcidev_is_attached_dev(struct pci_dev *pdev) +{ + return false; +} + /* SMCCC hypercall parameters */ #define HV_SMCCC_FUNC_NUMBER 1 #define HV_FUNC_ID ARM_SMCCC_CALL_VAL( \ diff --git a/arch/x86/hyperv/irqdomain.c b/arch/x86/hyperv/irqdomain.c index 33017aa0caa4..e6eb457f791e 100644 --- a/arch/x86/hyperv/irqdomain.c +++ b/arch/x86/hyperv/irqdomain.c @@ -13,6 +13,16 @@ #include <linux/irqchip/irq-msi-lib.h> #include <asm/mshyperv.h> +/* + * For direct attached devices (which use logical device ids), hypervisor will + * not allow mappings to host. But VFIO needs to bind the interrupt at the very + * start before the guest cpu/vector is known. So we use dummy cpu and vector + * to bind in such case, and later when the guest starts, retarget will move it + * to correct guest cpu and vector. + */ +#define HV_DDA_DUMMY_CPU 0 +#define HV_DDA_DUMMY_VECTOR 32 + static u64 hv_map_interrupt_hcall(u64 ptid, union hv_device_id hv_devid, bool level, int cpu, int vector, struct hv_interrupt_entry *ret_entry) @@ -24,6 +34,11 @@ static u64 hv_map_interrupt_hcall(u64 ptid, union hv_device_id hv_devid, u64 status; int nr_bank, var_size; + if (hv_devid.device_type == HV_DEVICE_TYPE_LOGICAL) { + cpu = HV_DDA_DUMMY_CPU; + vector = HV_DDA_DUMMY_VECTOR; + } + local_irq_save(flags); input = *this_cpu_ptr(hyperv_pcpu_input_arg); @@ -95,7 +110,8 @@ static int hv_map_interrupt(u64 ptid, union hv_device_id device_id, bool level, return hv_result_to_errno(status); } -static int hv_unmap_interrupt(u64 id, struct hv_interrupt_entry *irq_entry) +static int hv_unmap_interrupt(union hv_device_id hv_devid, + struct hv_interrupt_entry *irq_entry) { unsigned long flags; struct hv_input_unmap_device_interrupt *input; @@ -103,10 +119,14 @@ static int hv_unmap_interrupt(u64 id, struct hv_interrupt_entry *irq_entry) local_irq_save(flags); input = *this_cpu_ptr(hyperv_pcpu_input_arg); - memset(input, 0, sizeof(*input)); - input->partition_id = hv_current_partition_id; - input->device_id = id; + + if (hv_devid.device_type == HV_DEVICE_TYPE_LOGICAL) + input->partition_id = hv_iommu_get_curr_partid(); + else + input->partition_id = hv_current_partition_id; + + input->device_id = hv_devid.as_uint64; input->interrupt_entry = *irq_entry; status = hv_do_hypercall(HVCALL_UNMAP_DEVICE_INTERRUPT, input, NULL); @@ -263,6 +283,7 @@ static u64 hv_build_irq_devid(struct pci_dev *pdev) int hv_map_msi_interrupt(struct irq_data *data, struct hv_interrupt_entry *out_entry) { + u64 ptid; struct irq_cfg *cfg = irqd_cfg(data); struct hv_interrupt_entry dummy; union hv_device_id hv_devid; @@ -275,8 +296,17 @@ int hv_map_msi_interrupt(struct irq_data *data, hv_devid.as_uint64 = hv_build_irq_devid(pdev); cpu = cpumask_first(irq_data_get_effective_affinity_mask(data)); - return hv_map_interrupt(hv_current_partition_id, hv_devid, false, cpu, - cfg->vector, out_entry ? out_entry : &dummy); + if (hv_devid.device_type == HV_DEVICE_TYPE_LOGICAL) + if (hv_pcidev_is_attached_dev(pdev)) + ptid = hv_iommu_get_curr_partid(); + else + /* Device actually on l1vh root, not passthru'd to vm */ + ptid = hv_current_partition_id; + else + ptid = hv_current_partition_id; + + return hv_map_interrupt(ptid, hv_devid, false, cpu, cfg->vector, + out_entry ? out_entry : &dummy); } EXPORT_SYMBOL_GPL(hv_map_msi_interrupt); @@ -289,10 +319,7 @@ static void entry_to_msi_msg(struct hv_interrupt_entry *entry, msg->data = entry->msi_entry.data.as_uint32; } -static int hv_unmap_msi_interrupt(struct pci_dev *pdev, - struct hv_interrupt_entry *irq_entry); - -static void hv_irq_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) +void hv_irq_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) { struct hv_interrupt_entry *stored_entry; struct irq_cfg *cfg = irqd_cfg(data); @@ -341,16 +368,18 @@ static void hv_irq_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) data->chip_data = stored_entry; entry_to_msi_msg(data->chip_data, msg); } +EXPORT_SYMBOL_GPL(hv_irq_compose_msi_msg); -static int hv_unmap_msi_interrupt(struct pci_dev *pdev, - struct hv_interrupt_entry *irq_entry) +int hv_unmap_msi_interrupt(struct pci_dev *pdev, + struct hv_interrupt_entry *irq_entry) { union hv_device_id hv_devid; hv_devid.as_uint64 = hv_build_irq_devid(pdev); - return hv_unmap_interrupt(hv_devid.as_uint64, irq_entry); + return hv_unmap_interrupt(hv_devid, irq_entry); } +EXPORT_SYMBOL_GPL(hv_unmap_msi_interrupt); /* NB: during map, hv_interrupt_entry is saved via data->chip_data */ static void hv_teardown_msi_irq(struct pci_dev *pdev, struct irq_data *irqd) @@ -486,7 +515,7 @@ int hv_unmap_ioapic_interrupt(int ioapic_id, struct hv_interrupt_entry *entry) hv_devid.device_type = HV_DEVICE_TYPE_IOAPIC; hv_devid.ioapic.ioapic_id = (u8)ioapic_id; - return hv_unmap_interrupt(hv_devid.as_uint64, entry); + return hv_unmap_interrupt(hv_devid, entry); } EXPORT_SYMBOL_GPL(hv_unmap_ioapic_interrupt); diff --git a/arch/x86/include/asm/mshyperv.h b/arch/x86/include/asm/mshyperv.h index e4ccdbbf1d12..b6facd3a0f5e 100644 --- a/arch/x86/include/asm/mshyperv.h +++ b/arch/x86/include/asm/mshyperv.h @@ -204,11 +204,15 @@ static inline u64 hv_iommu_get_curr_partid(void) #endif /* CONFIG_HYPERV_IOMMU */ u64 hv_pci_vmbus_device_id(struct pci_dev *pdev); +void hv_irq_compose_msi_msg(struct irq_data *data, struct msi_msg *msg); +extern bool hv_no_attdev; struct irq_domain *hv_create_pci_msi_domain(void); int hv_map_msi_interrupt(struct irq_data *data, struct hv_interrupt_entry *out_entry); +int hv_unmap_msi_interrupt(struct pci_dev *dev, + struct hv_interrupt_entry *hvirqe); int hv_map_ioapic_interrupt(int ioapic_id, bool level, int vcpu, int vector, struct hv_interrupt_entry *entry); int hv_unmap_ioapic_interrupt(int ioapic_id, struct hv_interrupt_entry *entry); diff --git a/drivers/pci/controller/pci-hyperv.c b/drivers/pci/controller/pci-hyperv.c index 40f0b06bb966..71d1599dc4a8 100644 --- a/drivers/pci/controller/pci-hyperv.c +++ b/drivers/pci/controller/pci-hyperv.c @@ -660,15 +660,17 @@ static void hv_irq_retarget_interrupt(struct irq_data *data) params = *this_cpu_ptr(hyperv_pcpu_input_arg); memset(params, 0, sizeof(*params)); - params->partition_id = HV_PARTITION_ID_SELF; + + if (hv_pcidev_is_attached_dev(pdev)) + params->partition_id = hv_iommu_get_curr_partid(); + else + params->partition_id = HV_PARTITION_ID_SELF; + params->int_entry.source = HV_INTERRUPT_SOURCE_MSI; - params->int_entry.msi_entry.address.as_uint32 = int_desc->address & 0xffffffff; + params->int_entry.msi_entry.address.as_uint32 = + int_desc->address & 0xffffffff; params->int_entry.msi_entry.data.as_uint32 = int_desc->data; - params->device_id = (hbus->hdev->dev_instance.b[5] << 24) | - (hbus->hdev->dev_instance.b[4] << 16) | - (hbus->hdev->dev_instance.b[7] << 8) | - (hbus->hdev->dev_instance.b[6] & 0xf8) | - PCI_FUNC(pdev->devfn); + params->device_id = hv_pci_vmbus_device_id(pdev); params->int_target.vector = hv_msi_get_int_vector(data); if (hbus->protocol_version >= PCI_PROTOCOL_VERSION_1_2) { @@ -1263,6 +1265,15 @@ static void _hv_pcifront_read_config(struct hv_pci_dev *hpdev, int where, mb(); } spin_unlock_irqrestore(&hbus->config_lock, flags); + /* + * Make sure PCI_INTERRUPT_PIN is hard-wired to 0 since it may + * be read using a 32bit read which is skipped by the above + * emulation. + */ + if (PCI_INTERRUPT_PIN >= where && + PCI_INTERRUPT_PIN <= (where + size)) { + *((char *)val + PCI_INTERRUPT_PIN - where) = 0; + } } else { dev_err(dev, "Attempt to read beyond a function's config space.\n"); } @@ -1731,14 +1742,22 @@ static void hv_msi_free(struct irq_domain *domain, unsigned int irq) if (!int_desc) return; - irq_data->chip_data = NULL; hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn)); if (!hpdev) { + irq_data->chip_data = NULL; kfree(int_desc); return; } - hv_int_desc_free(hpdev, int_desc); + if (hv_pcidev_is_attached_dev(pdev)) { + hv_unmap_msi_interrupt(pdev, irq_data->chip_data); + kfree(irq_data->chip_data); + irq_data->chip_data = NULL; + } else { + irq_data->chip_data = NULL; + hv_int_desc_free(hpdev, int_desc); + } + put_pcichild(hpdev); } @@ -2139,6 +2158,56 @@ static void hv_vmbus_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) msg->data = 0; } +/* Compose an msi message for a directly attached device */ +static void hv_dda_compose_msi_msg(struct irq_data *irq_data, + struct msi_desc *msi_desc, + struct msi_msg *msg) +{ + bool multi_msi; + struct hv_pcibus_device *hbus; + struct hv_pci_dev *hpdev; + struct pci_dev *pdev = msi_desc_to_pci_dev(msi_desc); + + multi_msi = !msi_desc->pci.msi_attrib.is_msix && + msi_desc->nvec_used > 1; + + if (multi_msi) { + dev_err(&hbus->hdev->device, + "Passthru direct attach does not support multi msi\n"); + goto outerr; + } + + hbus = container_of(pdev->bus->sysdata, struct hv_pcibus_device, + sysdata); + + hpdev = get_pcichild_wslot(hbus, devfn_to_wslot(pdev->devfn)); + if (!hpdev) + goto outerr; + + /* will unmap if needed and also update irq_data->chip_data */ + hv_irq_compose_msi_msg(irq_data, msg); + + put_pcichild(hpdev); + return; + +outerr: + memset(msg, 0, sizeof(*msg)); +} + +static void hv_compose_msi_msg(struct irq_data *data, struct msi_msg *msg) +{ + struct pci_dev *pdev; + struct msi_desc *msi_desc; + + msi_desc = irq_data_get_msi_desc(data); + pdev = msi_desc_to_pci_dev(msi_desc); + + if (hv_pcidev_is_attached_dev(pdev)) + hv_dda_compose_msi_msg(data, msi_desc, msg); + else + hv_vmbus_compose_msi_msg(data, msg); +} + static bool hv_pcie_init_dev_msi_info(struct device *dev, struct irq_domain *domain, struct irq_domain *real_parent, struct msi_domain_info *info) { @@ -2177,7 +2246,7 @@ static const struct msi_parent_ops hv_pcie_msi_parent_ops = { /* HW Interrupt Chip Descriptor */ static struct irq_chip hv_msi_irq_chip = { .name = "Hyper-V PCIe MSI", - .irq_compose_msi_msg = hv_vmbus_compose_msi_msg, + .irq_compose_msi_msg = hv_compose_msi_msg, .irq_set_affinity = irq_chip_set_affinity_parent, .irq_ack = irq_chip_ack_parent, .irq_eoi = irq_chip_eoi_parent, @@ -4096,7 +4165,7 @@ static int hv_pci_restore_msi_msg(struct pci_dev *pdev, void *arg) irq_data = irq_get_irq_data(entry->irq); if (WARN_ON_ONCE(!irq_data)) return -EINVAL; - hv_vmbus_compose_msi_msg(irq_data, &entry->msg); + hv_compose_msi_msg(irq_data, &entry->msg); } return 0; } -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:28 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Upon guest access, in case of missing mmio mapping, the hypervisor generates an unmapped gpa intercept. In this path, lookup the PCI resource pfn for the guest gpa, and ask the hypervisor to map it via hypercall. The PCI resource pfn is maintained by the VFIO driver, and obtained via fixup_user_fault call (similar to KVM). Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- drivers/hv/mshv_root_main.c | 115 ++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/drivers/hv/mshv_root_main.c b/drivers/hv/mshv_root_main.c index 03f3aa9f5541..4c8bc7cd0888 100644 --- a/drivers/hv/mshv_root_main.c +++ b/drivers/hv/mshv_root_main.c @@ -56,6 +56,14 @@ struct hv_stats_page { }; } __packed; +bool hv_nofull_mmio; /* don't map entire mmio region upon fault */ +static int __init setup_hv_full_mmio(char *str) +{ + hv_nofull_mmio = true; + return 0; +} +__setup("hv_nofull_mmio", setup_hv_full_mmio); + struct mshv_root mshv_root; enum hv_scheduler_type hv_scheduler_type; @@ -612,6 +620,109 @@ mshv_partition_region_by_gfn(struct mshv_partition *partition, u64 gfn) } #ifdef CONFIG_X86_64 + +/* + * Check if uaddr is for mmio range. If yes, return 0 with mmio_pfn filled in + * else just return -errno. + */ +static int mshv_chk_get_mmio_start_pfn(struct mshv_partition *pt, u64 gfn, + u64 *mmio_pfnp) +{ + struct vm_area_struct *vma; + bool is_mmio; + u64 uaddr; + struct mshv_mem_region *mreg; + struct follow_pfnmap_args pfnmap_args; + int rc = -EINVAL; + + /* + * Do not allow mem region to be deleted beneath us. VFIO uses + * useraddr vma to lookup pci bar pfn. + */ + spin_lock(&pt->pt_mem_regions_lock); + + /* Get the region again under the lock */ + mreg = mshv_partition_region_by_gfn(pt, gfn); + if (mreg == NULL || mreg->type != MSHV_REGION_TYPE_MMIO) + goto unlock_pt_out; + + uaddr = mreg->start_uaddr + + ((gfn - mreg->start_gfn) << HV_HYP_PAGE_SHIFT); + + mmap_read_lock(current->mm); + vma = vma_lookup(current->mm, uaddr); + is_mmio = vma ? !!(vma->vm_flags & (VM_IO | VM_PFNMAP)) : 0; + if (!is_mmio) + goto unlock_mmap_out; + + pfnmap_args.vma = vma; + pfnmap_args.address = uaddr; + + rc = follow_pfnmap_start(&pfnmap_args); + if (rc) { + rc = fixup_user_fault(current->mm, uaddr, FAULT_FLAG_WRITE, + NULL); + if (rc) + goto unlock_mmap_out; + + rc = follow_pfnmap_start(&pfnmap_args); + if (rc) + goto unlock_mmap_out; + } + + *mmio_pfnp = pfnmap_args.pfn; + follow_pfnmap_end(&pfnmap_args); + +unlock_mmap_out: + mmap_read_unlock(current->mm); +unlock_pt_out: + spin_unlock(&pt->pt_mem_regions_lock); + return rc; +} + +/* + * At present, the only unmapped gpa is mmio space. Verify if it's mmio + * and resolve if possible. + * Returns: True if valid mmio intercept and it was handled, else false + */ +static bool mshv_handle_unmapped_gpa(struct mshv_vp *vp) +{ + struct hv_message *hvmsg = vp->vp_intercept_msg_page; + struct hv_x64_memory_intercept_message *msg; + union hv_x64_memory_access_info accinfo; + u64 gfn, mmio_spa, numpgs; + struct mshv_mem_region *mreg; + int rc; + struct mshv_partition *pt = vp->vp_partition; + + msg = (struct hv_x64_memory_intercept_message *)hvmsg->u.payload; + accinfo = msg->memory_access_info; + + if (!accinfo.gva_gpa_valid) + return false; + + /* Do a fast check and bail if non mmio intercept */ + gfn = msg->guest_physical_address >> HV_HYP_PAGE_SHIFT; + mreg = mshv_partition_region_by_gfn(pt, gfn); + if (mreg == NULL || mreg->type != MSHV_REGION_TYPE_MMIO) + return false; + + rc = mshv_chk_get_mmio_start_pfn(pt, gfn, &mmio_spa); + if (rc) + return false; + + if (!hv_nofull_mmio) { /* default case */ + gfn = mreg->start_gfn; + mmio_spa = mmio_spa - (gfn - mreg->start_gfn); + numpgs = mreg->nr_pages; + } else + numpgs = 1; + + rc = hv_call_map_mmio_pages(pt->pt_id, gfn, mmio_spa, numpgs); + + return rc == 0; +} + static struct mshv_mem_region * mshv_partition_region_by_gfn_get(struct mshv_partition *p, u64 gfn) { @@ -666,13 +777,17 @@ static bool mshv_handle_gpa_intercept(struct mshv_vp *vp) return ret; } + #else /* CONFIG_X86_64 */ +static bool mshv_handle_unmapped_gpa(struct mshv_vp *vp) { return false; } static bool mshv_handle_gpa_intercept(struct mshv_vp *vp) { return false; } #endif /* CONFIG_X86_64 */ static bool mshv_vp_handle_intercept(struct mshv_vp *vp) { switch (vp->vp_intercept_msg_page->header.message_type) { + case HVMSG_UNMAPPED_GPA: + return mshv_handle_unmapped_gpa(vp); case HVMSG_GPA_INTERCEPT: return mshv_handle_gpa_intercept(vp); } -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:30 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> VFIO no longer puts the mmio pfn in vma->vm_pgoff. So, remove code that is using it to map mmio space. It is broken and will cause panic. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- drivers/hv/mshv_root_main.c | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/drivers/hv/mshv_root_main.c b/drivers/hv/mshv_root_main.c index 27313419828d..03f3aa9f5541 100644 --- a/drivers/hv/mshv_root_main.c +++ b/drivers/hv/mshv_root_main.c @@ -1258,16 +1258,8 @@ static int mshv_prepare_pinned_region(struct mshv_mem_region *region) } /* - * This maps two things: guest RAM and for pci passthru mmio space. - * - * mmio: - * - vfio overloads vm_pgoff to store the mmio start pfn/spa. - * - Two things need to happen for mapping mmio range: - * 1. mapped in the uaddr so VMM can access it. - * 2. mapped in the hwpt (gfn <-> mmio phys addr) so guest can access it. - * - * This function takes care of the second. The first one is managed by vfio, - * and hence is taken care of via vfio_pci_mmap_fault(). + * This is called for both user ram and mmio space. The mmio space is not + * mapped here, but later during intercept. */ static long mshv_map_user_memory(struct mshv_partition *partition, @@ -1276,7 +1268,6 @@ mshv_map_user_memory(struct mshv_partition *partition, struct mshv_mem_region *region; struct vm_area_struct *vma; bool is_mmio; - ulong mmio_pfn; long ret; if (mem.flags & BIT(MSHV_SET_MEM_BIT_UNMAP) || @@ -1286,7 +1277,6 @@ mshv_map_user_memory(struct mshv_partition *partition, mmap_read_lock(current->mm); vma = vma_lookup(current->mm, mem.userspace_addr); is_mmio = vma ? !!(vma->vm_flags & (VM_IO | VM_PFNMAP)) : 0; - mmio_pfn = is_mmio ? vma->vm_pgoff : 0; mmap_read_unlock(current->mm); if (!vma) @@ -1313,10 +1303,8 @@ mshv_map_user_memory(struct mshv_partition *partition, HV_MAP_GPA_NO_ACCESS, NULL); break; case MSHV_REGION_TYPE_MMIO: - ret = hv_call_map_mmio_pages(partition->pt_id, - region->start_gfn, - mmio_pfn, - region->nr_pages); + /* mmio mappings are handled later during intercepts */ + ret = 0; break; } -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:29 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Import/copy from Hyper-V public headers, definitions and declarations that are related to attaching and detaching of device domains and interrupt remapping, and building device ids for those purposes. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- include/hyperv/hvgdk_mini.h | 11 ++++ include/hyperv/hvhdk_mini.h | 112 ++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) diff --git a/include/hyperv/hvgdk_mini.h b/include/hyperv/hvgdk_mini.h index 04b18d0e37af..bda9fae5b1ef 100644 --- a/include/hyperv/hvgdk_mini.h +++ b/include/hyperv/hvgdk_mini.h @@ -323,6 +323,9 @@ union hv_hypervisor_version_info { /* stimer Direct Mode is available */ #define HV_STIMER_DIRECT_MODE_AVAILABLE BIT(19) +#define HV_DEVICE_DOMAIN_AVAILABLE BIT(24) +#define HV_S1_DEVICE_DOMAIN_AVAILABLE BIT(25) + /* * Implementation recommendations. Indicates which behaviors the hypervisor * recommends the OS implement for optimal performance. @@ -471,6 +474,8 @@ union hv_vp_assist_msr_contents { /* HV_REGISTER_VP_ASSIST_PAGE */ #define HVCALL_MAP_DEVICE_INTERRUPT 0x007c #define HVCALL_UNMAP_DEVICE_INTERRUPT 0x007d #define HVCALL_RETARGET_INTERRUPT 0x007e +#define HVCALL_ATTACH_DEVICE 0x0082 +#define HVCALL_DETACH_DEVICE 0x0083 #define HVCALL_NOTIFY_PARTITION_EVENT 0x0087 #define HVCALL_ENTER_SLEEP_STATE 0x0084 #define HVCALL_NOTIFY_PORT_RING_EMPTY 0x008b @@ -482,9 +487,15 @@ union hv_vp_assist_msr_contents { /* HV_REGISTER_VP_ASSIST_PAGE */ #define HVCALL_GET_VP_INDEX_FROM_APIC_ID 0x009a #define HVCALL_FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE 0x00af #define HVCALL_FLUSH_GUEST_PHYSICAL_ADDRESS_LIST 0x00b0 +#define HVCALL_CREATE_DEVICE_DOMAIN 0x00b1 +#define HVCALL_ATTACH_DEVICE_DOMAIN 0x00b2 +#define HVCALL_MAP_DEVICE_GPA_PAGES 0x00b3 +#define HVCALL_UNMAP_DEVICE_GPA_PAGES 0x00b4 #define HVCALL_SIGNAL_EVENT_DIRECT 0x00c0 #define HVCALL_POST_MESSAGE_DIRECT 0x00c1 #define HVCALL_DISPATCH_VP 0x00c2 +#define HVCALL_DETACH_DEVICE_DOMAIN 0x00c4 +#define HVCALL_DELETE_DEVICE_DOMAIN 0x00c5 #define HVCALL_GET_GPA_PAGES_ACCESS_STATES 0x00c9 #define HVCALL_ACQUIRE_SPARSE_SPA_PAGE_HOST_ACCESS 0x00d7 #define HVCALL_RELEASE_SPARSE_SPA_PAGE_HOST_ACCESS 0x00d8 diff --git a/include/hyperv/hvhdk_mini.h b/include/hyperv/hvhdk_mini.h index 41a29bf8ec14..57821d6ddb61 100644 --- a/include/hyperv/hvhdk_mini.h +++ b/include/hyperv/hvhdk_mini.h @@ -449,6 +449,32 @@ struct hv_send_ipi_ex { /* HV_INPUT_SEND_SYNTHETIC_CLUSTER_IPI_EX */ struct hv_vpset vp_set; } __packed; +union hv_attdev_flags { /* HV_ATTACH_DEVICE_FLAGS */ + struct { + u32 logical_id : 1; + u32 resvd0 : 1; + u32 ats_enabled : 1; + u32 virt_func : 1; + u32 shared_irq_child : 1; + u32 virt_dev : 1; + u32 ats_supported : 1; + u32 small_irt : 1; + u32 resvd : 24; + } __packed; + u32 as_uint32; +}; + +union hv_dev_pci_caps { /* HV_DEVICE_PCI_CAPABILITIES */ + struct { + u32 max_pasid_width : 5; + u32 invalidate_qdepth : 5; + u32 global_inval : 1; + u32 prg_response_req : 1; + u32 resvd : 20; + } __packed; + u32 as_uint32; +}; + typedef u16 hv_pci_rid; /* HV_PCI_RID */ typedef u16 hv_pci_segment; /* HV_PCI_SEGMENT */ typedef u64 hv_logical_device_id; @@ -528,4 +554,90 @@ union hv_device_id { /* HV_DEVICE_ID */ } acpi; } __packed; +struct hv_input_attach_device { /* HV_INPUT_ATTACH_DEVICE */ + u64 partition_id; + union hv_device_id device_id; + union hv_attdev_flags attdev_flags; + u8 attdev_vtl; + u8 rsvd0; + u16 rsvd1; + u64 logical_devid; + union hv_dev_pci_caps dev_pcicaps; + u16 pf_pci_rid; + u16 resvd2; +} __packed; + +struct hv_input_detach_device { /* HV_INPUT_DETACH_DEVICE */ + u64 partition_id; + u64 logical_devid; +} __packed; + + +/* 3 domain types: stage 1, stage 2, and SOC */ +#define HV_DEVICE_DOMAIN_TYPE_S2 0 /* HV_DEVICE_DOMAIN_ID_TYPE_S2 */ +#define HV_DEVICE_DOMAIN_TYPE_S1 1 /* HV_DEVICE_DOMAIN_ID_TYPE_S1 */ +#define HV_DEVICE_DOMAIN_TYPE_SOC 2 /* HV_DEVICE_DOMAIN_ID_TYPE_SOC */ + +/* ID for stage 2 default domain and NULL domain */ +#define HV_DEVICE_DOMAIN_ID_S2_DEFAULT 0 +#define HV_DEVICE_DOMAIN_ID_S2_NULL 0xFFFFFFFFULL + +union hv_device_domain_id { + u64 as_uint64; + struct { + u32 type : 4; + u32 reserved : 28; + u32 id; + }; +} __packed; + +struct hv_input_device_domain { /* HV_INPUT_DEVICE_DOMAIN */ + u64 partition_id; + union hv_input_vtl owner_vtl; + u8 padding[7]; + union hv_device_domain_id domain_id; +} __packed; + +union hv_create_device_domain_flags { /* HV_CREATE_DEVICE_DOMAIN_FLAGS */ + u32 as_uint32; + struct { + u32 forward_progress_required : 1; + u32 inherit_owning_vtl : 1; + u32 reserved : 30; + } __packed; +} __packed; + +struct hv_input_create_device_domain { /* HV_INPUT_CREATE_DEVICE_DOMAIN */ + struct hv_input_device_domain device_domain; + union hv_create_device_domain_flags create_device_domain_flags; +} __packed; + +struct hv_input_delete_device_domain { /* HV_INPUT_DELETE_DEVICE_DOMAIN */ + struct hv_input_device_domain device_domain; +} __packed; + +struct hv_input_attach_device_domain { /* HV_INPUT_ATTACH_DEVICE_DOMAIN */ + struct hv_input_device_domain device_domain; + union hv_device_id device_id; +} __packed; + +struct hv_input_detach_device_domain { /* HV_INPUT_DETACH_DEVICE_DOMAIN */ + u64 partition_id; + union hv_device_id device_id; +} __packed; + +struct hv_input_map_device_gpa_pages { /* HV_INPUT_MAP_DEVICE_GPA_PAGES */ + struct hv_input_device_domain device_domain; + union hv_input_vtl target_vtl; + u8 padding[3]; + u32 map_flags; + u64 target_device_va_base; + u64 gpa_page_list[]; +} __packed; + +struct hv_input_unmap_device_gpa_pages { /* HV_INPUT_UNMAP_DEVICE_GPA_PAGES */ + struct hv_input_device_domain device_domain; + u64 target_device_va_base; +} __packed; + #endif /* _HV_HVHDK_MINI_H */ -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:24 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> On Hyper-V, most hypercalls related to PCI passthru to map/unmap regions, interrupts, etc need a device id as a parameter. This device id refers to that specific device during the lifetime of passthru. An L1VH VM only contains VMBus based devices. A device id for a VMBus device is slightly different in that it uses the hv_pcibus_device info for building it to make sure it matches exactly what the hypervisor expects. This VMBus based device id is needed when attaching devices in an L1VH based guest VM. Before building it, a check is done to make sure the device is a valid VMBus device. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- arch/x86/include/asm/mshyperv.h | 2 ++ drivers/pci/controller/pci-hyperv.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/arch/x86/include/asm/mshyperv.h b/arch/x86/include/asm/mshyperv.h index eef4c3a5ba28..0d7fdfb25e76 100644 --- a/arch/x86/include/asm/mshyperv.h +++ b/arch/x86/include/asm/mshyperv.h @@ -188,6 +188,8 @@ bool hv_vcpu_is_preempted(int vcpu); static inline void hv_apic_init(void) {} #endif +u64 hv_pci_vmbus_device_id(struct pci_dev *pdev); + struct irq_domain *hv_create_pci_msi_domain(void); int hv_map_msi_interrupt(struct irq_data *data, diff --git a/drivers/pci/controller/pci-hyperv.c b/drivers/pci/controller/pci-hyperv.c index 8bc6a38c9b5a..40f0b06bb966 100644 --- a/drivers/pci/controller/pci-hyperv.c +++ b/drivers/pci/controller/pci-hyperv.c @@ -579,6 +579,8 @@ static void hv_pci_onchannelcallback(void *context); #define DELIVERY_MODE APIC_DELIVERY_MODE_FIXED #define HV_MSI_CHIP_FLAGS MSI_CHIP_FLAG_SET_ACK +static bool hv_vmbus_pci_device(struct pci_bus *pbus); + static int hv_pci_irqchip_init(void) { return 0; @@ -598,6 +600,26 @@ static unsigned int hv_msi_get_int_vector(struct irq_data *data) #define hv_msi_prepare pci_msi_prepare +u64 hv_pci_vmbus_device_id(struct pci_dev *pdev) +{ + u64 u64val; + struct hv_pcibus_device *hbus; + struct pci_bus *pbus = pdev->bus; + + if (!hv_vmbus_pci_device(pbus)) + return 0; + + hbus = container_of(pbus->sysdata, struct hv_pcibus_device, sysdata); + u64val = (hbus->hdev->dev_instance.b[5] << 24) | + (hbus->hdev->dev_instance.b[4] << 16) | + (hbus->hdev->dev_instance.b[7] << 8) | + (hbus->hdev->dev_instance.b[6] & 0xf8) | + PCI_FUNC(pdev->devfn); + + return u64val; +} +EXPORT_SYMBOL_GPL(hv_pci_vmbus_device_id); + /** * hv_irq_retarget_interrupt() - "Unmask" the IRQ by setting its current * affinity. @@ -1404,6 +1426,13 @@ static struct pci_ops hv_pcifront_ops = { .write = hv_pcifront_write_config, }; +#ifdef CONFIG_X86 +static bool hv_vmbus_pci_device(struct pci_bus *pbus) +{ + return pbus->ops == &hv_pcifront_ops; +} +#endif /* CONFIG_X86 */ + /* * Paravirtual backchannel * -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:25 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> On Hyper-V, most hypercalls related to PCI passthru to map/unmap regions, interrupts, etc need a device id as a parameter. A device id refers to a specific device. A device id is of two types: o Logical: used for direct attach (see below) hypercalls. A logical device id is a unique 62bit value that is created and sent during the initial device attach. Then all further communications (for interrupt remaps etc) must use this logical id. o PCI: used for device domain hypercalls such as map, unmap, etc. This is built using actual device BDF info. PS: Since an L1VH only supports direct attaches, a logical device id on an L1VH VM is always a VMBus device id. For non-L1VH cases, we just use PCI BDF info, altho not strictly needed, to build the logical device id. At a high level, Hyper-V supports two ways to do PCI passthru: 1. Device Domain: root must create a device domain in the hypervisor, and do map/unmap hypercalls for mapping and unmapping guest RAM. All hypervisor communications use device id of type PCI for identifying and referencing the device. 2. Direct Attach: the hypervisor will simply use the guest's HW page table for mappings, thus the host need not do map/unmap hypercalls. A direct attached device must be referenced via logical device id and never via the PCI device id. For an L1VH root/parent, Hyper-V only supports direct attaches. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- arch/x86/hyperv/irqdomain.c | 60 ++++++++++++++++++++++++++++++--- arch/x86/include/asm/mshyperv.h | 14 ++++++++ 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/arch/x86/hyperv/irqdomain.c b/arch/x86/hyperv/irqdomain.c index ccbe5848a28f..33017aa0caa4 100644 --- a/arch/x86/hyperv/irqdomain.c +++ b/arch/x86/hyperv/irqdomain.c @@ -137,7 +137,7 @@ static int get_rid_cb(struct pci_dev *pdev, u16 alias, void *data) return 0; } -static union hv_device_id hv_build_devid_type_pci(struct pci_dev *pdev) +static u64 hv_build_devid_type_pci(struct pci_dev *pdev) { int pos; union hv_device_id hv_devid; @@ -197,7 +197,58 @@ static union hv_device_id hv_build_devid_type_pci(struct pci_dev *pdev) } out: - return hv_devid; + return hv_devid.as_uint64; +} + +/* Build device id for direct attached devices */ +static u64 hv_build_devid_type_logical(struct pci_dev *pdev) +{ + hv_pci_segment segment; + union hv_device_id hv_devid; + union hv_pci_bdf bdf = {.as_uint16 = 0}; + struct rid_data data = { + .bridge = NULL, + .rid = PCI_DEVID(pdev->bus->number, pdev->devfn) + }; + + segment = pci_domain_nr(pdev->bus); + bdf.bus = PCI_BUS_NUM(data.rid); + bdf.device = PCI_SLOT(data.rid); + bdf.function = PCI_FUNC(data.rid); + + hv_devid.as_uint64 = 0; + hv_devid.device_type = HV_DEVICE_TYPE_LOGICAL; + hv_devid.logical.id = (u64)segment << 16 | bdf.as_uint16; + + return hv_devid.as_uint64; +} + +/* Build device id after the device has been attached */ +u64 hv_build_devid_oftype(struct pci_dev *pdev, enum hv_device_type type) +{ + if (type == HV_DEVICE_TYPE_LOGICAL) { + if (hv_l1vh_partition()) + return hv_pci_vmbus_device_id(pdev); + else + return hv_build_devid_type_logical(pdev); + } else if (type == HV_DEVICE_TYPE_PCI) + return hv_build_devid_type_pci(pdev); + + return 0; +} +EXPORT_SYMBOL_GPL(hv_build_devid_oftype); + +/* Build device id for the interrupt path */ +static u64 hv_build_irq_devid(struct pci_dev *pdev) +{ + enum hv_device_type dev_type; + + if (hv_pcidev_is_attached_dev(pdev) || hv_l1vh_partition()) + dev_type = HV_DEVICE_TYPE_LOGICAL; + else + dev_type = HV_DEVICE_TYPE_PCI; + + return hv_build_devid_oftype(pdev, dev_type); } /* @@ -221,7 +272,7 @@ int hv_map_msi_interrupt(struct irq_data *data, msidesc = irq_data_get_msi_desc(data); pdev = msi_desc_to_pci_dev(msidesc); - hv_devid = hv_build_devid_type_pci(pdev); + hv_devid.as_uint64 = hv_build_irq_devid(pdev); cpu = cpumask_first(irq_data_get_effective_affinity_mask(data)); return hv_map_interrupt(hv_current_partition_id, hv_devid, false, cpu, @@ -296,7 +347,8 @@ static int hv_unmap_msi_interrupt(struct pci_dev *pdev, { union hv_device_id hv_devid; - hv_devid = hv_build_devid_type_pci(pdev); + hv_devid.as_uint64 = hv_build_irq_devid(pdev); + return hv_unmap_interrupt(hv_devid.as_uint64, irq_entry); } diff --git a/arch/x86/include/asm/mshyperv.h b/arch/x86/include/asm/mshyperv.h index 0d7fdfb25e76..97477c5a8487 100644 --- a/arch/x86/include/asm/mshyperv.h +++ b/arch/x86/include/asm/mshyperv.h @@ -188,6 +188,20 @@ bool hv_vcpu_is_preempted(int vcpu); static inline void hv_apic_init(void) {} #endif +#if IS_ENABLED(CONFIG_HYPERV_IOMMU) +static inline bool hv_pcidev_is_attached_dev(struct pci_dev *pdev) +{ return false; } /* temporary */ +u64 hv_build_devid_oftype(struct pci_dev *pdev, enum hv_device_type type); +#else /* CONFIG_HYPERV_IOMMU */ +static inline bool hv_pcidev_is_attached_dev(struct pci_dev *pdev) +{ return false; } + +static inline u64 hv_build_devid_oftype(struct pci_dev *pdev, + enum hv_device_type type) +{ return 0; } + +#endif /* CONFIG_HYPERV_IOMMU */ + u64 hv_pci_vmbus_device_id(struct pci_dev *pdev); struct irq_domain *hv_create_pci_msi_domain(void); -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:26 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
From: Mukesh Rathor <mrathor@linux.microsoft.com> Add a new file to implement management of device domains, mapping and unmapping of iommu memory, and other iommu_ops to fit within the VFIO framework for PCI passthru on Hyper-V running Linux as root or L1VH parent. This also implements direct attach mechanism for PCI passthru, and it is also made to work within the VFIO framework. At a high level, during boot the hypervisor creates a default identity domain and attaches all devices to it. This nicely maps to Linux iommu subsystem IOMMU_DOMAIN_IDENTITY domain. As a result, Linux does not need to explicitly ask Hyper-V to attach devices and do maps/unmaps during boot. As mentioned previously, Hyper-V supports two ways to do PCI passthru: 1. Device Domain: root must create a device domain in the hypervisor, and do map/unmap hypercalls for mapping and unmapping guest RAM. All hypervisor communications use device id of type PCI for identifying and referencing the device. 2. Direct Attach: the hypervisor will simply use the guest's HW page table for mappings, thus the host need not do map/unmap device memory hypercalls. As such, direct attach passthru setup during guest boot is extremely fast. A direct attached device must be referenced via logical device id and not via the PCI device id. At present, L1VH root/parent only supports direct attaches. Also direct attach is default in non-L1VH cases because there are some significant performance issues with device domain implementation currently for guests with higher RAM (say more than 8GB), and that unfortunately cannot be addressed in the short term. Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> --- MAINTAINERS | 1 + arch/x86/include/asm/mshyperv.h | 7 +- arch/x86/kernel/pci-dma.c | 2 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 876 ++++++++++++++++++++++++++++++++ include/linux/hyperv.h | 6 + 6 files changed, 890 insertions(+), 4 deletions(-) create mode 100644 drivers/iommu/hyperv-iommu.c diff --git a/MAINTAINERS b/MAINTAINERS index 381a0e086382..63160cee942c 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -11741,6 +11741,7 @@ F: drivers/hid/hid-hyperv.c F: drivers/hv/ F: drivers/infiniband/hw/mana/ F: drivers/input/serio/hyperv-keyboard.c +F: drivers/iommu/hyperv-iommu.c F: drivers/iommu/hyperv-irq.c F: drivers/net/ethernet/microsoft/ F: drivers/net/hyperv/ diff --git a/arch/x86/include/asm/mshyperv.h b/arch/x86/include/asm/mshyperv.h index 97477c5a8487..e4ccdbbf1d12 100644 --- a/arch/x86/include/asm/mshyperv.h +++ b/arch/x86/include/asm/mshyperv.h @@ -189,16 +189,17 @@ static inline void hv_apic_init(void) {} #endif #if IS_ENABLED(CONFIG_HYPERV_IOMMU) -static inline bool hv_pcidev_is_attached_dev(struct pci_dev *pdev) -{ return false; } /* temporary */ +bool hv_pcidev_is_attached_dev(struct pci_dev *pdev); u64 hv_build_devid_oftype(struct pci_dev *pdev, enum hv_device_type type); +u64 hv_iommu_get_curr_partid(void); #else /* CONFIG_HYPERV_IOMMU */ static inline bool hv_pcidev_is_attached_dev(struct pci_dev *pdev) { return false; } - static inline u64 hv_build_devid_oftype(struct pci_dev *pdev, enum hv_device_type type) { return 0; } +static inline u64 hv_iommu_get_curr_partid(void) +{ return HV_PARTITION_ID_INVALID; } #endif /* CONFIG_HYPERV_IOMMU */ diff --git a/arch/x86/kernel/pci-dma.c b/arch/x86/kernel/pci-dma.c index 6267363e0189..cfeee6505e17 100644 --- a/arch/x86/kernel/pci-dma.c +++ b/arch/x86/kernel/pci-dma.c @@ -8,6 +8,7 @@ #include <linux/gfp.h> #include <linux/pci.h> #include <linux/amd-iommu.h> +#include <linux/hyperv.h> #include <asm/proto.h> #include <asm/dma.h> @@ -105,6 +106,7 @@ void __init pci_iommu_alloc(void) gart_iommu_hole_init(); amd_iommu_detect(); detect_intel_iommu(); + hv_iommu_detect(); swiotlb_init(x86_swiotlb_enable, x86_swiotlb_flags); } diff --git a/drivers/iommu/Makefile b/drivers/iommu/Makefile index 598c39558e7d..cc9774864b00 100644 --- a/drivers/iommu/Makefile +++ b/drivers/iommu/Makefile @@ -30,7 +30,7 @@ obj-$(CONFIG_TEGRA_IOMMU_SMMU) += tegra-smmu.o obj-$(CONFIG_EXYNOS_IOMMU) += exynos-iommu.o obj-$(CONFIG_FSL_PAMU) += fsl_pamu.o fsl_pamu_domain.o obj-$(CONFIG_S390_IOMMU) += s390-iommu.o -obj-$(CONFIG_HYPERV_IOMMU) += hyperv-irq.o +obj-$(CONFIG_HYPERV_IOMMU) += hyperv-irq.o hyperv-iommu.o obj-$(CONFIG_VIRTIO_IOMMU) += virtio-iommu.o obj-$(CONFIG_IOMMU_SVA) += iommu-sva.o obj-$(CONFIG_IOMMU_IOPF) += io-pgfault.o diff --git a/drivers/iommu/hyperv-iommu.c b/drivers/iommu/hyperv-iommu.c new file mode 100644 index 000000000000..548483fec6b1 --- /dev/null +++ b/drivers/iommu/hyperv-iommu.c @@ -0,0 +1,876 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Hyper-V root vIOMMU driver. + * Copyright (C) 2026, Microsoft, Inc. + */ + +#include <linux/module.h> +#include <linux/pci.h> +#include <linux/dmar.h> +#include <linux/dma-map-ops.h> +#include <linux/interval_tree.h> +#include <linux/hyperv.h> +#include "dma-iommu.h" +#include <asm/iommu.h> +#include <asm/mshyperv.h> + +/* We will not claim these PCI devices, eg hypervisor needs it for debugger */ +static char *pci_devs_to_skip; +static int __init hv_iommu_setup_skip(char *str) +{ + pci_devs_to_skip = str; + + return 0; +} +/* hv_iommu_skip=(SSSS:BB:DD.F)(SSSS:BB:DD.F) */ +__setup("hv_iommu_skip=", hv_iommu_setup_skip); + +bool hv_no_attdev; /* disable direct device attach for passthru */ +EXPORT_SYMBOL_GPL(hv_no_attdev); +static int __init setup_hv_no_attdev(char *str) +{ + hv_no_attdev = true; + return 0; +} +__setup("hv_no_attdev", setup_hv_no_attdev); + +/* Iommu device that we export to the world. HyperV supports max of one */ +static struct iommu_device hv_virt_iommu; + +struct hv_domain { + struct iommu_domain iommu_dom; + u32 domid_num; /* as opposed to domain_id.type */ + u32 num_attchd; /* number of currently attached devices */ + bool attached_dom; /* is this direct attached dom? */ + spinlock_t mappings_lock; /* protects mappings_tree */ + struct rb_root_cached mappings_tree; /* iova to pa lookup tree */ +}; + +#define to_hv_domain(d) container_of(d, struct hv_domain, iommu_dom) + +struct hv_iommu_mapping { + phys_addr_t paddr; + struct interval_tree_node iova; + u32 flags; +}; + +/* + * By default, during boot the hypervisor creates one Stage 2 (S2) default + * domain. Stage 2 means that the page table is controlled by the hypervisor. + * S2 default: access to entire root partition memory. This for us easily + * maps to IOMMU_DOMAIN_IDENTITY in the iommu subsystem, and + * is called HV_DEVICE_DOMAIN_ID_S2_DEFAULT in the hypervisor. + * + * Device Management: + * There are two ways to manage device attaches to domains: + * 1. Domain Attach: A device domain is created in the hypervisor, the + * device is attached to this domain, and then memory + * ranges are mapped in the map callbacks. + * 2. Direct Attach: No need to create a domain in the hypervisor for direct + * attached devices. A hypercall is made to tell the + * hypervisor to attach the device to a guest. There is + * no need for explicit memory mappings because the + * hypervisor will just use the guest HW page table. + * + * Since a direct attach is much faster, it is the default. This can be + * changed via hv_no_attdev. + * + * L1VH: hypervisor only supports direct attach. + */ + +/* + * Create dummy domain to correspond to hypervisor prebuilt default identity + * domain (dummy because we do not make hypercall to create them). + */ +static struct hv_domain hv_def_identity_dom; + +static bool hv_special_domain(struct hv_domain *hvdom) +{ + return hvdom == &hv_def_identity_dom; +} + +struct iommu_domain_geometry default_geometry = (struct iommu_domain_geometry) { + .aperture_start = 0, + .aperture_end = -1UL, + .force_aperture = true, +}; + +/* + * Since the relevant hypercalls can only fit less than 512 PFNs in the pfn + * array, report 1M max. + */ +#define HV_IOMMU_PGSIZES (SZ_4K | SZ_1M) + +static u32 unique_id; /* unique numeric id of a new domain */ + +static void hv_iommu_detach_dev(struct iommu_domain *immdom, + struct device *dev); +static size_t hv_iommu_unmap_pages(struct iommu_domain *immdom, ulong iova, + size_t pgsize, size_t pgcount, + struct iommu_iotlb_gather *gather); + +/* + * If the current thread is a VMM thread, return the partition id of the VM it + * is managing, else return HV_PARTITION_ID_INVALID. + */ +u64 hv_iommu_get_curr_partid(void) +{ + u64 (*fn)(pid_t pid); + u64 partid; + + fn = symbol_get(mshv_pid_to_partid); + if (!fn) + return HV_PARTITION_ID_INVALID; + + partid = fn(current->tgid); + symbol_put(mshv_pid_to_partid); + + return partid; +} + +/* If this is a VMM thread, then this domain is for a guest VM */ +static bool hv_curr_thread_is_vmm(void) +{ + return hv_iommu_get_curr_partid() != HV_PARTITION_ID_INVALID; +} + +static bool hv_iommu_capable(struct device *dev, enum iommu_cap cap) +{ + switch (cap) { + case IOMMU_CAP_CACHE_COHERENCY: + return true; + default: + return false; + } + return false; +} + +/* + * Check if given pci device is a direct attached device. Caller must have + * verified pdev is a valid pci device. + */ +bool hv_pcidev_is_attached_dev(struct pci_dev *pdev) +{ + struct iommu_domain *iommu_domain; + struct hv_domain *hvdom; + struct device *dev = &pdev->dev; + + iommu_domain = iommu_get_domain_for_dev(dev); + if (iommu_domain) { + hvdom = to_hv_domain(iommu_domain); + return hvdom->attached_dom; + } + + return false; +} +EXPORT_SYMBOL_GPL(hv_pcidev_is_attached_dev); + +/* Create a new device domain in the hypervisor */ +static int hv_iommu_create_hyp_devdom(struct hv_domain *hvdom) +{ + u64 status; + unsigned long flags; + struct hv_input_device_domain *ddp; + struct hv_input_create_device_domain *input; + + local_irq_save(flags); + input = *this_cpu_ptr(hyperv_pcpu_input_arg); + memset(input, 0, sizeof(*input)); + + ddp = &input->device_domain; + ddp->partition_id = HV_PARTITION_ID_SELF; + ddp->domain_id.type = HV_DEVICE_DOMAIN_TYPE_S2; + ddp->domain_id.id = hvdom->domid_num; + + input->create_device_domain_flags.forward_progress_required = 1; + input->create_device_domain_flags.inherit_owning_vtl = 0; + + status = hv_do_hypercall(HVCALL_CREATE_DEVICE_DOMAIN, input, NULL); + + local_irq_restore(flags); + + if (!hv_result_success(status)) + hv_status_err(status, "\n"); + + return hv_result_to_errno(status); +} + +/* During boot, all devices are attached to this */ +static struct iommu_domain *hv_iommu_domain_alloc_identity(struct device *dev) +{ + return &hv_def_identity_dom.iommu_dom; +} + +static struct iommu_domain *hv_iommu_domain_alloc_paging(struct device *dev) +{ + struct hv_domain *hvdom; + int rc; + + if (hv_l1vh_partition() && !hv_curr_thread_is_vmm() && !hv_no_attdev) { + pr_err("Hyper-V: l1vh iommu does not support host devices\n"); + return NULL; + } + + hvdom = kzalloc(sizeof(struct hv_domain), GFP_KERNEL); + if (hvdom == NULL) + goto out; + + spin_lock_init(&hvdom->mappings_lock); + hvdom->mappings_tree = RB_ROOT_CACHED; + + if (++unique_id == HV_DEVICE_DOMAIN_ID_S2_DEFAULT) /* ie, 0 */ + goto out_free; + + hvdom->domid_num = unique_id; + hvdom->iommu_dom.geometry = default_geometry; + hvdom->iommu_dom.pgsize_bitmap = HV_IOMMU_PGSIZES; + + /* For guests, by default we do direct attaches, so no domain in hyp */ + if (hv_curr_thread_is_vmm() && !hv_no_attdev) + hvdom->attached_dom = true; + else { + rc = hv_iommu_create_hyp_devdom(hvdom); + if (rc) + goto out_free_id; + } + + return &hvdom->iommu_dom; + +out_free_id: + unique_id--; +out_free: + kfree(hvdom); +out: + return NULL; +} + +static void hv_iommu_domain_free(struct iommu_domain *immdom) +{ + struct hv_domain *hvdom = to_hv_domain(immdom); + unsigned long flags; + u64 status; + struct hv_input_delete_device_domain *input; + + if (hv_special_domain(hvdom)) + return; + + if (hvdom->num_attchd) { + pr_err("Hyper-V: can't free busy iommu domain (%p)\n", immdom); + return; + } + + if (!hv_curr_thread_is_vmm() || hv_no_attdev) { + struct hv_input_device_domain *ddp; + + local_irq_save(flags); + input = *this_cpu_ptr(hyperv_pcpu_input_arg); + ddp = &input->device_domain; + memset(input, 0, sizeof(*input)); + + ddp->partition_id = HV_PARTITION_ID_SELF; + ddp->domain_id.type = HV_DEVICE_DOMAIN_TYPE_S2; + ddp->domain_id.id = hvdom->domid_num; + + status = hv_do_hypercall(HVCALL_DELETE_DEVICE_DOMAIN, input, + NULL); + local_irq_restore(flags); + + if (!hv_result_success(status)) + hv_status_err(status, "\n"); + } + + kfree(hvdom); +} + +/* Attach a device to a domain previously created in the hypervisor */ +static int hv_iommu_att_dev2dom(struct hv_domain *hvdom, struct pci_dev *pdev) +{ + unsigned long flags; + u64 status; + enum hv_device_type dev_type; + struct hv_input_attach_device_domain *input; + + local_irq_save(flags); + input = *this_cpu_ptr(hyperv_pcpu_input_arg); + memset(input, 0, sizeof(*input)); + + input->device_domain.partition_id = HV_PARTITION_ID_SELF; + input->device_domain.domain_id.type = HV_DEVICE_DOMAIN_TYPE_S2; + input->device_domain.domain_id.id = hvdom->domid_num; + + /* NB: Upon guest shutdown, device is re-attached to the default domain + * without explicit detach. + */ + if (hv_l1vh_partition()) + dev_type = HV_DEVICE_TYPE_LOGICAL; + else + dev_type = HV_DEVICE_TYPE_PCI; + + input->device_id.as_uint64 = hv_build_devid_oftype(pdev, dev_type); + + status = hv_do_hypercall(HVCALL_ATTACH_DEVICE_DOMAIN, input, NULL); + local_irq_restore(flags); + + if (!hv_result_success(status)) + hv_status_err(status, "\n"); + + return hv_result_to_errno(status); +} + +/* Caller must have validated that dev is a valid pci dev */ +static int hv_iommu_direct_attach_device(struct pci_dev *pdev) +{ + struct hv_input_attach_device *input; + u64 status; + int rc; + unsigned long flags; + union hv_device_id host_devid; + enum hv_device_type dev_type; + u64 ptid = hv_iommu_get_curr_partid(); + + if (ptid == HV_PARTITION_ID_INVALID) { + pr_err("Hyper-V: Invalid partition id in direct attach\n"); + return -EINVAL; + } + + if (hv_l1vh_partition()) + dev_type = HV_DEVICE_TYPE_LOGICAL; + else + dev_type = HV_DEVICE_TYPE_PCI; + + host_devid.as_uint64 = hv_build_devid_oftype(pdev, dev_type); + + do { + local_irq_save(flags); + input = *this_cpu_ptr(hyperv_pcpu_input_arg); + memset(input, 0, sizeof(*input)); + input->partition_id = ptid; + input->device_id = host_devid; + + /* Hypervisor associates logical_id with this device, and in + * some hypercalls like retarget interrupts, logical_id must be + * used instead of the BDF. It is a required parameter. + */ + input->attdev_flags.logical_id = 1; + input->logical_devid = + hv_build_devid_oftype(pdev, HV_DEVICE_TYPE_LOGICAL); + + status = hv_do_hypercall(HVCALL_ATTACH_DEVICE, input, NULL); + local_irq_restore(flags); + + if (hv_result(status) == HV_STATUS_INSUFFICIENT_MEMORY) { + rc = hv_call_deposit_pages(NUMA_NO_NODE, ptid, 1); + if (rc) + break; + } + } while (hv_result(status) == HV_STATUS_INSUFFICIENT_MEMORY); + + if (!hv_result_success(status)) + hv_status_err(status, "\n"); + + return hv_result_to_errno(status); +} + +/* This to attach a device to both host app (like DPDK) and a guest VM */ +static int hv_iommu_attach_dev(struct iommu_domain *immdom, struct device *dev, + struct iommu_domain *old) +{ + struct pci_dev *pdev; + int rc; + struct hv_domain *hvdom_new = to_hv_domain(immdom); + struct hv_domain *hvdom_prev = dev_iommu_priv_get(dev); + + /* Only allow PCI devices for now */ + if (!dev_is_pci(dev)) + return -EINVAL; + + pdev = to_pci_dev(dev); + + /* l1vh does not support host device (eg DPDK) passthru */ + if (hv_l1vh_partition() && !hv_special_domain(hvdom_new) && + !hvdom_new->attached_dom) + return -EINVAL; + + /* + * VFIO does not do explicit detach calls, hence check first if we need + * to detach first. Also, in case of guest shutdown, it's the VMM + * thread that attaches it back to the hv_def_identity_dom, and + * hvdom_prev will not be null then. It is null during boot. + */ + if (hvdom_prev) + if (!hv_l1vh_partition() || !hv_special_domain(hvdom_prev)) + hv_iommu_detach_dev(&hvdom_prev->iommu_dom, dev); + + if (hv_l1vh_partition() && hv_special_domain(hvdom_new)) { + dev_iommu_priv_set(dev, hvdom_new); /* sets "private" field */ + return 0; + } + + if (hvdom_new->attached_dom) + rc = hv_iommu_direct_attach_device(pdev); + else + rc = hv_iommu_att_dev2dom(hvdom_new, pdev); + + if (rc && hvdom_prev) { + int rc1; + + if (hvdom_prev->attached_dom) + rc1 = hv_iommu_direct_attach_device(pdev); + else + rc1 = hv_iommu_att_dev2dom(hvdom_prev, pdev); + + if (rc1) + pr_err("Hyper-V: iommu could not restore orig device state.. dev:%s\n", + dev_name(dev)); + } + + if (rc == 0) { + dev_iommu_priv_set(dev, hvdom_new); /* sets "private" field */ + hvdom_new->num_attchd++; + } + + return rc; +} + +static void hv_iommu_det_dev_from_guest(struct hv_domain *hvdom, + struct pci_dev *pdev) +{ + struct hv_input_detach_device *input; + u64 status, log_devid; + unsigned long flags; + + log_devid = hv_build_devid_oftype(pdev, HV_DEVICE_TYPE_LOGICAL); + + local_irq_save(flags); + input = *this_cpu_ptr(hyperv_pcpu_input_arg); + memset(input, 0, sizeof(*input)); + + input->partition_id = hv_iommu_get_curr_partid(); + input->logical_devid = log_devid; + status = hv_do_hypercall(HVCALL_DETACH_DEVICE, input, NULL); + local_irq_restore(flags); + + if (!hv_result_success(status)) + hv_status_err(status, "\n"); +} + +static void hv_iommu_det_dev_from_dom(struct hv_domain *hvdom, + struct pci_dev *pdev) +{ + u64 status, devid; + unsigned long flags; + struct hv_input_detach_device_domain *input; + + devid = hv_build_devid_oftype(pdev, HV_DEVICE_TYPE_PCI); + + local_irq_save(flags); + input = *this_cpu_ptr(hyperv_pcpu_input_arg); + memset(input, 0, sizeof(*input)); + + input->partition_id = HV_PARTITION_ID_SELF; + input->device_id.as_uint64 = devid; + status = hv_do_hypercall(HVCALL_DETACH_DEVICE_DOMAIN, input, NULL); + local_irq_restore(flags); + + if (!hv_result_success(status)) + hv_status_err(status, "\n"); +} + +static void hv_iommu_detach_dev(struct iommu_domain *immdom, struct device *dev) +{ + struct pci_dev *pdev; + struct hv_domain *hvdom = to_hv_domain(immdom); + + /* See the attach function, only PCI devices for now */ + if (!dev_is_pci(dev)) + return; + + if (hvdom->num_attchd == 0) + pr_warn("Hyper-V: num_attchd is zero (%s)\n", dev_name(dev)); + + pdev = to_pci_dev(dev); + + if (hvdom->attached_dom) { + hv_iommu_det_dev_from_guest(hvdom, pdev); + + /* Do not reset attached_dom, hv_iommu_unmap_pages happens + * next. + */ + } else { + hv_iommu_det_dev_from_dom(hvdom, pdev); + } + + hvdom->num_attchd--; +} + +static int hv_iommu_add_tree_mapping(struct hv_domain *hvdom, + unsigned long iova, phys_addr_t paddr, + size_t size, u32 flags) +{ + unsigned long irqflags; + struct hv_iommu_mapping *mapping; + + mapping = kzalloc(sizeof(*mapping), GFP_ATOMIC); + if (!mapping) + return -ENOMEM; + + mapping->paddr = paddr; + mapping->iova.start = iova; + mapping->iova.last = iova + size - 1; + mapping->flags = flags; + + spin_lock_irqsave(&hvdom->mappings_lock, irqflags); + interval_tree_insert(&mapping->iova, &hvdom->mappings_tree); + spin_unlock_irqrestore(&hvdom->mappings_lock, irqflags); + + return 0; +} + +static size_t hv_iommu_del_tree_mappings(struct hv_domain *hvdom, + unsigned long iova, size_t size) +{ + unsigned long flags; + size_t unmapped = 0; + unsigned long last = iova + size - 1; + struct hv_iommu_mapping *mapping = NULL; + struct interval_tree_node *node, *next; + + spin_lock_irqsave(&hvdom->mappings_lock, flags); + next = interval_tree_iter_first(&hvdom->mappings_tree, iova, last); + while (next) { + node = next; + mapping = container_of(node, struct hv_iommu_mapping, iova); + next = interval_tree_iter_next(node, iova, last); + + /* Trying to split a mapping? Not supported for now. */ + if (mapping->iova.start < iova) + break; + + unmapped += mapping->iova.last - mapping->iova.start + 1; + + interval_tree_remove(node, &hvdom->mappings_tree); + kfree(mapping); + } + spin_unlock_irqrestore(&hvdom->mappings_lock, flags); + + return unmapped; +} + +/* Return: must return exact status from the hypercall without changes */ +static u64 hv_iommu_map_pgs(struct hv_domain *hvdom, + unsigned long iova, phys_addr_t paddr, + unsigned long npages, u32 map_flags) +{ + u64 status; + int i; + struct hv_input_map_device_gpa_pages *input; + unsigned long flags, pfn = paddr >> HV_HYP_PAGE_SHIFT; + + local_irq_save(flags); + input = *this_cpu_ptr(hyperv_pcpu_input_arg); + memset(input, 0, sizeof(*input)); + + input->device_domain.partition_id = HV_PARTITION_ID_SELF; + input->device_domain.domain_id.type = HV_DEVICE_DOMAIN_TYPE_S2; + input->device_domain.domain_id.id = hvdom->domid_num; + input->map_flags = map_flags; + input->target_device_va_base = iova; + + pfn = paddr >> HV_HYP_PAGE_SHIFT; + for (i = 0; i < npages; i++, pfn++) + input->gpa_page_list[i] = pfn; + + status = hv_do_rep_hypercall(HVCALL_MAP_DEVICE_GPA_PAGES, npages, 0, + input, NULL); + + local_irq_restore(flags); + return status; +} + +/* + * The core VFIO code loops over memory ranges calling this function with + * the largest size from HV_IOMMU_PGSIZES. cond_resched() is in vfio_iommu_map. + */ +static int hv_iommu_map_pages(struct iommu_domain *immdom, ulong iova, + phys_addr_t paddr, size_t pgsize, size_t pgcount, + int prot, gfp_t gfp, size_t *mapped) +{ + u32 map_flags; + int ret; + u64 status; + unsigned long npages, done = 0; + struct hv_domain *hvdom = to_hv_domain(immdom); + size_t size = pgsize * pgcount; + + map_flags = HV_MAP_GPA_READABLE; /* required */ + map_flags |= prot & IOMMU_WRITE ? HV_MAP_GPA_WRITABLE : 0; + + ret = hv_iommu_add_tree_mapping(hvdom, iova, paddr, size, map_flags); + if (ret) + return ret; + + if (hvdom->attached_dom) { + *mapped = size; + return 0; + } + + npages = size >> HV_HYP_PAGE_SHIFT; + while (done < npages) { + ulong completed, remain = npages - done; + + status = hv_iommu_map_pgs(hvdom, iova, paddr, remain, + map_flags); + + completed = hv_repcomp(status); + done = done + completed; + iova = iova + (completed << HV_HYP_PAGE_SHIFT); + paddr = paddr + (completed << HV_HYP_PAGE_SHIFT); + + if (hv_result(status) == HV_STATUS_INSUFFICIENT_MEMORY) { + ret = hv_call_deposit_pages(NUMA_NO_NODE, + hv_current_partition_id, + 256); + if (ret) + break; + } + if (!hv_result_success(status)) + break; + } + + if (!hv_result_success(status)) { + size_t done_size = done << HV_HYP_PAGE_SHIFT; + + hv_status_err(status, "pgs:%lx/%lx iova:%lx\n", + done, npages, iova); + /* + * lookup tree has all mappings [0 - size-1]. Below unmap will + * only remove from [0 - done], we need to remove second chunk + * [done+1 - size-1]. + */ + hv_iommu_del_tree_mappings(hvdom, iova, size - done_size); + hv_iommu_unmap_pages(immdom, iova - done_size, pgsize, + done, NULL); + if (mapped) + *mapped = 0; + } else + if (mapped) + *mapped = size; + + return hv_result_to_errno(status); +} + +static size_t hv_iommu_unmap_pages(struct iommu_domain *immdom, ulong iova, + size_t pgsize, size_t pgcount, + struct iommu_iotlb_gather *gather) +{ + unsigned long flags, npages; + struct hv_input_unmap_device_gpa_pages *input; + u64 status; + struct hv_domain *hvdom = to_hv_domain(immdom); + size_t unmapped, size = pgsize * pgcount; + + unmapped = hv_iommu_del_tree_mappings(hvdom, iova, size); + if (unmapped < size) + pr_err("%s: could not delete all mappings (%lx:%lx/%lx)\n", + __func__, iova, unmapped, size); + + if (hvdom->attached_dom) + return size; + + npages = size >> HV_HYP_PAGE_SHIFT; + + local_irq_save(flags); + input = *this_cpu_ptr(hyperv_pcpu_input_arg); + memset(input, 0, sizeof(*input)); + + input->device_domain.partition_id = HV_PARTITION_ID_SELF; + input->device_domain.domain_id.type = HV_DEVICE_DOMAIN_TYPE_S2; + input->device_domain.domain_id.id = hvdom->domid_num; + input->target_device_va_base = iova; + + status = hv_do_rep_hypercall(HVCALL_UNMAP_DEVICE_GPA_PAGES, npages, + 0, input, NULL); + local_irq_restore(flags); + + if (!hv_result_success(status)) + hv_status_err(status, "\n"); + + return unmapped; +} + +static phys_addr_t hv_iommu_iova_to_phys(struct iommu_domain *immdom, + dma_addr_t iova) +{ + u64 paddr = 0; + unsigned long flags; + struct hv_iommu_mapping *mapping; + struct interval_tree_node *node; + struct hv_domain *hvdom = to_hv_domain(immdom); + + spin_lock_irqsave(&hvdom->mappings_lock, flags); + node = interval_tree_iter_first(&hvdom->mappings_tree, iova, iova); + if (node) { + mapping = container_of(node, struct hv_iommu_mapping, iova); + paddr = mapping->paddr + (iova - mapping->iova.start); + } + spin_unlock_irqrestore(&hvdom->mappings_lock, flags); + + return paddr; +} + +/* + * Currently, hypervisor does not provide list of devices it is using + * dynamically. So use this to allow users to manually specify devices that + * should be skipped. (eg. hypervisor debugger using some network device). + */ +static struct iommu_device *hv_iommu_probe_device(struct device *dev) +{ + if (!dev_is_pci(dev)) + return ERR_PTR(-ENODEV); + + if (pci_devs_to_skip && *pci_devs_to_skip) { + int rc, pos = 0; + int parsed; + int segment, bus, slot, func; + struct pci_dev *pdev = to_pci_dev(dev); + + do { + parsed = 0; + + rc = sscanf(pci_devs_to_skip + pos, " (%x:%x:%x.%x) %n", + &segment, &bus, &slot, &func, &parsed); + if (rc) + break; + if (parsed <= 0) + break; + + if (pci_domain_nr(pdev->bus) == segment && + pdev->bus->number == bus && + PCI_SLOT(pdev->devfn) == slot && + PCI_FUNC(pdev->devfn) == func) { + + dev_info(dev, "skipped by Hyper-V IOMMU\n"); + return ERR_PTR(-ENODEV); + } + pos += parsed; + + } while (pci_devs_to_skip[pos]); + } + + /* Device will be explicitly attached to the default domain, so no need + * to do dev_iommu_priv_set() here. + */ + + return &hv_virt_iommu; +} + +static void hv_iommu_probe_finalize(struct device *dev) +{ + struct iommu_domain *immdom = iommu_get_domain_for_dev(dev); + + if (immdom && immdom->type == IOMMU_DOMAIN_DMA) + iommu_setup_dma_ops(dev); + else + set_dma_ops(dev, NULL); +} + +static void hv_iommu_release_device(struct device *dev) +{ + struct hv_domain *hvdom = dev_iommu_priv_get(dev); + + /* Need to detach device from device domain if necessary. */ + if (hvdom) + hv_iommu_detach_dev(&hvdom->iommu_dom, dev); + + dev_iommu_priv_set(dev, NULL); + set_dma_ops(dev, NULL); +} + +static struct iommu_group *hv_iommu_device_group(struct device *dev) +{ + if (dev_is_pci(dev)) + return pci_device_group(dev); + else + return generic_device_group(dev); +} + +static int hv_iommu_def_domain_type(struct device *dev) +{ + /* The hypervisor always creates this by default during boot */ + return IOMMU_DOMAIN_IDENTITY; +} + +static struct iommu_ops hv_iommu_ops = { + .capable = hv_iommu_capable, + .domain_alloc_identity = hv_iommu_domain_alloc_identity, + .domain_alloc_paging = hv_iommu_domain_alloc_paging, + .probe_device = hv_iommu_probe_device, + .probe_finalize = hv_iommu_probe_finalize, + .release_device = hv_iommu_release_device, + .def_domain_type = hv_iommu_def_domain_type, + .device_group = hv_iommu_device_group, + .default_domain_ops = &(const struct iommu_domain_ops) { + .attach_dev = hv_iommu_attach_dev, + .map_pages = hv_iommu_map_pages, + .unmap_pages = hv_iommu_unmap_pages, + .iova_to_phys = hv_iommu_iova_to_phys, + .free = hv_iommu_domain_free, + }, + .owner = THIS_MODULE, +}; + +static void __init hv_initialize_special_domains(void) +{ + hv_def_identity_dom.iommu_dom.geometry = default_geometry; + hv_def_identity_dom.domid_num = HV_DEVICE_DOMAIN_ID_S2_DEFAULT; /* 0 */ +} + +static int __init hv_iommu_init(void) +{ + int ret; + struct iommu_device *iommup = &hv_virt_iommu; + + if (!hv_is_hyperv_initialized()) + return -ENODEV; + + ret = iommu_device_sysfs_add(iommup, NULL, NULL, "%s", "hyperv-iommu"); + if (ret) { + pr_err("Hyper-V: iommu_device_sysfs_add failed: %d\n", ret); + return ret; + } + + /* This must come before iommu_device_register because the latter calls + * into the hooks. + */ + hv_initialize_special_domains(); + + ret = iommu_device_register(iommup, &hv_iommu_ops, NULL); + if (ret) { + pr_err("Hyper-V: iommu_device_register failed: %d\n", ret); + goto err_sysfs_remove; + } + + pr_info("Hyper-V IOMMU initialized\n"); + + return 0; + +err_sysfs_remove: + iommu_device_sysfs_remove(iommup); + return ret; +} + +void __init hv_iommu_detect(void) +{ + if (no_iommu || iommu_detected) + return; + + /* For l1vh, always expose an iommu unit */ + if (!hv_l1vh_partition()) + if (!(ms_hyperv.misc_features & HV_DEVICE_DOMAIN_AVAILABLE)) + return; + + iommu_detected = 1; + x86_init.iommu.iommu_init = hv_iommu_init; + + pci_request_acs(); +} diff --git a/include/linux/hyperv.h b/include/linux/hyperv.h index dfc516c1c719..2ad111727e82 100644 --- a/include/linux/hyperv.h +++ b/include/linux/hyperv.h @@ -1767,4 +1767,10 @@ static inline unsigned long virt_to_hvpfn(void *addr) #define HVPFN_DOWN(x) ((x) >> HV_HYP_PAGE_SHIFT) #define page_to_hvpfn(page) (page_to_pfn(page) * NR_HV_HYP_PAGES_IN_PAGE) +#ifdef CONFIG_HYPERV_IOMMU +void __init hv_iommu_detect(void); +#else +static inline void hv_iommu_detect(void) { } +#endif /* CONFIG_HYPERV_IOMMU */ + #endif /* _HYPERV_H */ -- 2.51.2.vfs.0.1
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 19 Jan 2026 22:42:27 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:21PM -0800, Mukesh R wrote: There is a Linux standard for giving credits when code is adapted from. This doesn't follow that standard. Please fix. This put must be sync as device must be detached from domain before attempting partition destruction. This was explicitly mentioned in the patch originated this code. Please fix, add a comment and credits to the commit message. Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 08:09:02 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:22PM -0800, Mukesh R wrote: Shouldn't the partition be put here? Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 08:13:55 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
Hi Mukesh, kernel test robot noticed the following build errors: [auto build test ERROR on tip/x86/core] [also build test ERROR on pci/next pci/for-linus arm64/for-next/core clk/clk-next soc/for-next linus/master arnd-asm-generic/master v6.19-rc6 next-20260119] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch#_base_tree_information] url: https://github.com/intel-lab-lkp/linux/commits/Mukesh-R/iommu-hyperv-rename-hyperv-iommu-c-to-hyperv-irq-c/20260120-145832 base: tip/x86/core patch link: https://lore.kernel.org/r/20260120064230.3602565-2-mrathor%40linux.microsoft.com patch subject: [PATCH v0 01/15] iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c config: i386-randconfig-001-20260120 (https://download.01.org/0day-ci/archive/20260121/202601210208.mg3YUkif-lkp@intel.com/config) compiler: gcc-14 (Debian 14.2.0-19) 14.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260121/202601210208.mg3YUkif-lkp@intel.com/reproduce) If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags | Reported-by: kernel test robot <lkp@intel.com> | Closes: https://lore.kernel.org/oe-kbuild-all/202601210208.mg3YUkif-lkp@intel.com/ All errors (new ones prefixed by >>): In file included from drivers/acpi/pci_root.c:20: 269 | __u128 irte; | ^~~~~~ | __u32 Kconfig warnings: (for reference only) WARNING: unmet direct dependencies detected for IRQ_REMAP Depends on [n]: IOMMU_SUPPORT [=y] && X86_64 [=n] && X86_IO_APIC [=y] && PCI_MSI [=n] && ACPI [=y] Selected by [y]: - HYPERV_IOMMU [=y] && IOMMU_SUPPORT [=y] && HYPERV [=y] && X86 [=y] vim +269 include/linux/dmar.h 2ae21010694e56 Suresh Siddha 2008-07-10 200 2ae21010694e56 Suresh Siddha 2008-07-10 201 struct irte { b1fe7f2cda2a00 Peter Zijlstra 2023-05-31 202 union { b1fe7f2cda2a00 Peter Zijlstra 2023-05-31 203 struct { 2ae21010694e56 Suresh Siddha 2008-07-10 204 union { 3bf17472226b00 Thomas Gleixner 2015-06-09 205 /* Shared between remapped and posted mode*/ 2ae21010694e56 Suresh Siddha 2008-07-10 206 struct { 3bf17472226b00 Thomas Gleixner 2015-06-09 207 __u64 present : 1, /* 0 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 208 fpd : 1, /* 1 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 209 __res0 : 6, /* 2 - 6 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 210 avail : 4, /* 8 - 11 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 211 __res1 : 3, /* 12 - 14 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 212 pst : 1, /* 15 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 213 vector : 8, /* 16 - 23 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 214 __res2 : 40; /* 24 - 63 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 215 }; 3bf17472226b00 Thomas Gleixner 2015-06-09 216 3bf17472226b00 Thomas Gleixner 2015-06-09 217 /* Remapped mode */ 3bf17472226b00 Thomas Gleixner 2015-06-09 218 struct { 3bf17472226b00 Thomas Gleixner 2015-06-09 219 __u64 r_present : 1, /* 0 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 220 r_fpd : 1, /* 1 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 221 dst_mode : 1, /* 2 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 222 redir_hint : 1, /* 3 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 223 trigger_mode : 1, /* 4 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 224 dlvry_mode : 3, /* 5 - 7 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 225 r_avail : 4, /* 8 - 11 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 226 r_res0 : 4, /* 12 - 15 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 227 r_vector : 8, /* 16 - 23 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 228 r_res1 : 8, /* 24 - 31 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 229 dest_id : 32; /* 32 - 63 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 230 }; 3bf17472226b00 Thomas Gleixner 2015-06-09 231 3bf17472226b00 Thomas Gleixner 2015-06-09 232 /* Posted mode */ 3bf17472226b00 Thomas Gleixner 2015-06-09 233 struct { 3bf17472226b00 Thomas Gleixner 2015-06-09 234 __u64 p_present : 1, /* 0 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 235 p_fpd : 1, /* 1 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 236 p_res0 : 6, /* 2 - 7 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 237 p_avail : 4, /* 8 - 11 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 238 p_res1 : 2, /* 12 - 13 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 239 p_urgent : 1, /* 14 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 240 p_pst : 1, /* 15 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 241 p_vector : 8, /* 16 - 23 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 242 p_res2 : 14, /* 24 - 37 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 243 pda_l : 26; /* 38 - 63 */ 2ae21010694e56 Suresh Siddha 2008-07-10 244 }; 2ae21010694e56 Suresh Siddha 2008-07-10 245 __u64 low; 2ae21010694e56 Suresh Siddha 2008-07-10 246 }; 2ae21010694e56 Suresh Siddha 2008-07-10 247 2ae21010694e56 Suresh Siddha 2008-07-10 248 union { 3bf17472226b00 Thomas Gleixner 2015-06-09 249 /* Shared between remapped and posted mode*/ 2ae21010694e56 Suresh Siddha 2008-07-10 250 struct { 3bf17472226b00 Thomas Gleixner 2015-06-09 251 __u64 sid : 16, /* 64 - 79 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 252 sq : 2, /* 80 - 81 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 253 svt : 2, /* 82 - 83 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 254 __res3 : 44; /* 84 - 127 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 255 }; 3bf17472226b00 Thomas Gleixner 2015-06-09 256 3bf17472226b00 Thomas Gleixner 2015-06-09 257 /* Posted mode*/ 3bf17472226b00 Thomas Gleixner 2015-06-09 258 struct { 3bf17472226b00 Thomas Gleixner 2015-06-09 259 __u64 p_sid : 16, /* 64 - 79 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 260 p_sq : 2, /* 80 - 81 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 261 p_svt : 2, /* 82 - 83 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 262 p_res3 : 12, /* 84 - 95 */ 3bf17472226b00 Thomas Gleixner 2015-06-09 263 pda_h : 32; /* 96 - 127 */ 2ae21010694e56 Suresh Siddha 2008-07-10 264 }; 2ae21010694e56 Suresh Siddha 2008-07-10 265 __u64 high; 2ae21010694e56 Suresh Siddha 2008-07-10 266 }; 2ae21010694e56 Suresh Siddha 2008-07-10 267 }; b1fe7f2cda2a00 Peter Zijlstra 2023-05-31 268 #ifdef CONFIG_IRQ_REMAP b1fe7f2cda2a00 Peter Zijlstra 2023-05-31 @269 __u128 irte; b1fe7f2cda2a00 Peter Zijlstra 2023-05-31 270 #endif b1fe7f2cda2a00 Peter Zijlstra 2023-05-31 271 }; b1fe7f2cda2a00 Peter Zijlstra 2023-05-31 272 }; 423f085952fd72 Thomas Gleixner 2010-10-10 273 -- 0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
{ "author": "kernel test robot <lkp@intel.com>", "date": "Wed, 21 Jan 2026 03:08:24 +0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
Hi Mukesh, kernel test robot noticed the following build warnings: [auto build test WARNING on tip/x86/core] [also build test WARNING on pci/next pci/for-linus arm64/for-next/core soc/for-next linus/master v6.19-rc6] [cannot apply to clk/clk-next arnd-asm-generic/master next-20260119] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch#_base_tree_information] url: https://github.com/intel-lab-lkp/linux/commits/Mukesh-R/iommu-hyperv-rename-hyperv-iommu-c-to-hyperv-irq-c/20260120-145832 base: tip/x86/core patch link: https://lore.kernel.org/r/20260120064230.3602565-16-mrathor%40linux.microsoft.com patch subject: [PATCH v0 15/15] mshv: Populate mmio mappings for PCI passthru config: x86_64-randconfig-003-20260120 (https://download.01.org/0day-ci/archive/20260121/202601210255.2ZZOLtMV-lkp@intel.com/config) compiler: gcc-14 (Debian 14.2.0-19) 14.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260121/202601210255.2ZZOLtMV-lkp@intel.com/reproduce) If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags | Reported-by: kernel test robot <lkp@intel.com> | Closes: https://lore.kernel.org/oe-kbuild-all/202601210255.2ZZOLtMV-lkp@intel.com/ All warnings (new ones prefixed by >>): 60 | static int __init setup_hv_full_mmio(char *str) | ^~~~~~~~~~~~~~~~~~ vim +/setup_hv_full_mmio +60 drivers/hv/mshv_root_main.c 58 59 bool hv_nofull_mmio; /* don't map entire mmio region upon fault */ > 60 static int __init setup_hv_full_mmio(char *str) 61 { 62 hv_nofull_mmio = true; 63 return 0; 64 } 65 __setup("hv_nofull_mmio", setup_hv_full_mmio); 66 -- 0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
{ "author": "kernel test robot <lkp@intel.com>", "date": "Wed, 21 Jan 2026 03:52:58 +0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
Hi Mukesh, kernel test robot noticed the following build warnings: [auto build test WARNING on tip/x86/core] [also build test WARNING on pci/next pci/for-linus arm64/for-next/core clk/clk-next soc/for-next linus/master arnd-asm-generic/master v6.19-rc6 next-20260120] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch#_base_tree_information] url: https://github.com/intel-lab-lkp/linux/commits/Mukesh-R/iommu-hyperv-rename-hyperv-iommu-c-to-hyperv-irq-c/20260120-145832 base: tip/x86/core patch link: https://lore.kernel.org/r/20260120064230.3602565-2-mrathor%40linux.microsoft.com patch subject: [PATCH v0 01/15] iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c config: i386-allmodconfig (https://download.01.org/0day-ci/archive/20260121/202601210423.wwOrf2K8-lkp@intel.com/config) compiler: gcc-14 (Debian 14.2.0-19) 14.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260121/202601210423.wwOrf2K8-lkp@intel.com/reproduce) If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags | Reported-by: kernel test robot <lkp@intel.com> | Closes: https://lore.kernel.org/oe-kbuild-all/202601210423.wwOrf2K8-lkp@intel.com/ All warnings (new ones prefixed by >>): In file included from drivers/iommu/intel/irq_remapping.c:6: include/linux/dmar.h:269:17: error: unknown type name '__u128'; did you mean '__u32'? 269 | __u128 irte; | ^~~~~~ | __u32 drivers/iommu/intel/irq_remapping.c: In function 'modify_irte': drivers/iommu/intel/irq_remapping.c:181:17: error: unknown type name 'u128' 181 | u128 old = irte->irte; | ^~~~ In file included from arch/x86/include/asm/bug.h:193, from arch/x86/include/asm/alternative.h:9, from arch/x86/include/asm/barrier.h:5, from include/asm-generic/bitops/generic-non-atomic.h:7, from include/linux/bitops.h:28, from include/linux/kernel.h:23, from include/linux/interrupt.h:6, from drivers/iommu/intel/irq_remapping.c:5: include/linux/atomic/atomic-arch-fallback.h:326:14: error: void value not ignored as it ought to be 326 | ___r = raw_cmpxchg128((_ptr), ___o, (_new)); \ | ^ include/asm-generic/bug.h:110:32: note: in definition of macro 'WARN_ON' 110 | int __ret_warn_on = !!(condition); \ | ^~~~~~~~~ include/linux/atomic/atomic-instrumented.h:4956:9: note: in expansion of macro 'raw_try_cmpxchg128' 4956 | raw_try_cmpxchg128(__ai_ptr, __ai_oldp, __VA_ARGS__); \ | ^~~~~~~~~~~~~~~~~~ drivers/iommu/intel/irq_remapping.c:182:26: note: in expansion of macro 'try_cmpxchg128' 182 | WARN_ON(!try_cmpxchg128(&irte->irte, &old, irte_modified->irte)); | ^~~~~~~~~~~~~~ drivers/iommu/intel/irq_remapping.c: In function 'intel_ir_set_vcpu_affinity': 1270 | ~(-1UL << PDA_HIGH_BIT); | ^~ Kconfig warnings: (for reference only) WARNING: unmet direct dependencies detected for IRQ_REMAP Depends on [n]: IOMMU_SUPPORT [=y] && X86_64 [=n] && X86_IO_APIC [=y] && PCI_MSI [=y] && ACPI [=y] Selected by [y]: - HYPERV_IOMMU [=y] && IOMMU_SUPPORT [=y] && HYPERV [=y] && X86 [=y] vim +1270 drivers/iommu/intel/irq_remapping.c b106ee63abccbba drivers/iommu/intel_irq_remapping.c Jiang Liu 2015-04-13 1241 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1242 static int intel_ir_set_vcpu_affinity(struct irq_data *data, void *info) 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1243 { 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1244 struct intel_ir_data *ir_data = data->chip_data; 53527ea1b70224d drivers/iommu/intel/irq_remapping.c Sean Christopherson 2025-06-11 1245 struct intel_iommu_pi_data *pi_data = info; 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1246 ed1e48ea4370300 drivers/iommu/intel/irq_remapping.c Jacob Pan 2024-04-23 1247 /* stop posting interrupts, back to the default mode */ 53527ea1b70224d drivers/iommu/intel/irq_remapping.c Sean Christopherson 2025-06-11 1248 if (!pi_data) { 2454823e97a63d8 drivers/iommu/intel/irq_remapping.c Sean Christopherson 2025-03-19 1249 __intel_ir_reconfigure_irte(data, true); 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1250 } else { 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1251 struct irte irte_pi; 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1252 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1253 /* 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1254 * We are not caching the posted interrupt entry. We 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1255 * copy the data from the remapped entry and modify 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1256 * the fields which are relevant for posted mode. The 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1257 * cached remapped entry is used for switching back to 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1258 * remapped mode. 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1259 */ 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1260 memset(&irte_pi, 0, sizeof(irte_pi)); 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1261 dmar_copy_shared_irte(&irte_pi, &ir_data->irte_entry); 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1262 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1263 /* Update the posted mode fields */ 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1264 irte_pi.p_pst = 1; 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1265 irte_pi.p_urgent = 0; 53527ea1b70224d drivers/iommu/intel/irq_remapping.c Sean Christopherson 2025-06-11 1266 irte_pi.p_vector = pi_data->vector; 53527ea1b70224d drivers/iommu/intel/irq_remapping.c Sean Christopherson 2025-06-11 1267 irte_pi.pda_l = (pi_data->pi_desc_addr >> 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1268 (32 - PDA_LOW_BIT)) & ~(-1UL << PDA_LOW_BIT); 53527ea1b70224d drivers/iommu/intel/irq_remapping.c Sean Christopherson 2025-06-11 1269 irte_pi.pda_h = (pi_data->pi_desc_addr >> 32) & 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 @1270 ~(-1UL << PDA_HIGH_BIT); 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1271 688124cc541f60d drivers/iommu/intel/irq_remapping.c Sean Christopherson 2025-03-19 1272 ir_data->irq_2_iommu.posted_vcpu = true; 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1273 modify_irte(&ir_data->irq_2_iommu, &irte_pi); 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1274 } 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1275 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1276 return 0; 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1277 } 8541186faf3b596 drivers/iommu/intel_irq_remapping.c Feng Wu 2015-06-09 1278 -- 0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
{ "author": "kernel test robot <lkp@intel.com>", "date": "Wed, 21 Jan 2026 05:09:48 +0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
Hi Mukesh, On Mon, 19 Jan 2026 22:42:15 -0800 Mukesh R <mrathor@linux.microsoft.com> wrote: I think some introduction/background to L1VH would help. It may be clearer to state that the hypervisor supports Linux IOMMU paging domains through map/unmap hypercalls, mapping GPAs to HPAs using stage‑2 I/O page tables. This may warrant introducing a new IOMMU domain feature flag, as it performs mappings but does not support map/unmap semantics in the same way as a paging domain.
{ "author": "Jacob Pan <jacob.pan@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 13:50:32 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:24PM -0800, Mukesh R wrote: <snip> Shouldn't the inner struct be packed instead? Why should the union be packed? Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 14:17:24 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:25PM -0800, Mukesh R wrote: Why not moving this static function definition above the called instead of defining the prototype? This variable is redundant. It looks like this value always fits into 32 bit, so what is the value in returning 64 bit? Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 14:22:23 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:26PM -0800, Mukesh R wrote: Should this one be renamed into hv_build_devid_type_vmbus() to align with the other two function names? Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 14:27:33 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:27PM -0800, Mukesh R wrote: <snip> The return above is never reached. hvdom varaible is redundant. Why goto here and not return NULL like above? Shouldn't this be modified iff the detach succeeded? There is some inconsistency in namings and behaviour of paired functions: 1. The pair of hv_iommu_unmap_pages is called hv_iommu_map_pgs 2. hv_iommu_map_pgs doesn't print status in case of error. It would be much better to keep this code consistent. hv_def_identity_dom is a static global variable. Why not initialize hv_def_identity_dom upon definition instead of introducing a new function? It looks weird to initialize an object after creating sysfs entries for it. It should be the other way around. Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 16:12:42 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:28PM -0800, Mukesh R wrote: l1vh and root are mutually exclusive partitions. If you wanted to highlight that it's l1vh itself and not its child guest, then "l1vh parent" term would do. Looks like the only special case is for attached logical devices, otherwise hv_current_partition_id is used. Can the logic simplified here? Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 16:47:07 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
Hi Mukesh, kernel test robot noticed the following build warnings: [auto build test WARNING on tip/x86/core] [also build test WARNING on pci/next pci/for-linus arm64/for-next/core clk/clk-next soc/for-next linus/master v6.19-rc6 next-20260120] [cannot apply to arnd-asm-generic/master] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in https://git-scm.com/docs/git-format-patch#_base_tree_information] url: https://github.com/intel-lab-lkp/linux/commits/Mukesh-R/iommu-hyperv-rename-hyperv-iommu-c-to-hyperv-irq-c/20260120-145832 base: tip/x86/core patch link: https://lore.kernel.org/r/20260120064230.3602565-4-mrathor%40linux.microsoft.com patch subject: [PATCH v0 03/15] x86/hyperv: add insufficient memory support in irqdomain.c config: i386-randconfig-053-20260120 (https://download.01.org/0day-ci/archive/20260121/202601210731.f1WLdgcO-lkp@intel.com/config) compiler: gcc-14 (Debian 14.2.0-19) 14.2.0 If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags | Reported-by: kernel test robot <lkp@intel.com> | Closes: https://lore.kernel.org/oe-kbuild-all/202601210731.f1WLdgcO-lkp@intel.com/ cocci warnings: (new ones prefixed by >>) vim +90 arch/x86/hyperv/irqdomain.c 72 73 static int hv_map_interrupt(u64 ptid, union hv_device_id device_id, bool level, 74 int cpu, int vector, 75 struct hv_interrupt_entry *ret_entry) 76 { 77 u64 status; 78 int rc, deposit_pgs = 16; /* don't loop forever */ 79 80 while (deposit_pgs--) { 81 status = hv_map_interrupt_hcall(ptid, device_id, level, cpu, 82 vector, ret_entry); 83 84 if (hv_result(status) != HV_STATUS_INSUFFICIENT_MEMORY) 85 break; 86 87 rc = hv_call_deposit_pages(NUMA_NO_NODE, ptid, 1); 88 if (rc) 89 break; > 90 }; 91 92 if (!hv_result_success(status)) 93 hv_status_err(status, "\n"); 94 95 return hv_result_to_errno(status); 96 } 97 -- 0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
{ "author": "kernel test robot <lkp@intel.com>", "date": "Wed, 21 Jan 2026 08:53:50 +0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:29PM -0800, Mukesh R wrote: No need updating ret here: it's 0 after the previous call. Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 17:41:39 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:30PM -0800, Mukesh R wrote: Semaphore can't be taken under spinlock. Get it instead. Why this check is needed again? The region type is stored on the region itself. And the type is checked on the caller side. This call needs to be protected by the spinlock. Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 20 Jan 2026 17:53:29 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
Hi Mukesh, On Mon, 19 Jan 2026 22:42:27 -0800 Mukesh R <mrathor@linux.microsoft.com> wrote: Given we are also developing a guest iommu driver on hyperv, I think it is more clear to name them accordingly. Perhaps, hyperv-iommu-root.c? Will this driver be x86 only? DMA and IRQ remapping should be separate I don't think this is needed since this driver cannot be a module should not depend on Intel's DMAR rename to num_dev_attached? This function is not iommu specific. Maybe move it to mshv code? Attached domain can change anytime, what guarantee does the caller have? nit: use consistent coding style, inverse Christmas tree. why is this an error if user input choose not to do direct attach? This is true only when unique_id wraps around, right? Then this driver stops working? can you use an IDR for the unique_id and free it as you detach instead of doing this cyclic allocation? you could free the domid here, no? The IOMMU driver should be agnostic to the type of consumer, whether a userspace driver or a VM. This comment is not necessary. This does not match upstream kernel prototype, which kernel version is this based on? I will stop here for now. struct iommu_domain_ops { int (*attach_dev)(struct iommu_domain *domain, struct device *dev); This could be initialized statically.
{ "author": "Jacob Pan <jacob.pan@linux.microsoft.com>", "date": "Wed, 21 Jan 2026 21:18:06 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/19/2026 10:42 PM, Mukesh R wrote: This should go inside the #if IS_ENABLED(CONFIG_MSHV_ROOT) section.
{ "author": "Nuno Das Neves <nunodasneves@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 10:23:04 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/19/2026 10:42 PM, Mukesh R wrote: With this commit, the IOCTL number is exposed to userspace but it doesn't work. Ideally the IOCTL number should be added in the commit where it becomes usable.
{ "author": "Nuno Das Neves <nunodasneves@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 10:25:36 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/19/2026 10:42 PM, Mukesh R wrote: Since the code is very similar to Wei's original commit, the way I'd recommend to do it is: 1. Change the commit author to Wei, using git commit --amend --author= and 2. Put his signed-off line before yours: Signed-off-by: Wei Liu <wei.liu@kernel.org> Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com> This shows he is the author of the commit but you ported it. If you feel you changed it enough that it should be considered co-authored, you can instead keep your authorship of the commit and put: Co-developed-by: Wei Liu <wei.liu@kernel.org> Signed-off-by: Wei Liu <wei.liu@kernel.org> Signed-off-by: Mukesh Rathor <mrathor@linux.microsoft.com>
{ "author": "Nuno Das Neves <nunodasneves@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 10:32:09 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/19/2026 10:42 PM, Mukesh R wrote: What is the reason for having this as a separate commit from patch 15? It seems like removing this code and adding the mmio intercept handling could be done in one patch.
{ "author": "Nuno Das Neves <nunodasneves@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 10:34:55 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/23/26 10:25, Nuno Das Neves wrote: Correct, I switched it because the next patch won't compile without it as it needs the declarations here. It could be combined into one big patch, but I think normally one would not expect full functionality until the release is certified to be that feature compliant anyways. Hope that makes sense. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 16:36:28 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/23/26 10:32, Nuno Das Neves wrote: Perfect! Thank you, that is exactly the information I was trying to seek... makes sense. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 16:37:34 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/20/26 14:17, Stanislav Kinsburskii wrote: From GCC docs: Specifying this attribute for struct and union types is equivalent to specifying the packed attribute on each of the structure or union members. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 16:38:56 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/20/26 14:22, Stanislav Kinsburskii wrote: Did you see the function implementation? It has other dependencies that are later, it would need code reorg. Thanks, -Mukesh Not really. It helps with debug by putting a quick print, and is harmless. The ABI has device id defined as 64bits where this is assigned. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 16:42:54 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/20/26 14:27, Stanislav Kinsburskii wrote: No, because hyperv only defines two types of device ids, and it would unnecessary at to confusion. vmbus uses one the two types of device ids.
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 16:44:01 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/20/26 16:12, Stanislav Kinsburskii wrote: Some debug code there got removed. Will fix in next version. We want to still free the domain and not let it get stuck. The purpose is more to make sure detach was called before domain free. The pair of hv_iommu_unmap_pages is hv_iommu_map_pages right above. hv_iommu_map_pgs could be renamed to hv_iommu_map_pgs_hcall I suppose. it does: hv_status_err(status, "\n"); <============== Originally, it was function. I changed it static, but during 6.6 review I changed it back to function. I can't remember why, but is pretty harmless. We may add more domains, for example null domain to the initilization in future. Not sure if it should be, much easier to remove sysfs entry than other cleanup, even tho iommu_device_unregister is there. I am sure we'll add more code here, probably why it was originally done this way. Thanks, -Mukesh ... snip........
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 17:26:19 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/21/26 21:18, Jacob Pan wrote: well, l1vh is not quite root, more like a parent. But we've been using l1vh root loosely to mean l1vh parent. so probably ok to rename it to hyperv-iommu-root.c. I prefer not calling it parent or something like that. j Yes for now. not sure i follow. Well, it is getting the information from mshv by calling a function there for iommu, and is not needed if no HYPER_IOMMU. So this is probably the best place for it. Not sure I understand what can change: the device moving from attached to non-attached? or the domain getting deleted? In any case, this is called from leaf functions, so that should not happen... and it will return false if the device did somehow got removed. Like the error message says: on l1vh, direct attaches of host devices (eg dpdk) is not supported. and l1vh only does direct attaches. IOW, no host devices on l1vh. Correct. It's a u32, so if my math is right, and a device is attached every second, it will take 136 years to wrap! Did i get that right? sorry, don't follow what you mean by domid, you mean unique_id? As I mentioned in the cover letter: Based on: 8f0b4cce4481 (origin/hyperv-next) which is now 6.19 based. I think you got it backwards, 6.6 has this. 6.19 has extra paremeter. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 18:01:29 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/20/26 16:47, Stanislav Kinsburskii wrote: We've been loosely using "l1vh root" to mean "privilated l1vh" as opposed to l1vh guests. I think that is fine. l1vh parent is confusing, as it may also refer to l1vh parent, which would be the host. so as long as the context is clear, we are ok. Could be, but at the cost of clear upfront clarity. this nicely tells the reader that a logical ID has different cases, where as PCI does not. End instructions are the same. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 18:08:49 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/23/26 10:34, Nuno Das Neves wrote: Just ease of review and porting patches from this branch to that branch to that release to this release... I am sure someone would have asked for this to be a separate patch :). Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 18:12:14 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/20/26 17:53, Stanislav Kinsburskii wrote: Yeah, something didn't feel right here and I meant to recheck, now regret rushing to submit the patch. Rethinking, I think the pt_mem_regions_lock is not needed to protect the uaddr because unmap will properly serialize via the mm lock. To make sure region did not change. This check is under lock. This is sorta fast path to bail. We recheck under partition lock above. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 18:19:15 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/20/26 13:50, Jacob Pan wrote: Ok, i can add something, but l1vh was very well introduced if you search the mshv commits for "l1vh". sure. Yeah, I was hoping we can get by for now without it. At least in case of the cloud hypervisor, entire guest ram is mapped anyways. We can document it and work on enhancements which are much easier once we have a baseline. For now, it's a paging domain will all pages pinned.. :).
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 23 Jan 2026 18:27:34 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Fri, Jan 23, 2026 at 05:26:19PM -0800, Mukesh R wrote: <snip> How can one debug subseqent errors if num_attchd is decremented unconditionally? In reality the device is left attached, but the related kernel metadata is gone. Hv_iommu_map_pages is a wrapper around hv_iommu_map_pgs while hv_iommu_unmap_pages is a wrapper around the correspodning hypercall. That's the inconsistency I meant. It does not. I guess you are confusing it with some other function. Here is the function: Sysfs provides user space access to kernel objects. If the object is not initialized, it's not only a useless sysfs entry, but also a potential cause for kernel panic if user space will try to access this entry before the object is initialized. Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Mon, 26 Jan 2026 07:57:35 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Fri, Jan 23, 2026 at 06:19:15PM -0800, Mukesh R wrote: How can this happen? One can't change VMA type without unmapping it first. And unmapping it leads to a kernel MMIO region state dangling around without corresponding user space mapping. This is similar to dangling pinned regions and should likely be addressed the same way by utilizing MMU notifiers to destpoy memoty regions is VMA is detached. Accessing the list of regions without lock is unsafe. Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Mon, 26 Jan 2026 10:15:53 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Fri, Jan 23, 2026 at 04:42:54PM -0800, Mukesh R wrote: Why not placing the caller side after the function definition then? Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Mon, 26 Jan 2026 12:50:03 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/26/26 07:57, Stanislav Kinsburskii wrote: Error is printed in case of failed detach. If there is panic, at least you can get some info about the device. Metadata in hypervisor is around if failed. Unmap does not need intermediate function. We print error upon its failure in hv_iommu_map_pages(): if (!hv_result_success(status)) { size_t done_size = done << HV_HYP_PAGE_SHIFT; hv_status_err(status, "pgs:%lx/%lx iova:%lx\n", done, npages, iova); I hear you... but, o there is nothing under sysfs to be accessed when created o it is during boot o it should almost never fail... o iommu_device_sysfs_remove is much more light weight than iommu_device_unregister o i expect more to be added there as we enhance it Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 26 Jan 2026 19:02:29 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/26/26 10:15, Stanislav Kinsburskii wrote: Right, and vm_flags would not be mmio expected then. I don't think we need that. Either it succeeds if the region did not change at all, or just fails. I am not sure why? This check is done by a vcpu thread, so regions will not have just gone away. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Mon, 26 Jan 2026 19:07:22 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 26, 2026 at 07:02:29PM -0800, Mukesh R wrote: With this approach the only thing left is a kernel message. But if the state is kept intact, one could collect a kernel core and analyze it. And note, that there won't be a hypervisor core by default: our main context with the usptreamed version of the driver is L1VH and a kernel core is the only thing a third party customer can provide for our analysis. Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 27 Jan 2026 10:46:49 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 26, 2026 at 07:07:22PM -0800, Mukesh R wrote: I'm afraid we do, as if the driver mapped a page with the previous memory region, and then the region is unmapped, the page will stay mapped in the hypervisor, but will be considered free by kernel, which in turn will lead to GPF upn next allocation. With pinned regions we issue is similar but less impacting: pages can't be released by user space unmapping and thus will be simply leaked, but the system stays intact. MMIO regions are simila to movable region in this regard: they don't reference the user pages, and thus this guest region replaement is a stright wat to kernel panic. This is shared resources. Multiple VP thread get into this function simultaneously, so there is a race already. But this one we can live with without locking as they don't mutate the list of the regions. The issue happens when VMM adds or removed another region as it mutates the list and races with VP threads doing this lookup. Thanks, Stanislav
{ "author": "Stanislav Kinsburskii <skinsburskii@linux.microsoft.com>", "date": "Tue, 27 Jan 2026 10:57:08 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
Hi Mukesh, On Fri, 23 Jan 2026 18:01:29 -0800 Mukesh R <mrathor@linux.microsoft.com> wrote: yeah, something specific and different than the guest driver will do. If there is nothing x86 specific in this driver (assuming the hypercalls here are not x86 only), maybe you can move to the generic startup code. In IOMMU subsystem, DMA remapping and IRQ remapping can be turned on/off independently. e.g. you could have an option to turn on IRQ remapping w/o DMA remapping. But here you tied them together. ok, maybe move it to mshv after we have a second user. But the function name can be just hv_get_curr_partid(void), no? I was thinking the device can be attached to a different domain type at runtime, e.g. via sysfs to identity or DMA. But I guess here is a static attachment either for l1vh or root. This hv_no_attdev flag is really confusing to me, by default hv_no_attdev is false, which allows direct attach. And you are saying l1vh allows it. Why is this flag also controls host device attachment in l1vh? If you can tell the difference between direct host device attach and other direct attach, why don't you reject always reject host attach in l1vh? This is still a unnecessary vulnerability. yes. where is this repo? you are right, this is a very recent change. my bad.
{ "author": "Jacob Pan <jacob.pan@linux.microsoft.com>", "date": "Tue, 27 Jan 2026 11:21:44 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
Hi Mukesh, On second thought, if the hv_no_attdev knob is only meant to control host domain attach vs. direct attach, then it is irrelevant on L1VH. Would it make more sense to rename this to something like hv_host_disable_direct_attach? That would better reflect its scope and allow it to be ignored under L1VH, and reduce the risk of users misinterpreting or misusing it.
{ "author": "Jacob Pan <jacob.pan@linux.microsoft.com>", "date": "Tue, 27 Jan 2026 14:31:19 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Mon, Jan 19, 2026 at 10:42:23PM -0800, Mukesh R wrote: Don't mix up cleanup changes. Do it in a separate patch. - Mani -- மணிவண்ணன் சதாசிவம்
{ "author": "Manivannan Sadhasivam <mani@kernel.org>", "date": "Wed, 28 Jan 2026 19:33:57 +0530", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On Fri, Jan 23, 2026 at 04:42:54PM -0800, Mukesh R wrote: Such debug print do not exist now. So there is no need of a variable, drop it. - Mani -- மணிவண்ணன் சதாசிவம்
{ "author": "Manivannan Sadhasivam <mani@kernel.org>", "date": "Wed, 28 Jan 2026 20:06:21 +0530", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/27/26 14:31, Jacob Pan wrote: It would, but it is kernel parameter and needs to be terse. It would be documented properly tho, so we should be ok. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 30 Jan 2026 14:10:57 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/27/26 10:57, Stanislav Kinsburskii wrote: There are no ram pages for mmio regions. Also, we don't do much with mmio regions other than tell the hyp about it. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 30 Jan 2026 14:17:24 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }
lkml
[PATCH v0 00/15] PCI passthru on Hyper-V (Part I)
From: Mukesh Rathor <mrathor@linux.microsoft.com> Implement passthru of PCI devices to unprivileged virtual machines (VMs) when Linux is running as a privileged VM on Microsoft Hyper-V hypervisor. This support is made to fit within the workings of VFIO framework, and any VMM needing to use it must use the VFIO subsystem. This supports both full device passthru and SR-IOV based VFs. There are 3 cases where Linux can run as a privileged VM (aka MSHV): Baremetal root (meaning Hyper-V+Linux), L1VH, and Nested. At a high level, the hypervisor supports traditional mapped iommu domains that use explicit map and unmap hypercalls for mapping and unmapping guest RAM into the iommu subsystem. Hyper-V also has a concept of direct attach devices whereby the iommu subsystem simply uses the guest HW page table (ept/npt/..). This series adds support for both, and both are made to work in VFIO type1 subsystem. While this Part I focuses on memory mappings, upcoming Part II will focus on irq bypass along with some minor irq remapping updates. This patch series was tested using Cloud Hypervisor verion 48. Qemu support of MSHV is in the works, and that will be extended to include PCI passthru and SR-IOV support also in near future. Based on: 8f0b4cce4481 (origin/hyperv-next) Thanks, -Mukesh Mukesh Rathor (15): iommu/hyperv: rename hyperv-iommu.c to hyperv-irq.c x86/hyperv: cosmetic changes in irqdomain.c for readability x86/hyperv: add insufficient memory support in irqdomain.c mshv: Provide a way to get partition id if running in a VMM process mshv: Declarations and definitions for VFIO-MSHV bridge device mshv: Implement mshv bridge device for VFIO mshv: Add ioctl support for MSHV-VFIO bridge device PCI: hv: rename hv_compose_msi_msg to hv_vmbus_compose_msi_msg mshv: Import data structs around device domains and irq remapping PCI: hv: Build device id for a VMBus device x86/hyperv: Build logical device ids for PCI passthru hcalls x86/hyperv: Implement hyperv virtual iommu x86/hyperv: Basic interrupt support for direct attached devices mshv: Remove mapping of mmio space during map user ioctl mshv: Populate mmio mappings for PCI passthru MAINTAINERS | 1 + arch/arm64/include/asm/mshyperv.h | 15 + arch/x86/hyperv/irqdomain.c | 314 ++++++--- arch/x86/include/asm/mshyperv.h | 21 + arch/x86/kernel/pci-dma.c | 2 + drivers/hv/Makefile | 3 +- drivers/hv/mshv_root.h | 24 + drivers/hv/mshv_root_main.c | 296 +++++++- drivers/hv/mshv_vfio.c | 210 ++++++ drivers/iommu/Kconfig | 1 + drivers/iommu/Makefile | 2 +- drivers/iommu/hyperv-iommu.c | 1004 +++++++++++++++++++++------ drivers/iommu/hyperv-irq.c | 330 +++++++++ drivers/pci/controller/pci-hyperv.c | 207 ++++-- include/asm-generic/mshyperv.h | 1 + include/hyperv/hvgdk_mini.h | 11 + include/hyperv/hvhdk_mini.h | 112 +++ include/linux/hyperv.h | 6 + include/uapi/linux/mshv.h | 31 + 19 files changed, 2182 insertions(+), 409 deletions(-) create mode 100644 drivers/hv/mshv_vfio.c create mode 100644 drivers/iommu/hyperv-irq.c -- 2.51.2.vfs.0.1
On 1/27/26 10:46, Stanislav Kinsburskii wrote: Again, most of linux stuff is cleaned up, the only state is in hypervisor, and hypervisor can totally protect itself and devices. So there is not much in kernel core as it got cleaned up already. Think of this as additional check, we can remove in future after it stands the test of time, until then, every debugging bit helps. Wei can correct me, but we are not only l1vh focused here. There is work going on on all fronts. Thanks, -Mukesh
{ "author": "Mukesh R <mrathor@linux.microsoft.com>", "date": "Fri, 30 Jan 2026 14:51:19 -0800", "thread_id": "20260120064230.3602565-1-mrathor@linux.microsoft.com.mbox.gz" }