Linux kbuild/kconfig development
 help / color / mirror / Atom feed
* [PATCH v2 00/11] tools: Introduce a kernel configuration checker
@ 2026-12-03 22:49 Ahmed S. Darwish
  2026-12-03 22:49 ` [PATCH v2 01/11] kconfig-audit: Add schema for policy files Ahmed S. Darwish
                   ` (10 more replies)
  0 siblings, 11 replies; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Hi,

Last September in Prague I proposed a kernel configuration checker:

    https://youtu.be/hqnOmdpGBdQ

This series adds kconfig-audit, a Python tool that checks a kernel .config
against a YAML configuration policy and reports found issues by severity.

It also adds a PREEMPT_RT configuration policy, support for policy
overlays, documentation, and a make auditconfig target.

Beside mainline policies, the tool is designed to let downstream projects,
such as Debian and systemd, check their kernel configuration requirements.

Special thanks to Julian Braha, Nathan Chancellor, Nicolas Schier, and
Emanuele Rocca for all the v1 reviews.

v1: https://msgid.link/20261106091922.7560-1-darwi@linutronix.de

Changelog v2
============

(I) Standardize terminology
---------------------------

Rename the tool to 'kconfig-audit'.
Use 'policy' for kernel configuration policies, instead of 'rules'.
Use 'enabled', 'disabled', and 'neutral' for rule expectations.

Adapt all code and documentation accordingly.

(II) Introduce strict schema versioning
---------------------------------------

This allows repositories outside of the kernel tree (e.g. systemd) to
include their own kernel configuration policies while being sure that such
policies will continue to work for future kconfig-audit releases.

Implement a light schema versioning scheme that is similar in spirit to
Kubernetes object specs; i.e., with an `api_version` and `kind` fields.

Policy files are now required to have on top:

    api_version: kconfig-audit.kernel.org/v1
    kind: Policy

Overlay files are now required to have:

    api_version: kconfig-audit.kernel.org/v1
    kind: PolicyOverlay

And the tool's schemas are now structured as:

    $ tree ~/linux/tools/kconfig-audit/schema/

      tools/kconfig-audit/schema/
      ├── policy-overlay-v1.yml
      ├── policy-v1.yml
      └── rule.yml

The Python code loads the appropriate schema according to `api_version`.

After merge, forward compatibility is intended to be strictly enforced.

Also introduce a new sub-command for listing supported APIs:

    $ ./tools/kconfig-audit/audit.py list-api-versions

      kconfig-audit.kernel.org/v1

(III) Introduce a pattern priority mechanism
--------------------------------------------

Introduce pattern rules priorities, so that a .config symbol matching more
than one pattern rule can be gracefully handled.

For example, for the policy file below:

    rules:
      - name_pattern: CONFIG_DEBUG
        expected: disabled
        severity: medium

      - name_pattern: CONFIG_DEBUG_INFO
        pattern_prio: 1
        expected: enabled
        severity: low

If the checked .config has CONFIG_DEBUG_INFO_DWARF4, then that symbol is
expected to be enabled.  That's the case because the CONFIG_DEBUG_INFO
pattern has a higher priority of 1, while the broader CONFIG_DEBUG pattern
has a (lower) default priority of zero.

Priorities are enforced by the schema from 1 to 100.

(IV) Handle all kconfig symbol types
------------------------------------

Model kconfig symbols in a proper python objects data model.  For below
policy:

    rules:
      - name: CONFIG_PREEMPT_RT
        expected: enabled
        severity: fatal

      - name: CONFIG_CPU_FREQ
        expected: enabled
        severity: high

      - name: CONFIG_DRM
        expected: disabled
        severity: info

The checked .config:

    CONFIG_PREEMPT_RT=1
    CONFIG_CPU_FREQ="string"
    CONFIG_DRM=0x1234

will trigger error reports of a type mismatch for each symbol, since a
kconfig tristate was expected instead.

Due to the better kconfig symbols modelling, the tool also now complains
about any invalid syntax in config files.

(V) Add a configuration policies guide
--------------------------------------

Transform v1 documentation into a full configuration policies guide.

Document kconfig-audit report format, exit codes, policy file format,
overlay files format, rule matching semantics, rule precedence semantics,
and a reference for the policy files grammar.

(VI) Maintain stricter separation between YAML parsing and data model
---------------------------------------------------------------------

Remove all YAML dictionary access from the data model init code.

The tool was already very careful about separating the data model from the
parsed YAML dictionaries, but some minimal YAML parsing leaked into objects
initialization logic. This is now fully removed.

The tool's python code has below design:

    KernelConfig      # internal model, typed .config symbols repository
    KernelConfigFile  # parser

    Policy            # internal model, typed policy rules repository
    PolicyFile        # parser

    PolicyOverlay     # internal model, typed overrides repository
    PolicyOverlayFile # parser

    Schema            # internal model, dictionary-like
    SchemaFile        # parser

(VII) Tighten policy checking
-----------------------------

Allow pattern rules with `expected: enabled`.

Make explicit rules poke a hole in name_pattern rules, or modify it.  For
example, below policy:

    rules:
      - name_pattern: CONFIG_CC_HAS_COUNTED_BY
        expected: enabled
        severity: fatal

      - name: CONFIG_CC_HAS_COUNTED_BY_PTR
        expected: enabled
        severity: low

If the .config has CONFIG_CC_HAS_COUNTED_BY_PTR disabled, then the conflict
will be reported with a low (instead of fatal) severity.

Moreover:

* Report conflicting expectations when a symbol matches multiple pattern
  rules.

* Report an issue if an `expected: enabled` pattern matches no .config
  enabled symbols.

* Reject invalid .config syntax, repeated CONFIG_* definitions, and policy
  overlays containing duplicate rules.

* Let pattern rules matching non-tristate symbols report type mismatches.

* Update the PREEMPT_RT policy for CONFIG_DEBUG_FS_ALLOW_{ALL,NONE} and
  CONFIG_DEBUG_INFO.  Correct the CONFIG_DEBUG_KERNEL rationale.  Add entry
  for CONFIG_RCU_NOCB_CPU.  Incorporate further review feedback.

(VIII) Move the auditconfig Makefile target to PQ end
-----------------------------------------------------

Place the `auditconfig` Makefile target after the Python tool and its
documentation, so it does not block review and merging of the tool itself.

Thanks!

8<-----

Ahmed S. Darwish (11):
  kconfig-audit: Add schema for policy files
  kconfig-audit: Introduce a PREEMPT_RT configuration policy
  kconfig-audit: Add the configuration checker code
  Documentation: Describe kconfig-audit usage and design
  kconfig-audit: Split policy schema for component reuse
  kconfig-audit: Introduce policy overlays schema
  kconfig-audit: Add support for policy overlays
  Documentation: kconfig-audit: Describe policy overlays
  MAINTAINERS: Add entry for kernel configuration audit
  kconfig: Introduce auditconfig target
  Documentation: Describe auditconfig build target

 Documentation/admin-guide/README.rst          |   29 +
 .../real-time/kernel-configuration.rst        |    3 +
 Documentation/tools/index.rst                 |    1 +
 Documentation/tools/kconfig-audit.rst         |  628 +++++++++
 MAINTAINERS                                   |   10 +
 scripts/kconfig/Makefile                      |   25 +
 tools/kconfig-audit/audit.py                  | 1151 +++++++++++++++++
 tools/kconfig-audit/policy/preempt_rt.yml     |  179 +++
 .../schema/policy-overlay-v1.yml              |   49 +
 tools/kconfig-audit/schema/policy-v1.yml      |   40 +
 tools/kconfig-audit/schema/rule.yml           |  117 ++
 11 files changed, 2232 insertions(+)
 create mode 100644 Documentation/tools/kconfig-audit.rst
 create mode 100755 tools/kconfig-audit/audit.py
 create mode 100644 tools/kconfig-audit/policy/preempt_rt.yml
 create mode 100644 tools/kconfig-audit/schema/policy-overlay-v1.yml
 create mode 100644 tools/kconfig-audit/schema/policy-v1.yml
 create mode 100644 tools/kconfig-audit/schema/rule.yml

base-commit: fe6ff8d5d675c01793b9f051d16055dd4aa75244
-- 
2.56.0


^ permalink raw reply	[flat|nested] 22+ messages in thread

* [PATCH v2 01/11] kconfig-audit: Add schema for policy files
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  2026-12-03 22:49 ` [PATCH v2 02/11] kconfig-audit: Introduce a PREEMPT_RT configuration policy Ahmed S. Darwish
                   ` (9 subsequent siblings)
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

kconfig-audit validates the passed kernel's .config against a selected
configuration policy.

Define the YAML schema for kconfig-audit policy files, and document the
purpose of each field.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 tools/kconfig-audit/schema/policy-v1.yml | 139 +++++++++++++++++++++++
 1 file changed, 139 insertions(+)
 create mode 100644 tools/kconfig-audit/schema/policy-v1.yml

diff --git a/tools/kconfig-audit/schema/policy-v1.yml b/tools/kconfig-audit/schema/policy-v1.yml
new file mode 100644
index 000000000000..10672226415b
--- /dev/null
+++ b/tools/kconfig-audit/schema/policy-v1.yml
@@ -0,0 +1,139 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+"$schema": "https://json-schema.org/draft-07/schema#"
+
+title: kconfig-audit policy schema
+type: object
+required: [api_version, kind, rules]
+additionalProperties: false
+
+properties:
+  api_version:
+    type: string
+    const: kconfig-audit.kernel.org/v1
+
+  kind:
+    type: string
+    const: Policy
+
+  #
+  # Optional base URL for the documentation page used by rationale
+  # links.  See `docs_hint`.
+  #
+  docs_url:
+    type: string
+    format: uri
+
+  rules:
+    type: array
+    minItems: 1
+    items:
+      type: object
+      oneOf:
+        - required: [name]
+        - required: [name_pattern]
+      allOf:
+        - if:
+            required: [name]
+          then:
+            not:
+              required: [pattern_prio]
+      required: [expected, severity]
+      additionalProperties: false
+
+      properties:
+        #
+        # Exact kernel configuration symbol to check.
+        #
+        # Example: CONFIG_PREEMPT_RT
+        #
+        name:
+          type: string
+          pattern: '^CONFIG_[A-Z0-9_]+$'
+
+        #
+        # Regex matching one or more kernel configuration symbols.
+        #
+        # Example: CONFIG_DEBUG_.*
+        #
+        name_pattern:
+          type: string
+          format: regex
+
+        #
+        # Optional priority for a pattern rule.
+        #
+        # Higher numbers imply a higher priority.  All pattern rules have a
+        # default priority of zero, so specifying a zero here is of no use.
+        #
+        pattern_prio:
+          type: integer
+          minimum: 1
+          maximum: 100
+
+        #
+        # Expected value for the matching kernel configuration option.
+        #
+        # Values:
+        #
+        #   enabled  option is expected to be enabled (built-in or module).
+        #   disabled option is expected to be either absent or unset.
+        #   neutral  option can be enabled or disabled. This is used to exempt
+        #            one or more symbols from a `name_pattern` rule.
+        #
+        expected:
+          type: string
+          enum: [enabled, disabled, neutral]
+
+        #
+        # Issue severity to report when the configuration rule is not met.
+        #
+        # Higher severities should be reserved for rules affecting correctness.
+        #
+        severity:
+          type: string
+          enum: [fatal, high, medium, low, info]
+
+        #
+        # Optional documentation anchor for this rule.
+        #
+        # The rationale URL is built from `docs_url` plus an HTML fragment
+        # identifier.
+        #
+        # If `docs_hint` is set to `config`, then the HTML fragment id is
+        # derived from the kernel configuration symbol name:
+        #
+        #   CONFIG_DRM  ->  #config-drm
+        #
+        # For example, with below docs_url:
+        #
+        #   https://docs.kernel.org/core-api/real-time/kernel-configuration.html
+        #
+        # and the symbol entry:
+        #
+        #   - name: CONFIG_DRM
+        #     expected: disabled
+        #     severity: info
+        #     docs_hint: config
+        #
+        # the rationale URL becomes:
+        #
+        #   https://docs.kernel.org/core-api/real-time/kernel-configuration.html#config-drm
+        #
+        # If `docs_hint` is any other string, that string is used directly as
+        # the HTML fragment identifier.
+        #
+        docs_hint:
+          type: string
+          anyOf:
+            - const: config
+            - pattern: '^\S+$'   # URI fragments cannot have spaces
+
+        #
+        # Optional human-readable explanation for the rule.
+        #
+        # This text should explain why the option is expected to have the given
+        # value, and may span multiple lines.
+        #
+        rationale:
+          type: string
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 02/11] kconfig-audit: Introduce a PREEMPT_RT configuration policy
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
  2026-12-03 22:49 ` [PATCH v2 01/11] kconfig-audit: Add schema for policy files Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  2026-12-03 22:49 ` [PATCH v2 03/11] kconfig-audit: Add the configuration checker code Ahmed S. Darwish
                   ` (8 subsequent siblings)
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Add a kconfig-audit policy for PREEMPT_RT configuration requirements.

Keep it aligned with
Documentation/core-api/real-time/kernel-configuration.rst.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 tools/kconfig-audit/policy/preempt_rt.yml | 179 ++++++++++++++++++++++
 1 file changed, 179 insertions(+)
 create mode 100644 tools/kconfig-audit/policy/preempt_rt.yml

diff --git a/tools/kconfig-audit/policy/preempt_rt.yml b/tools/kconfig-audit/policy/preempt_rt.yml
new file mode 100644
index 000000000000..a9972e3c3453
--- /dev/null
+++ b/tools/kconfig-audit/policy/preempt_rt.yml
@@ -0,0 +1,179 @@
+# PREEMPT_RT .config sanitization
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# List all config options in alphabetic order, per group
+---
+
+api_version: kconfig-audit.kernel.org/v1
+kind: Policy
+
+docs_url: https://docs.kernel.org/core-api/real-time/kernel-configuration.html
+rules:
+  - name: CONFIG_CPU_FREQ
+    expected: enabled
+    severity: high
+    docs_hint: config
+
+  - name: CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE
+    expected: enabled
+    severity: high
+    docs_hint: config
+
+  # Changing the CPU frequency while a real-time task is running is quite
+  # dangerous. Set a high severity to all dynamic scaling governors.
+  - name_pattern: CONFIG_CPU_FREQ_GOV_(CONSERVATIVE|ONDEMAND|SCHEDUTIL)
+    expected: disabled
+    severity: high
+    docs_hint: non-performance-cpu-frequency-governors
+
+  - name_pattern: CONFIG_CPU_FREQ_GOV_(POWERSAVE|USERSPACE)
+    expected: disabled
+    severity: medium
+    docs_hint: non-performance-cpu-frequency-governors
+
+  - name: CONFIG_CPU_IDLE
+    expected: enabled
+    severity: info
+    docs_hint: config
+
+  - name: CONFIG_DRM
+    expected: disabled
+    severity: info
+    docs_hint: config
+
+  - name: CONFIG_EFI_DISABLE_RUNTIME
+    expected: enabled
+    severity: medium
+    docs_hint: config
+
+  - name_pattern: CONFIG_NO_HZ(_FULL|_IDLE)?
+    expected: disabled
+    severity: medium
+    docs_hint: config-no-hz-config-no-hz-full
+
+  - name: CONFIG_PREEMPT_RT
+    expected: enabled
+    severity: fatal
+    docs_hint: config
+
+  - name: CONFIG_RCU_NOCB_CPU
+    expected: enabled
+    severity: low
+    docs_hint: config
+
+  #
+  # Tracing
+  #
+
+  - name: CONFIG_DYNAMIC_FTRACE
+    expected: enabled
+    severity: info
+    docs_hint: config-tracing-and-tracing-options
+
+  - name: CONFIG_FUNCTION_GRAPH_TRACER
+    expected: enabled
+    severity: info
+    docs_hint: config-tracing-and-tracing-options
+
+  - name: CONFIG_HWLAT_TRACER
+    expected: enabled
+    severity: info
+    docs_hint: config-tracing-and-tracing-options
+
+  - name: CONFIG_IRQSOFF_TRACER
+    expected: disabled
+    severity: high
+    docs_hint: config-irqsoff-tracer-and-config-preempt-tracer
+
+  - name: CONFIG_KPROBE_EVENTS
+    expected: enabled
+    severity: info
+    docs_hint: config-tracing-and-tracing-options
+
+  - name: CONFIG_PREEMPT_TRACER
+    expected: disabled
+    severity: high
+    docs_hint: config-irqsoff-tracer-and-config-preempt-tracer
+
+  - name: CONFIG_SCHED_TRACER
+    expected: enabled
+    severity: info
+    docs_hint: config-tracing-and-tracing-options
+
+  - name: CONFIG_TRACING
+    expected: enabled
+    severity: info
+    docs_hint: config-tracing-and-tracing-options
+
+  - name: CONFIG_UPROBE_EVENTS
+    expected: enabled
+    severity: info
+    docs_hint: config-tracing-and-tracing-options
+
+  #
+  # Debug symbols
+  #
+
+  - name_pattern: CONFIG_DEBUG
+    expected: disabled
+    severity: medium
+    docs_hint: kernel-debug-options
+
+  - name_pattern: CONFIG_DEBUG_INFO
+    pattern_prio: 1
+    expected: neutral
+    severity: low
+
+  - name: CONFIG_DEBUG_ATOMIC_SLEEP
+    expected: neutral
+    severity: low
+
+  - name: CONFIG_DEBUG_BOOT_PARAMS
+    expected: neutral
+    severity: low
+
+  - name: CONFIG_DEBUG_BUGVERBOSE
+    expected: neutral
+    severity: low
+
+  - name: CONFIG_DEBUG_FS
+    expected: neutral
+    severity: low
+
+  - name: CONFIG_DEBUG_FS_ALLOW_ALL
+    expected: neutral
+    severity: low
+
+  - name: CONFIG_DEBUG_FS_ALLOW_NONE
+    expected: neutral
+    severity: low
+
+  - name: CONFIG_DEBUG_KERNEL
+    expected: neutral
+    severity: low
+    rationale:
+      A menu option which enables the display of other debug symbols.
+
+  - name: CONFIG_DEBUG_MISC
+    expected: neutral
+    severity: low
+
+  #
+  # Debugging features
+  #
+
+  - name: CONFIG_LOCKUP_DETECTOR
+    expected: disabled
+    severity: high
+    docs_hint: config
+
+  - name: CONFIG_PROVE_LOCKING
+    expected: disabled
+    severity: high
+    docs_hint: config
+
+  - name_pattern: CONFIG_SLUB_DEBUG.*
+    expected: disabled
+    severity: high
+    docs_hint: kernel-debug-options
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 03/11] kconfig-audit: Add the configuration checker code
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
  2026-12-03 22:49 ` [PATCH v2 01/11] kconfig-audit: Add schema for policy files Ahmed S. Darwish
  2026-12-03 22:49 ` [PATCH v2 02/11] kconfig-audit: Introduce a PREEMPT_RT configuration policy Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  2026-12-03 22:49 ` [PATCH v2 04/11] Documentation: Describe kconfig-audit usage and design Ahmed S. Darwish
                   ` (7 subsequent siblings)
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Introduce the kconfig-audit tool to validate a kernel .config against a
YAML policy and report violations by severity.

For correctness, readability, and long-term maintainability, type-annotate
all the Python code and split the tool's logic into a clean set of classes.

Build a proper data model for policies and .config symbols.  Implement all
configuration checking logic in terms of that model, and never on the YAML
files dictionaries.

Clearly document the tool's development rules on top.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 tools/kconfig-audit/audit.py | 908 +++++++++++++++++++++++++++++++++++
 1 file changed, 908 insertions(+)
 create mode 100755 tools/kconfig-audit/audit.py

diff --git a/tools/kconfig-audit/audit.py b/tools/kconfig-audit/audit.py
new file mode 100755
index 000000000000..6ff4a56281ad
--- /dev/null
+++ b/tools/kconfig-audit/audit.py
@@ -0,0 +1,908 @@
+#!/usr/bin/env python3
+#
+# SPDX-License-Identifier: GPL-2.0-only
+#
+# Kernel .config audit
+#
+# Main usage:
+#
+#     $ audit.py list-policies
+#     $ audit.py list-api-versions
+#
+#     $ audit.py check -c path/to/.config -p preempt_rt
+#
+# Development rules:
+#
+# - Full type-annotations are required.  Verify type-safety using:
+#
+#     $ mypy --strict --no-warn-return-any audit.py
+#
+# - The minimum required Python version must not be newer than what is
+#   required by the kernel build at Documentation/process/changes.rst.
+#
+# - The tool must not depend on being run inside the kernel source tree.
+#   This simplifies invocation, testing and possible future packaging.
+#
+# - Keep the parsing code and the internal data model separate:
+#
+#       KernelConfig      # internal model, typed .config symbols repo
+#       KernelConfigFile  # parser
+#
+#       Policy            # internal model, typed policy rules repo
+#       PolicyFile        # parser
+#
+#       Schema            # internal model, dictionary-like
+#       SchemaFile        # parser
+#
+# - The YAML policy files are only treated as a serialization format.
+#   After loading and schema validation, such rules are parsed into the
+#   internal data model: Severity, Rule, SymbolRule, PatternRule, Policy,
+#   and other Python objects.
+#
+#   The .config check logic must operate on that typed Python model, and
+#   _never_ on the raw YAML dictionaries.
+#
+# - Schema versioning must be handled only during parsing.  Keep the
+#   internal data model free from any version tags.  Keep the .config
+#   checker logic free from any schema versioning conditionals.
+#
+# - During parsing, never re-validate what has already been validated by
+#   the schema.  It is redundant and makes the parser unnecessarily ugly.
+#
+# - Open all policy files with a UTF-8 encoding, so that users can include
+#   non-ASCII characters in a policy rule's rationale.
+#
+# - Minimize external dependencies, as this tool is also intended to be run
+#   from distributions kernel packaging scripts in the future.
+#
+# - Code simplicity and clarity is favored over random policy features.
+#   Before submitting new features, please prove beforehand that they are
+#   required by a mainline real-world use case; e.g. a new mainline policy.
+#
+# Script Exit Codes:
+#
+#   os.EX_CONFIG          passed kernel .config does not match policy
+#   os.EX_NOINPUT         input file(s) could not be opened
+#   os.EX_DATAERR         YAML/schema/rule data is malformed
+#   os.EX_UNAVAILABLE     Python version or dependency is unavailable
+#
+
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import sys
+import textwrap
+
+from dataclasses import dataclass, field
+from enum import Enum, auto
+from pathlib import Path
+from typing import Any, ClassVar, Final, Mapping, NoReturn, Optional
+
+#
+# Initial sanity checks:
+#
+
+def warn(message: str) -> None:
+    print(message, file=sys.stderr)
+
+def error(message: str, code: int) -> NoReturn:
+    print(f'Error: {message}', file=sys.stderr)
+    sys.exit(code)
+
+if sys.version_info < (3, 9):
+    error('Python 3.9 or later is required', os.EX_UNAVAILABLE)
+
+try:
+    import jsonschema               # type: ignore
+    import yaml as yaml_m           # type: ignore
+except ModuleNotFoundError as e:
+    error(f'Missing Python module: {e.name}', os.EX_UNAVAILABLE)
+
+#
+# Kernel .config model:
+#
+
+@dataclass(eq=False)
+class Symbol():
+    """Kernel .config symbol"""
+    name: str
+
+@dataclass(eq=False)
+class BooleanSymbol(Symbol):
+    """Kconfig 'tristate' symbol, where value=True implies 'y' or 'm'"""
+    value: bool
+
+@dataclass(eq=False)
+class IntSymbol(Symbol):
+    """Kconfig int symbol"""
+    value: int
+
+@dataclass(eq=False)
+class HexSymbol(Symbol):
+    """Kconfig hex symbol"""
+    value: int
+
+@dataclass(eq=False)
+class StringSymbol(Symbol):
+    """Kconfig string symbol"""
+    value: str
+
+@dataclass
+class KernelConfig:
+    """Internal repository for parsed kconfig symbols"""
+    symbols: dict[str, Symbol] = field(default_factory=dict)
+
+    def add_symbol(self, symbol: Symbol) -> None:
+        if symbol.name in self.symbols:
+            error(f'.config defines {symbol.name} more than once', os.EX_DATAERR)
+
+        self.symbols[symbol.name] = symbol
+
+    def add_bool_symbol(self, name: str, val: bool) -> None:
+        self.add_symbol(BooleanSymbol(name, val))
+
+    def add_str_symbol(self, name: str, val: str) -> None:
+        self.add_symbol(StringSymbol(name, val))
+
+    def add_int_symbol(self, name: str, val: int) -> None:
+        self.add_symbol(IntSymbol(name, val))
+
+    def add_hex_symbol(self, name: str, val: int) -> None:
+        self.add_symbol(HexSymbol(name, val))
+
+    def get_symbol(self, sym_name: str) -> Optional[Symbol]:
+        return self.symbols.get(sym_name)
+
+    def get_matching_symbols(self, pa: re.Pattern[str]) -> list[Symbol]:
+        """Get all symbols whose names match the passed regex"""
+        return [sym for sym in self.symbols.values() if pa.search(sym.name)]
+
+class KernelConfigFile:
+    """Kernel .config file parser (to a KernelConfig model)"""
+
+    def __init__(self, file: Path):
+        try:
+            self.lines = file.read_text(encoding='utf-8').splitlines()
+        except OSError as e:
+            error(f'Could not open {file}: {e.strerror}', os.EX_NOINPUT)
+        except UnicodeError as e:
+            error(f'Invalid UTF-8 in {file}: {e}', os.EX_DATAERR)
+
+    def parse(self) -> KernelConfig:
+        """Parse .config file into a repository of Symbol objects"""
+        config = KernelConfig()
+
+        symbol_unset = re.compile(r'^# (CONFIG_[A-Za-z0-9_]+) is not set$')
+        symbol_assign = re.compile(r'^(CONFIG_[A-Za-z0-9_]+)=(.*)$')
+
+        comment = re.compile('^#')
+        empty_line = re.compile('^$')
+
+        for line in self.lines:
+            if m := symbol_unset.match(line):
+                config.add_bool_symbol(m.group(1), False)
+                continue
+
+            if not (m := symbol_assign.match(line)):
+                if not comment.match(line) and not empty_line.match(line):
+                    error(f'Invalid .config line: {line}', os.EX_DATAERR)
+                continue
+
+            name, val = m.group(1), m.group(2)
+
+            if val in ('y', 'm'):
+                config.add_bool_symbol(name, True)
+            elif re.fullmatch(r'0[xX][0-9a-fA-F]+', val):
+                config.add_hex_symbol(name, int(val, 16))
+            elif re.fullmatch(r'-?[0-9]+', val):
+                config.add_int_symbol(name, int(val))
+            elif len(val) >= 2 and val[0] == '"' and val[-1] == '"':
+                config.add_str_symbol(name, val[1:-1])
+            else:
+                error(f'Invalid .config assignment: {line}', os.EX_DATAERR)
+
+        return config
+
+#
+# Shared code for YAML files access:
+#
+
+YamlDict = dict[str, Any]
+
+class Helpers:
+
+    @staticmethod
+    def load_yaml(yaml_f: Path) -> YamlDict:
+        """
+        Load a YAML file and return its top-level mapping.
+
+        If the file cannot be opened, contains invalid UTF-8, contains invalid
+        YAML syntax, or does not contain a top-level mapping, report the error
+        and exit the script.
+        """
+        try:
+            with open(yaml_f, 'r', encoding='utf-8') as f:
+                yaml = yaml_m.safe_load(f)
+        except OSError as e:
+            error(f'Could not open {yaml_f}: {e.strerror}', os.EX_NOINPUT)
+        except UnicodeError as e:
+            error(f'Invalid UTF-8 in {yaml_f}: {e}', os.EX_DATAERR)
+        except yaml_m.YAMLError as e:
+            error(f'Invalid YAML syntax at {yaml_f}:\n {e}', os.EX_DATAERR)
+
+        if not isinstance(yaml, dict):
+            error(
+                f'{yaml_f.name} must contain a YAML mapping at the top level',
+                os.EX_DATAERR,
+            )
+
+        return yaml
+
+    @staticmethod
+    def validate_yaml(yaml: YamlDict, schema: Schema, f_name: str) -> None:
+        """Validate a parsed YAML mapping against passed JSON Schema"""
+        try:
+            # For regex validation, manually enforce a format checker
+            jsonschema.validate(
+                yaml,
+                schema,
+                format_checker=jsonschema.FormatChecker(),
+            )
+        except jsonschema.exceptions.ValidationError as e:
+            error(
+                f'{f_name} does not match its schema\n'
+                f'Reason: {e.message}',
+                os.EX_DATAERR
+            )
+
+    @staticmethod
+    def unreachable(message: str) -> NoReturn:
+        """For type checkers and readers, mark an unreachable code path"""
+        raise AssertionError(f'unreachable: {message}')
+
+class VersionedYamlFile:
+    """YAML file whose api_version field selects its validation schema"""
+
+    # Version tags for the entirety of kconfig-audit YAML files
+    AUDIT_API_V1: Final = 'kconfig-audit.kernel.org/v1'
+
+    # Map kconfig-audit version tags to YAML schema file names. To be
+    # filled by children classes.
+    SCHEMAS: ClassVar[Mapping[str, str]] = {}
+
+    yaml: YamlDict
+
+    def __init__(self, yaml_f: Path, schema_dir: Path):
+        """Open YAML file and load its validated dictionary mappings"""
+        self.yaml_f = yaml_f
+        self.yaml = Helpers.load_yaml(yaml_f)
+        self._validate_yaml(schema_dir)
+
+    def _validate_yaml(self, schema_dir: Path) -> None:
+        """Validate this YAML file against its selected schema"""
+        api_version = self._read_api_version()
+        schema_f = schema_dir / self.SCHEMAS[api_version]
+
+        schema = SchemaFile(schema_f).parse()
+        Helpers.validate_yaml(self.yaml, schema, self.yaml_f.name)
+
+    def _read_api_version(self) -> str:
+        """Read and validate api_version to select the YAML schema"""
+        api_version = self.yaml.get('api_version')
+
+        if not api_version:
+            error(
+                f'{self.yaml_f.name}: missing api_version field',
+                os.EX_DATAERR,
+            )
+        if not isinstance(api_version, str):
+            error(
+                f'{self.yaml_f.name}: api_version must be a string',
+                os.EX_DATAERR,
+            )
+
+        if api_version in self.SCHEMAS:
+            return api_version
+
+        versions = '\n\t'.join(self.SCHEMAS)
+        warn(f'Supported API versions:\n\t{versions}\n')
+        error(
+            f'{self.yaml_f.name}: Unknown API version: {api_version}',
+            os.EX_DATAERR,
+        )
+
+#
+# Schema model:
+#
+
+class Schema(YamlDict):
+    """Modeled policy schema, as a YAML dictionary mapping"""
+
+class SchemaFile:
+    """json-schema.org policy schema parser (to Schema model)"""
+
+    def __init__(self, schema_f: Path):
+        self.schema_f = schema_f
+        self.yaml = Helpers.load_yaml(schema_f)
+
+    def parse(self) -> Schema:
+        """Parse and validate a policy schema file"""
+
+        schema = Schema(self.yaml)
+
+        # Validate the schema against its own draft-07 grammar
+        try:
+            jsonschema.Draft7Validator.check_schema(schema)
+        except jsonschema.exceptions.SchemaError as e:
+            error(
+                f'Invalid schema {self.schema_f}:\nReason: {e.message}',
+                os.EX_DATAERR,
+            )
+
+        return schema
+
+#
+# Policy model:
+#
+
+class ExpectedValue(Enum):
+    """Expected values for a .config symbol"""
+
+    enabled  = auto()   # Implies both a built-in or a module, as in schema
+    disabled = auto()
+    neutral  = auto()
+
+class Severity(Enum):
+    """Rule-check severity"""
+
+    fatal  = auto()
+    high   = auto()
+    medium = auto()
+    low    = auto()
+    info   = auto()
+
+@dataclass
+class Rule:
+    """Single rule entry"""
+
+    expected: ExpectedValue
+    severity: Severity
+    rationale: Optional[str]
+    docs_hint: Optional[str]
+
+    def __post_init__(self) -> None:
+        self._normalize_docs_hint()
+
+    def _normalize_docs_hint(self) -> None:
+        """Transform the hint to a URI fragment identifier"""
+        if self.docs_hint:
+            self.docs_hint = '#' + self.docs_hint
+
+@dataclass
+class SymbolRule(Rule):
+    """Rule entry for one .config symbol"""
+
+    symbol: str
+
+    def _normalize_docs_hint(self) -> None:
+        """Transform the hint to a docs.kernel.org URI fragment identifier"""
+        if self.docs_hint == 'config':
+            self.docs_hint = self.symbol.lower().replace('_', '-')
+
+        super()._normalize_docs_hint()
+
+@dataclass
+class PatternRule(Rule):
+    """Rule entry for a regex pattern of .config symbols"""
+
+    regex: re.Pattern[str]
+    pattern_prio: int = 0
+
+@dataclass
+class Policy:
+    """The .config checker policy rules repository / data model"""
+
+    rules: list[Rule] = field(default_factory=list)
+    docs_url: Optional[str] = None
+
+    def add_rule(self, rule: Rule) -> None:
+        """Add given rule to the existing rules repository"""
+        if isinstance(rule, SymbolRule):
+            symbol = rule.symbol
+            if self.get_symbol_rule(symbol):
+                error(f'Duplicate rule name: {symbol}', os.EX_DATAERR)
+
+        if isinstance(rule, PatternRule):
+            pattern = rule.regex.pattern
+            if self.get_pattern_rule(pattern):
+                error(f'Duplicate rule pattern: {pattern}', os.EX_DATAERR)
+
+        self.rules.append(rule)
+
+    def get_docs_url_for(self, rule: Rule) -> Optional[str]:
+        """Return full documentation URL for a rule, if available"""
+        if not self.docs_url or not rule.docs_hint:
+            return None
+
+        return f'{self.docs_url}{rule.docs_hint}'
+
+    def get_symbol_rule(self, kconfig_symbol: str) -> Optional[SymbolRule]:
+        """Return symbol rule matching passed .config symbol, if any"""
+        for rule in self.rules:
+            if isinstance(rule, SymbolRule):
+                if rule.symbol == kconfig_symbol:
+                    return rule
+        return None
+
+    def get_pattern_rule(self, pattern: str) -> Optional[PatternRule]:
+        """Return pattern rule matching passed name pattern, if any"""
+        for rule in self.rules:
+            if isinstance(rule, PatternRule):
+                if rule.regex.pattern == pattern:
+                    return rule
+        return None
+
+    def get_symbol_rule_matching(self, pattern: re.Pattern[str]) -> list[SymbolRule]:
+        """Get all symbol rules matching passed regex"""
+        rules = []
+        for rule in self.rules:
+            if isinstance(rule, SymbolRule):
+                if pattern.search(rule.symbol):
+                    rules.append(rule)
+        return rules
+
+    def get_pattern_rules_for(self, kconfig_symbol: str) -> list[PatternRule]:
+        """Get all pattern rules with a regex matching passed .config symbol"""
+        rules = []
+        for rule in self.rules:
+            if isinstance(rule, PatternRule):
+                if rule.regex.search(kconfig_symbol):
+                    rules.append(rule)
+        return rules
+
+class PolicyFile(VersionedYamlFile):
+    """Policy file parser (to a Policy model)"""
+
+    SCHEMAS: ClassVar[Mapping[str, str]] = {
+        VersionedYamlFile.AUDIT_API_V1: 'policy-v1.yml',
+    }
+
+    def parse(self) -> Policy:
+        """Parse the YAML policy file into a python Policy object"""
+        policy = Policy()
+
+        for rule_mapping in self.yaml.get('rules', []):
+            rule = self._parse_rule(rule_mapping)
+            policy.add_rule(rule)
+
+        policy.docs_url = self.yaml.get('docs_url')
+        return policy
+
+    def _parse_rule(self, rule: YamlDict) -> Rule:
+        """Parse one policy YAML rule into a polymorphic Rule object"""
+        expected = ExpectedValue[rule['expected']]
+        severity = Severity[rule['severity']]
+        rationale = rule.get('rationale')
+        docs_hint = rule.get('docs_hint')
+
+        if 'name' in rule:
+            return SymbolRule(
+                expected,
+                severity,
+                rationale,
+                docs_hint,
+                symbol=rule['name'],
+            )
+
+        if 'name_pattern' in rule:
+            return PatternRule(
+                expected,
+                severity,
+                rationale,
+                docs_hint,
+                regex=re.compile(rule['name_pattern']),
+                pattern_prio=rule.get('pattern_prio', 0),
+            )
+
+        # Schema should guard against this
+        Helpers.unreachable('YAML rule entry without `name` or `name_pattern`')
+
+#
+# Error reporting model:
+#
+
+@dataclass
+class Issue:
+    message: str
+    docs_url: Optional[str]
+    severity: Severity
+    rationale: Optional[str]
+
+@dataclass
+class SymbolIssue(Issue):
+    """Checker issue concerning a single .config symbol"""
+    symbol: str
+
+@dataclass
+class PatternIssue(Issue):
+    """Checker issue concerning a regex pattern of .config symbols"""
+    symbols: list[str]
+
+@dataclass
+class RegexIssue(Issue):
+    """Checker issue concerning a regex pattern that has no matches"""
+    regex: re.Pattern[str]
+
+class Issues:
+    """Repository of all issues found by the checker"""
+
+    def __init__(self, all_issues: list[Issue]):
+        # Index all issues by severity
+        self.issues: dict[Severity, list[Issue]] = {
+            severity: [] for severity in Severity
+        }
+        for issue in all_issues:
+            self.issues[issue.severity].append(issue)
+
+    def by_severity(self, severity: Severity) -> list[Issue]:
+        return self.issues[severity]
+
+@dataclass
+class Report:
+    """kconfig checker sanity report. Main script output"""
+
+    issues: Issues
+
+    def _print_header(self, header: str) -> None:
+        print(header)
+        print('=' * len(header))
+        print()
+
+    def _print_symbol(self, issue: SymbolIssue) -> None:
+        print(f'* {issue.symbol} {issue.message}')
+        print()
+
+    def _print_pattern(self, issue: PatternIssue) -> None:
+        print(f'* Below options {issue.message}:\n')
+        for symbol in issue.symbols:
+            print(f'  {symbol}')
+        print()
+
+    def _print_regex(self, issue: RegexIssue) -> None:
+        print(f'* Regular expression "{issue.regex.pattern}" {issue.message}')
+        print()
+
+    def _print_issue(self, issue: Issue) -> None:
+        if isinstance(issue, SymbolIssue):
+            self._print_symbol(issue)
+        elif isinstance(issue, PatternIssue):
+            self._print_pattern(issue)
+        elif isinstance(issue, RegexIssue):
+            self._print_regex(issue)
+        else:
+            raise TypeError(f'Unsupported issue type: {type(issue).__name__}')
+
+    def _print_rationale(self, issue: Issue) -> None:
+        if not issue.docs_url and not issue.rationale:
+            return
+
+        print('  Rationale:')
+
+        if issue.docs_url:
+            print(' ', issue.docs_url)
+            if issue.rationale:
+                print()
+
+        if issue.rationale:
+            print(textwrap.fill(
+                issue.rationale,
+                width=75,
+                initial_indent='  ',
+                subsequent_indent='  ',
+            ))
+
+        print()
+
+    def print(self) -> None:
+        """Print the checker's .config report, in order of severity"""
+        print()
+        for severity in Severity:
+            issues = self.issues.by_severity(severity)
+            if not issues:
+                continue
+
+            self._print_header('Configuration Issues with severity = ' +
+                               severity.name.upper())
+
+            for issue in issues:
+                self._print_issue(issue)
+                self._print_rationale(issue)
+
+#
+# Configuration checking machinery:
+#
+
+PatternRuleMap = Mapping[Symbol, PatternRule]
+
+@dataclass
+class Checker:
+    """Check a parsed kernel .config against a parsed policy"""
+
+    kconfig: KernelConfig
+    policy: Policy
+
+    def __post_init__(self) -> None:
+        self.pattern_rules_map = self._map_pattern_rules()
+
+    def make_report(self) -> Optional[Report]:
+        """Return a report if the policy produced any issues"""
+        if not (issues := self.find_issues()):
+            return None
+
+        return Report(Issues(issues))
+
+    def find_issues(self) -> list[Issue]:
+        """Check .config against all policy rules and return any issues"""
+        issues: list[Issue] = []
+
+        for rule in self.policy.rules:
+            issues.extend(self._find_rule_issues(rule))
+
+        return issues
+
+    def _map_pattern_rules(self) -> PatternRuleMap:
+        """Map each .config symbol to highest-priority matching pattern rule, if any"""
+        pattern_map: dict[Symbol, PatternRule] = {}
+
+        for symbol in self.kconfig.symbols.values():
+
+            # No matching pattern rules for symbol
+            rules = self.policy.get_pattern_rules_for(symbol.name)
+            if not rules:
+                continue
+
+            highest_prio = max(rule.pattern_prio for rule in rules)
+            highest_prio_rules = [
+                rule for rule in rules if rule.pattern_prio == highest_prio
+            ]
+
+            if len(highest_prio_rules) > 1:
+                patterns = '\n\t'.join(
+                    rule.regex.pattern for rule in highest_prio_rules
+                )
+                error(
+                    f'{symbol.name} is covered by multiple pattern rules with '
+                    f'priority {highest_prio}:\n\t{patterns}',
+                    os.EX_DATAERR,
+                )
+
+            pattern_map[symbol] = highest_prio_rules[0]
+
+        return pattern_map
+
+    def _find_rule_issues(self, rule: Rule) -> list[Issue]:
+        """Check .config against single passed rule and return any issues"""
+        if rule.expected is ExpectedValue.neutral:
+            return []
+
+        if isinstance(rule, SymbolRule):
+            return self._find_symbol_rule_issues(rule)
+
+        if isinstance(rule, PatternRule):
+            return self._find_pattern_rule_issues(rule)
+
+        raise TypeError(f'Unsupported rule type: {type(rule).__name__}')
+
+    def _find_symbol_rule_issues(self, rule: SymbolRule) -> list[Issue]:
+        """Check .config against a symbol rule and return any issues"""
+
+        symbol = self.kconfig.get_symbol(rule.symbol)
+
+        if symbol is None:
+            if rule.expected is ExpectedValue.enabled:
+                return [self._make_symbol_issue(rule, 'is not in .config')]
+
+            return []
+
+        if not isinstance(symbol, BooleanSymbol):
+            msg = 'has the wrong type, expected boolean'
+            return [self._make_symbol_issue(rule, msg)]
+
+        if Checker._expected_enabled(rule) != symbol.value:
+            msg = 'is ' + self._wrong_symbol_state_message(rule)
+            return [self._make_symbol_issue(rule, msg)]
+
+        return []
+
+    def _find_pattern_rule_issues(self, rule: PatternRule) -> list[Issue]:
+        """Check .config against a pattern rule and return any issues"""
+        wrong_type_symbols: list[str] = []
+        wrong_value_symbols: list[str] = []
+
+        matched_symbols = False
+
+        for symbol in self.kconfig.get_matching_symbols(rule.regex):
+            # Record the regex symbol match before applying overrides
+            matched_symbols = True
+
+            # An exact rule for symbol overrides all pattern rules
+            if self.policy.get_symbol_rule(symbol.name):
+                continue
+
+            # Higher-priority patterns overrides us
+            if self.pattern_rules_map.get(symbol) is not rule:
+                continue
+
+            if not isinstance(symbol, BooleanSymbol):
+                wrong_type_symbols.append(symbol.name)
+                continue
+
+            if Checker._expected_enabled(rule) != symbol.value:
+                wrong_value_symbols.append(symbol.name)
+                continue
+
+        issues: list[Issue] = []
+
+        if Checker._expected_enabled(rule) and not matched_symbols:
+            if not self.policy.get_symbol_rule_matching(rule.regex):
+                msg = 'does not match any enabled kconfig symbol'
+                issues.append(self._make_regex_issue(rule, msg))
+
+        if wrong_type_symbols:
+            issues.append(self._make_pattern_issue(
+                rule,
+                'have the wrong types, expected boolean',
+                wrong_type_symbols,
+            ))
+
+        if wrong_value_symbols:
+            issues.append(self._make_pattern_issue(
+                rule,
+                'are ' + self._wrong_symbol_state_message(rule),
+                wrong_value_symbols,
+            ))
+
+        return issues
+
+    @staticmethod
+    def _expected_enabled(rule: Rule) -> bool:
+        if rule.expected is ExpectedValue.enabled:
+            return True
+
+        if rule.expected is ExpectedValue.disabled:
+            return False
+
+        raise ValueError('Neutral rule has no boolean representation')
+
+    @staticmethod
+    def _wrong_symbol_state_message(rule: Rule) -> str:
+        if Checker._expected_enabled(rule):
+            return 'disabled'
+
+        return 'enabled'
+
+    def _make_symbol_issue(self, rule: SymbolRule, err_message: str) -> SymbolIssue:
+        return SymbolIssue(
+            err_message,
+            self.policy.get_docs_url_for(rule),
+            rule.severity,
+            rule.rationale,
+            rule.symbol,
+        )
+
+    def _make_pattern_issue(self, rule: PatternRule, err_message: str, symbols: list[str]) -> PatternIssue:
+        return PatternIssue(
+            err_message,
+            self.policy.get_docs_url_for(rule),
+            rule.severity,
+            rule.rationale,
+            symbols,
+        )
+
+    def _make_regex_issue(self, rule: PatternRule, message: str) -> RegexIssue:
+        return RegexIssue(
+            message,
+            self.policy.get_docs_url_for(rule),
+            rule.severity,
+            rule.rationale,
+            rule.regex,
+        )
+
+#
+# Argument parsing and main code:
+#
+
+def parse_args(policies: list[str]) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        prog='audit.py',
+        description='Kernel .config options checker',
+    )
+
+    subparsers = parser.add_subparsers(
+        dest='command',
+        required=True,
+    )
+
+    subparsers.add_parser(
+        'list-policies',
+        help='return available .config rule checking profiles',
+    )
+
+    subparsers.add_parser(
+        'list-api-versions',
+        help='return supported policy API versions',
+    )
+
+    check_parser = subparsers.add_parser(
+        'check',
+        help='check a .config file against a rule profile',
+    )
+
+    check_parser.add_argument(
+        '-c',
+        '--config',
+        metavar='KCONFIG_FILE',
+        type=Path,
+        required=True,
+        help='.config file to be checked',
+    )
+
+    policy_group = check_parser.add_mutually_exclusive_group(required=True)
+
+    policy_group.add_argument(
+        '-p',
+        '--policy',
+        metavar='POLICY',
+        choices=policies,
+        help='registered policy name to check against',
+    )
+
+    policy_group.add_argument(
+        '-P',
+        '--policy-file',
+        metavar='POLICY_FILE',
+        type=Path,
+        help='policy file to check against',
+    )
+
+    return parser.parse_args()
+
+def main() -> None:
+    base_dir = Path(__file__).resolve().parent
+    policy_dir = base_dir / 'policy'
+    schema_dir = base_dir / 'schema'
+
+    policies = sorted(path.stem for path in policy_dir.glob('*.yml'))
+    args = parse_args(policies)
+
+    if args.command == 'list-policies':
+        print(*policies, sep='\n')
+        return
+
+    if args.command == 'list-api-versions':
+        versions = sorted(PolicyFile.SCHEMAS)
+        print(*versions, sep='\n')
+        return
+
+    kconfig_f = args.config.resolve()
+    kconfig = KernelConfigFile(kconfig_f).parse()
+
+    if args.policy_file:
+        policy_f = args.policy_file
+    else:
+        policy_f = policy_dir / f'{args.policy}.yml'
+    policy = PolicyFile(policy_f, schema_dir).parse()
+
+    checker = Checker(kconfig, policy)
+    report = checker.make_report()
+
+    if report:
+        report.print()
+        error(f'{kconfig_f} does not match required policy', os.EX_CONFIG)
+
+    print(f'Success: {kconfig_f} matches required policy')
+
+if __name__ == '__main__':
+    main()
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 04/11] Documentation: Describe kconfig-audit usage and design
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
                   ` (2 preceding siblings ...)
  2026-12-03 22:49 ` [PATCH v2 03/11] kconfig-audit: Add the configuration checker code Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  2026-12-03 22:49 ` [PATCH v2 05/11] kconfig-audit: Split policy schema for component reuse Ahmed S. Darwish
                   ` (6 subsequent siblings)
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Document kconfig-audit usage, policy format, design, and dependencies.

For PREEMPT_RT users, mention that kconfig-audit can now be used for
validating a kernel's .config against PREEMPT_RT requirements.

For the kconfig-audit external dependencies error handling code, reference
the newly added documentation as well.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 .../real-time/kernel-configuration.rst        |   3 +
 Documentation/tools/index.rst                 |   1 +
 Documentation/tools/kconfig-audit.rst         | 517 ++++++++++++++++++
 tools/kconfig-audit/audit.py                  |   7 +-
 4 files changed, 527 insertions(+), 1 deletion(-)
 create mode 100644 Documentation/tools/kconfig-audit.rst

diff --git a/Documentation/core-api/real-time/kernel-configuration.rst b/Documentation/core-api/real-time/kernel-configuration.rst
index d7f08e7b8760..7ae61d171a75 100644
--- a/Documentation/core-api/real-time/kernel-configuration.rst
+++ b/Documentation/core-api/real-time/kernel-configuration.rst
@@ -14,6 +14,9 @@ Introduction
 This document lists the kernel configuration options that might affect a
 real-time kernel's worst-case latency.  It is intended for system integrators.
 
+You can validate your kernel's ``.config`` against the guidelines below using
+the ``kconfig-audit`` tool.  See Documentation/tools/kconfig-audit.rst
+
 Configuration options
 =====================
 
diff --git a/Documentation/tools/index.rst b/Documentation/tools/index.rst
index 1adf4a6f909b..ee87e3599931 100644
--- a/Documentation/tools/index.rst
+++ b/Documentation/tools/index.rst
@@ -10,6 +10,7 @@ more additions are needed here:
 .. toctree::
    :maxdepth: 1
 
+   kconfig-audit
    rtla/index
    rv/index
    python
diff --git a/Documentation/tools/kconfig-audit.rst b/Documentation/tools/kconfig-audit.rst
new file mode 100644
index 000000000000..5b8e2fa842b1
--- /dev/null
+++ b/Documentation/tools/kconfig-audit.rst
@@ -0,0 +1,517 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+============================
+Kernel configuration checker
+============================
+
+``kconfig-audit`` is a Python tool for checking a kernel ``.config`` file
+against a set of policy rules; e.g. PREEMPT_RT kernel configuration
+requirements.  It generates a sanity report showing whether the supplied
+kernel configuration satisfies a known profile.
+
+.. contents:: Table of Contents
+   :depth: 2
+   :local:
+
+Invocation
+==========
+
+The checker can be invoked from anywhere in the file system::
+
+   audit.py list-policies
+
+   audit.py list-api-versions
+
+Check a ``.config`` against a policy known to the checker::
+
+   audit.py check -c path/to/.config -p preempt_rt
+
+Example invocation from within the kernel tree:
+
+.. code-block:: shell
+
+   ~/linux$ make defconfig
+   ~/linux$ tools/kconfig-audit/audit.py check -c .config -p preempt_rt
+
+External dependencies
+=====================
+
+The checker requires the ``PyYAML`` and ``jsonschema`` Python modules.
+Install them using your distribution's package manager, for example:
+
+.. table::
+   :align: left
+
+   ============ ================== ======================
+   Distribution PyYAML             jsonschema
+   ============ ================== ======================
+   Debian       ``python3-yaml``   ``python3-jsonschema``
+   Red Hat      ``python3-pyyaml`` ``python3-jsonschema``
+   Arch Linux   ``python-yaml``    ``python-jsonschema``
+   ============ ================== ======================
+
+Report format
+=============
+
+When the configuration does not match the policy, the checker prints a
+report grouped by severity.
+
+A typical report looks like::
+
+   Configuration Issues with severity = FATAL
+   ==========================================
+
+   * CONFIG_PREEMPT_RT is not in .config
+
+     Rationale:
+     https://docs.kernel.org/core-api/real-time/kernel-configuration.html#config-preempt-rt
+
+   Configuration Issues with severity = MEDIUM
+   ===========================================
+
+   * CONFIG_EFI_DISABLE_RUNTIME is disabled
+
+     Rationale:
+     https://docs.kernel.org/core-api/real-time/kernel-configuration.html#config-efi-disable-runtime
+
+After printing the report, the checker exits with an error code.
+
+Exit codes
+==========
+
+When checking a ``.config`` file against a policy, kconfig-audit uses the
+following exit codes:
+
+.. table::
+   :align: left
+
+   =================== ====== =====================================================
+   Exit code           Value  Meaning
+   =================== ====== =====================================================
+   Success               0    The ``.config`` file matches selected policy.
+   ``EX_CONFIG``         78   The ``.config`` file does not match selected policy.
+   ``EX_NOINPUT``        66   One or more input files could not be opened.
+   ``EX_DATAERR``        65   The ``.config``, the selected policy, or the tool's
+                              internal schema is malformed or invalid.
+   ``EX_UNAVAILABLE``    69   Python 3.9 or later, or a required Python module, is
+                              unavailable.
+   Usage error           2    The command-line arguments are invalid.
+   =================== ====== =====================================================
+
+Policy file format
+==================
+
+Configuration policy files are YAML documents. A minimal policy looks like
+this:
+
+.. code-block:: yaml
+
+   api_version: kconfig-audit.kernel.org/v1
+   kind: Policy
+
+   rules:
+     - name: CONFIG_PREEMPT_RT
+       expected: enabled
+       severity: fatal
+
+The supplied PREEMPT_RT policy resides in the kernel source tree at::
+
+   tools/kconfig-audit/policy/preempt_rt.yml
+
+For field-by-field descriptions of the policy's top-level and rule fields,
+see :ref:`Policy file reference <policy-file-reference>`.
+
+Rule matching
+=============
+
+Exact symbol rules
+------------------
+
+An exact symbol rule checks only the named symbol.  For example:
+
+.. code-block:: yaml
+
+   rules:
+     - name: CONFIG_EXT4_FS
+       expected: enabled
+       severity: high
+
+passes the checked ``.config`` if it contains either::
+
+   CONFIG_EXT4_FS=y
+
+or::
+
+   CONFIG_EXT4_FS=m
+
+It fails the checked ``.config`` if it has::
+
+   # CONFIG_EXT4_FS is not set
+
+or if such a symbol is absent from ``.config``.
+
+Pattern rules
+-------------
+
+A pattern rule ensures that all symbols in the checked ``.config`` matching
+its regular expression pattern satisfies expectations.
+
+For example, for below policy:
+
+.. code-block:: yaml
+
+   rules:
+     - name_pattern: CONFIG_SLUB_DEBUG.*
+       expected: enabled
+       severity: high
+
+if the checked ``.config`` has below symbols::
+
+   CONFIG_SLUB_DEBUG
+   CONFIG_SLUB_DEBUG_ON
+
+then, they're expected to be enabled.
+
+Rule precedence
+===============
+
+Rule order in the YAML file **does not** define precedence.  Moving a rule
+earlier or later in the file does not change the meaning of the policy.
+
+Exact rules take precedence over pattern rules
+----------------------------------------------
+
+For example, for below policy:
+
+.. code-block:: yaml
+
+   rules:
+     - name_pattern: CONFIG_USB
+       expected: disabled
+       severity: high
+
+     - name: CONFIG_USB_GADGET
+       expected: disabled
+       severity: low
+
+if the checked ``.config`` has ``CONFIG_USB_GADGET`` enabled, the only the
+policy's exact rule will trigger an issue, *at low severity*.
+
+Similarly, for the policy:
+
+.. code-block:: yaml
+
+   rules:
+     - name_pattern: CONFIG_CPU_FREQ_GOV.*
+       expected: disabled
+       severity: medium
+
+     - name: CONFIG_CPU_FREQ_GOV_USERSPACE
+       expected: enabled
+       severity: low
+
+if the checked ``.config`` has ``CONFIG_CPU_FREQ_GOV_USERSPACE``, then it
+is expected to be enabled, regardless of the pattern's rule disabled
+expectation.
+
+Pattern priorities
+------------------
+
+When a symbol matches more than one pattern rule, the pattern rule with the
+highest priority (``pattern_prio``) is used.  That field is optional and
+defaults to ``0``.  A bigger integer implies a higher priority.
+
+For example, for the policy below:
+
+.. code-block:: yaml
+
+  rules:
+    - name_pattern: CONFIG_DEBUG
+      expected: disabled
+      severity: medium
+
+    - name_pattern: CONFIG_DEBUG_INFO
+      pattern_prio: 1
+      expected: enabled
+      severity: low
+
+if the checked ``.config`` has ``CONFIG_DEBUG_INFO_DWARF4``, it is expected
+to be enabled.  This is because the ``CONFIG_DEBUG_INFO`` pattern has a
+higher priority of ``1``, while the broader ``CONFIG_DEBUG`` pattern has
+the default priority ``0``.
+
+Pattern priority conflicts are rejected
+---------------------------------------
+
+If multiple matching pattern rules share the highest priority for a symbol,
+the policy is ambiguous and the checker reports it as malformed.  A unique
+higher-priority match takes precedence over any lower-priority matches.
+
+For example, for the policy below:
+
+.. code-block:: yaml
+
+   rules:
+     - name_pattern: CONFIG_NETFILTER_XT_MATCH_.*
+       expected: disabled
+       severity: medium
+
+     - name_pattern: CONFIG_NETFILTER_XT_MATCH_BPF.*
+       expected: enabled
+       severity: low
+
+if the checked ``.config`` has a ``CONFIG_NETFILTER_XT_MATCH_BPF`` symbol,
+then ``kconfig-audit`` will exit with a "malformed policy" error.
+
+Note that pattern priority conflicts are detected only for symbols present
+in the checked ``.config``.  An exact ``name`` rule continues to take
+precedence over all pattern rules for such symbols.
+
+Duplicate rules are rejected
+----------------------------
+
+Duplicate exact symbol rules are rejected.  The policy below:
+
+.. code-block:: yaml
+
+   rules:
+     - name: CONFIG_SECURITY_SELINUX
+       expected: enabled
+       severity: fatal
+
+     - name: CONFIG_SECURITY_SELINUX
+       expected: neutral
+       severity: low
+
+is considered malformed.
+
+.. _policy-file-reference:
+
+Policy file reference
+=====================
+
+Top-level fields
+----------------
+
+``api_version``
++++++++++++++++
+
+*Required*.  Sets the kconfig-audit policy file version.  Only one version
+tag is supported so far::
+
+   kconfig-audit.kernel.org/v1
+
+``kind``
+++++++++
+
+*Required*.  Identifies the YAML document's type.  For a configuration
+policy file, the value must be::
+
+   Policy
+
+``docs_url``
+++++++++++++
+
+*Optional*.  Base URL used for rule documentation links.  For example:
+
+.. code-block:: yaml
+
+   docs_url: https://docs.kernel.org/core-api/real-time/kernel-configuration.html
+
+A rule may then provide ``docs_hint`` to form a full rationale URL.
+
+``rules``
++++++++++
+
+*Required*.  A non-empty list of rule entries.
+
+Each rule describes either one exact configuration symbol or a pattern that
+matches several symbols.  See :ref:`Rule fields <rule-fields>`.
+
+.. _rule-fields:
+
+Rule fields
+-----------
+
+Each rule must contain one configuration symbol selector, one expected
+value, and one severity.
+
+A rule matching one exact symbol uses ``name``:
+
+.. code-block:: yaml
+
+   rules:
+     - name: CONFIG_PREEMPT_RT
+       expected: enabled
+       severity: fatal
+
+A rule matching symbols by regular expression uses ``name_pattern``:
+
+.. code-block:: yaml
+
+   rules:
+     - name_pattern: CONFIG_USB
+       expected: disabled
+       severity: medium
+
+A rule must not contain both ``name`` and ``name_pattern``.
+
+``name``
+++++++++
+
+Matches one exact kernel configuration symbol.
+
+The name must have the usual ``CONFIG_`` form, for example::
+
+   CONFIG_EXT4_FS
+
+Exact symbol rules are best when one symbol has a distinct meaning, a
+distinct severity, or its own rationale.
+
+``name_pattern``
+++++++++++++++++
+
+Matches configuration symbols by Python regular expression.
+
+The checker applies the regular expression to each symbol name using search
+semantics.  Expressions are not implicitly anchored.
+
+For example, this pattern::
+
+   CONFIG_NETFILTER
+
+matches names such as::
+
+   CONFIG_NETFILTER
+   CONFIG_NETFILTER_ADVANCED
+   CONFIG_NETFILTER_XT_MATCH_BPF
+
+Use anchors when the rule should match only a narrow set of symbols.  For
+example::
+
+   ^CONFIG_NO_HZ(_FULL|_IDLE)?$
+
+The schema validates that ``name_pattern`` is a syntactically valid regular
+expression.
+
+``pattern_prio``
+++++++++++++++++
+
+*Optional*.  Sets the priority of a ``name_pattern`` rule.  The value must
+be an integer from 1 to 100.  If omitted, the priority is ``0``.
+
+For a symbol matching multiple pattern rules, the matching rule with the
+highest priority is used.  If multiple matching rules share the highest
+priority, the policy is rejected as ambiguous.  This field is not valid on
+an exact ``name`` rule.
+
+``expected``
+++++++++++++
+
+*Required*.  Describes the expected state of the matching symbol or
+symbols.
+
+Allowed values are:
+
+``enabled``
+   The symbol must be set to ``y`` or ``m``.
+
+   For an exact ``name`` rule, a missing symbol fails an ``enabled`` rule.
+   An explicitly unset symbol also fails.  For a ``name_pattern`` rule, the
+   rule applies only to symbols matched in the checked ``.config``.  A
+   non-boolean value, such as an integer, hexadecimal value, or string,
+   fails because the rule expects a tristate kconfig symbol.
+
+``disabled``
+   For an exact ``name`` rule, the symbol must be absent or explicitly
+   unset.  For a ``name_pattern`` rule, any matched symbol must be
+   explicitly unset.
+
+   A symbol set to ``y`` or ``m`` fails.  A non-boolean value also fails,
+   because the rule has a tristate kconfig expectation.
+
+``neutral``
+   The symbol is deliberately not checked.
+
+   A neutral pattern rule can exempt symbols from broader pattern rules when
+   its ``pattern_prio`` is higher.  Neutral rules are also useful when a
+   policy wants to document that a symbol was considered but intentionally
+   left unconstrained.
+
+``severity``
+++++++++++++
+
+*Required*.  Describes how serious a rule violation is.
+
+Allowed values are, from highest to lowest::
+
+    fatal
+    high
+    medium
+    low
+    info
+
+The checker reports issues grouped by severity.  Any issue, including an
+``info`` issue, causes the check command to exit unsuccessfully.  Severity
+is therefore for reporting and triage; it is not a pass/fail threshold.
+
+``docs_hint``
++++++++++++++
+
+*Optional*.  Identifies documentation for the rule.
+
+If the policy has ``docs_url`` and a rule has ``docs_hint``, the checker
+prints a rationale URL by appending the hint as a URI fragment.
+
+For an exact ``name`` rule, this shortcut may be used:
+
+.. code-block:: yaml
+
+   docs_hint: config
+
+With an exact symbol rule, ``config`` is converted into a fragment derived
+from the configuration symbol name.
+
+For example:
+
+.. code-block:: yaml
+
+   docs_url: https://docs.kernel.org/core-api/real-time/kernel-configuration.html
+
+   rules:
+     - name: CONFIG_DRM
+       expected: disabled
+       severity: info
+       docs_hint: config
+
+produces the URL::
+
+   https://docs.kernel.org/core-api/real-time/kernel-configuration.html#config-drm
+
+For any other ``docs_hint`` value, the value is used directly as the
+fragment identifier.  For example:
+
+.. code-block:: yaml
+
+   docs_hint: non-performance-cpu-frequency-governors
+
+produces::
+
+   #non-performance-cpu-frequency-governors
+
+Since a pattern does not name one specific symbol, pattern rules *should*
+use an explicit fragment name rather than the ``config`` shortcut.
+
+``rationale``
++++++++++++++
+
+*Optional*.  Human-readable explanation printed with a reported issue.
+
+A rationale *should* explain why the rule exists, not merely repeat the
+rule.  It may be written on one line, or as a YAML block for longer text:
+
+.. code-block:: yaml
+
+   rationale:
+     Dynamic CPU frequency changes can introduce latency variation.
+     Real-time deployments must select a fixed performance governor.
diff --git a/tools/kconfig-audit/audit.py b/tools/kconfig-audit/audit.py
index 6ff4a56281ad..eac25740beca 100755
--- a/tools/kconfig-audit/audit.py
+++ b/tools/kconfig-audit/audit.py
@@ -98,7 +98,12 @@ try:
     import jsonschema               # type: ignore
     import yaml as yaml_m           # type: ignore
 except ModuleNotFoundError as e:
-    error(f'Missing Python module: {e.name}', os.EX_UNAVAILABLE)
+    docs = 'Documentation/tools/kconfig-audit.rst'
+    error(
+        f'Missing Python module: {e.name}\n'
+        f'Check {docs} for how to install required dependencies',
+        os.EX_UNAVAILABLE
+    )
 
 #
 # Kernel .config model:
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 05/11] kconfig-audit: Split policy schema for component reuse
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
                   ` (3 preceding siblings ...)
  2026-12-03 22:49 ` [PATCH v2 04/11] Documentation: Describe kconfig-audit usage and design Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  2026-12-03 22:49 ` [PATCH v2 06/11] kconfig-audit: Introduce policy overlays schema Ahmed S. Darwish
                   ` (5 subsequent siblings)
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Normal kconfig-audit policy files require every rule to define both
'expected' and 'severity'.  Overlay files are different: an overlay rule
may override only selected fields of an existing base rule.  Thus, a schema
for overlay files will permit these fields to be omitted.

Move common rule definitions into schema/rule.yml, where it can be used by
multiple schemas.  Add a strict schema/policy-v1.yml wrapper for complete
policy files.

Teach the checker to build a Draft7Validator with local file:// URIs so
that policy-v1.yml can resolve the new rule.yml file.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 tools/kconfig-audit/audit.py             |  56 ++++++++---
 tools/kconfig-audit/schema/policy-v1.yml | 117 ++---------------------
 tools/kconfig-audit/schema/rule.yml      | 117 +++++++++++++++++++++++
 3 files changed, 170 insertions(+), 120 deletions(-)
 create mode 100644 tools/kconfig-audit/schema/rule.yml

diff --git a/tools/kconfig-audit/audit.py b/tools/kconfig-audit/audit.py
index eac25740beca..94ff427715d1 100755
--- a/tools/kconfig-audit/audit.py
+++ b/tools/kconfig-audit/audit.py
@@ -78,7 +78,7 @@ import textwrap
 from dataclasses import dataclass, field
 from enum import Enum, auto
 from pathlib import Path
-from typing import Any, ClassVar, Final, Mapping, NoReturn, Optional
+from typing import Any, ClassVar, Final, Mapping, NoReturn, Optional, Protocol
 
 #
 # Initial sanity checks:
@@ -249,12 +249,7 @@ class Helpers:
     def validate_yaml(yaml: YamlDict, schema: Schema, f_name: str) -> None:
         """Validate a parsed YAML mapping against passed JSON Schema"""
         try:
-            # For regex validation, manually enforce a format checker
-            jsonschema.validate(
-                yaml,
-                schema,
-                format_checker=jsonschema.FormatChecker(),
-            )
+            schema.validator.validate(yaml)
         except jsonschema.exceptions.ValidationError as e:
             error(
                 f'{f_name} does not match its schema\n'
@@ -322,31 +317,68 @@ class VersionedYamlFile:
 # Schema model:
 #
 
+class YamlValidator(Protocol):
+    """Protocol for JSON Schema validators accepted by the Schema model"""
+    def validate(self, instance: YamlDict) -> None:
+        ...
+
 class Schema(YamlDict):
     """Modeled policy schema, as a YAML dictionary mapping"""
 
+    validator: YamlValidator
+
+    def __init__(self, mapping: YamlDict, validator: YamlValidator):
+        super().__init__(mapping)
+        self.validator = validator
+
 class SchemaFile:
     """json-schema.org policy schema parser (to Schema model)"""
 
     def __init__(self, schema_f: Path):
         self.schema_f = schema_f
-        self.yaml = Helpers.load_yaml(schema_f)
+        self.schema_y = Helpers.load_yaml(schema_f)
 
     def parse(self) -> Schema:
         """Parse and validate a policy schema file"""
 
-        schema = Schema(self.yaml)
+        rule_schema_f = self.schema_f.parent / 'rule.yml'
+        rule_schema_y = Helpers.load_yaml(rule_schema_f)
+
+        self._check_schema(rule_schema_f, rule_schema_y)
+        self._check_schema(self.schema_f, self.schema_y)
+
+        validator = self._create_validator({
+            rule_schema_f.resolve().as_uri(): rule_schema_y,
+        })
 
-        # Validate the schema against its own draft-07 grammar
+        return Schema(self.schema_y, validator)
+
+    @staticmethod
+    def _check_schema(schema_f: Path, schema: YamlDict) -> None:
+        """Validate passed schema against its own draft-07 metaschema"""
         try:
             jsonschema.Draft7Validator.check_schema(schema)
         except jsonschema.exceptions.SchemaError as e:
             error(
-                f'Invalid schema {self.schema_f}:\nReason: {e.message}',
+                f'Invalid schema {schema_f}:\nReason: {e.message}',
                 os.EX_DATAERR,
             )
 
-        return schema
+    def _create_validator(self, store: dict[str, YamlDict]) -> YamlValidator:
+        """Create a schema validator for resolving sibling '$ref' entries"""
+
+        resolver = jsonschema.RefResolver(
+            base_uri=self.schema_f.resolve().as_uri(),
+            referrer=self.schema_y,
+            store=store,
+        )
+
+        return jsonschema.Draft7Validator(
+            self.schema_y,
+            resolver=resolver,
+            # For regex entries validation, manually enforce a format checker
+            format_checker=jsonschema.FormatChecker(),
+        )
 
 #
 # Policy model:
diff --git a/tools/kconfig-audit/schema/policy-v1.yml b/tools/kconfig-audit/schema/policy-v1.yml
index 10672226415b..2eacb5d2f485 100644
--- a/tools/kconfig-audit/schema/policy-v1.yml
+++ b/tools/kconfig-audit/schema/policy-v1.yml
@@ -17,8 +17,8 @@ properties:
     const: Policy
 
   #
-  # Optional base URL for the documentation page used by rationale
-  # links.  See `docs_hint`.
+  # Optional base URL for the rules rationale documentation page.
+  # See `docs_hint` @ schema/rule.yml.
   #
   docs_url:
     type: string
@@ -28,112 +28,13 @@ properties:
     type: array
     minItems: 1
     items:
-      type: object
-      oneOf:
-        - required: [name]
-        - required: [name_pattern]
       allOf:
-        - if:
-            required: [name]
-          then:
-            not:
-              required: [pattern_prio]
-      required: [expected, severity]
-      additionalProperties: false
-
-      properties:
-        #
-        # Exact kernel configuration symbol to check.
-        #
-        # Example: CONFIG_PREEMPT_RT
-        #
-        name:
-          type: string
-          pattern: '^CONFIG_[A-Z0-9_]+$'
-
-        #
-        # Regex matching one or more kernel configuration symbols.
-        #
-        # Example: CONFIG_DEBUG_.*
-        #
-        name_pattern:
-          type: string
-          format: regex
-
-        #
-        # Optional priority for a pattern rule.
-        #
-        # Higher numbers imply a higher priority.  All pattern rules have a
-        # default priority of zero, so specifying a zero here is of no use.
-        #
-        pattern_prio:
-          type: integer
-          minimum: 1
-          maximum: 100
-
-        #
-        # Expected value for the matching kernel configuration option.
-        #
-        # Values:
-        #
-        #   enabled  option is expected to be enabled (built-in or module).
-        #   disabled option is expected to be either absent or unset.
-        #   neutral  option can be enabled or disabled. This is used to exempt
-        #            one or more symbols from a `name_pattern` rule.
-        #
-        expected:
-          type: string
-          enum: [enabled, disabled, neutral]
-
-        #
-        # Issue severity to report when the configuration rule is not met.
-        #
-        # Higher severities should be reserved for rules affecting correctness.
-        #
-        severity:
-          type: string
-          enum: [fatal, high, medium, low, info]
-
-        #
-        # Optional documentation anchor for this rule.
-        #
-        # The rationale URL is built from `docs_url` plus an HTML fragment
-        # identifier.
-        #
-        # If `docs_hint` is set to `config`, then the HTML fragment id is
-        # derived from the kernel configuration symbol name:
-        #
-        #   CONFIG_DRM  ->  #config-drm
-        #
-        # For example, with below docs_url:
-        #
-        #   https://docs.kernel.org/core-api/real-time/kernel-configuration.html
-        #
-        # and the symbol entry:
-        #
-        #   - name: CONFIG_DRM
-        #     expected: disabled
-        #     severity: info
-        #     docs_hint: config
-        #
-        # the rationale URL becomes:
-        #
-        #   https://docs.kernel.org/core-api/real-time/kernel-configuration.html#config-drm
-        #
-        # If `docs_hint` is any other string, that string is used directly as
-        # the HTML fragment identifier.
-        #
-        docs_hint:
-          type: string
-          anyOf:
-            - const: config
-            - pattern: '^\S+$'   # URI fragments cannot have spaces
-
-        #
-        # Optional human-readable explanation for the rule.
+        - $ref: "rule.yml#/definitions/rule"
         #
-        # This text should explain why the option is expected to have the given
-        # value, and may span multiple lines.
+        # The base schema leaves `expected` and `severity` optional so that
+        # policy overlays can contain partial rule entries without
+        # restating fields they do not override.  In a complete policy
+        # file, like this one, these fields are mandatory for every rule.
         #
-        rationale:
-          type: string
+        - type: object
+          required: [expected, severity]
diff --git a/tools/kconfig-audit/schema/rule.yml b/tools/kconfig-audit/schema/rule.yml
new file mode 100644
index 000000000000..a6b1bfdb435b
--- /dev/null
+++ b/tools/kconfig-audit/schema/rule.yml
@@ -0,0 +1,117 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+"$schema": "https://json-schema.org/draft-07/schema#"
+
+title: Schema for a single kconfig-audit policy rule
+type: object
+
+definitions:
+  rule:
+    type: object
+    oneOf:
+      - required: [name]
+      - required: [name_pattern]
+    allOf:
+      - if:
+          required: [name]
+        then:
+          not:
+            required: [pattern_prio]
+    additionalProperties: false
+
+    properties:
+      #
+      # Exact kernel configuration symbol to check.
+      #
+      # Example: CONFIG_PREEMPT_RT
+      #
+      name:
+        type: string
+        pattern: '^CONFIG_[A-Z0-9_]+$'
+
+      #
+      # Regex matching one or more kernel configuration symbols.
+      #
+      # Example: CONFIG_DEBUG_.*
+      #
+      name_pattern:
+        type: string
+        format: regex
+
+      #
+      # Optional priority for a pattern rule.
+      #
+      # Higher numbers imply a higher priority.  All pattern rules have a
+      # default priority of zero, so specifying a zero here is of no use.
+      #
+      pattern_prio:
+        type: integer
+        minimum: 1
+        maximum: 100
+
+      #
+      # Expected value for the matching kernel configuration option.
+      #
+      # Values:
+      #
+      #   enabled  option is expected to be enabled (built-in or module).
+      #   disabled option is expected to be either absent or unset.
+      #   neutral  option can be enabled or disabled. This is used to exempt
+      #            one or more symbols from a `name_pattern` rule.
+      #
+      expected:
+        type: string
+        enum: [enabled, disabled, neutral]
+
+      #
+      # Issue severity to report when the configuration rule is not met.
+      #
+      # Higher severities should be reserved for rules affecting correctness.
+      #
+      severity:
+        type: string
+        enum: [fatal, high, medium, low, info]
+
+      #
+      # Optional documentation anchor for this rule.
+      #
+      # The rationale URL is built from `docs_url` plus an HTML fragment
+      # identifier.
+      #
+      # If `docs_hint` is set to `config`, then the HTML fragment id is
+      # derived from the kernel configuration symbol name:
+      #
+      #   CONFIG_DRM  ->  #config-drm
+      #
+      # For example, with below docs_url:
+      #
+      #   https://docs.kernel.org/core-api/real-time/kernel-configuration.html
+      #
+      # and the symbol entry:
+      #
+      #   - name: CONFIG_DRM
+      #     expected: disabled
+      #     severity: info
+      #     docs_hint: config
+      #
+      # the rationale URL becomes:
+      #
+      #   https://docs.kernel.org/core-api/real-time/kernel-configuration.html#config-drm
+      #
+      # If `docs_hint` is any other string, that string is used directly as
+      # the HTML fragment identifier.
+      #
+      docs_hint:
+        type: string
+        anyOf:
+          - const: config
+          - pattern: '^\S+$'   # URI fragments cannot have spaces
+
+      #
+      # Optional human-readable explanation for the rule.
+      #
+      # This text should explain why the option is expected to have the given
+      # value, and may span multiple lines.
+      #
+      rationale:
+        type: string
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 06/11] kconfig-audit: Introduce policy overlays schema
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
                   ` (4 preceding siblings ...)
  2026-12-03 22:49 ` [PATCH v2 05/11] kconfig-audit: Split policy schema for component reuse Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  2026-12-03 22:49 ` [PATCH v2 07/11] kconfig-audit: Add support for policy overlays Ahmed S. Darwish
                   ` (4 subsequent siblings)
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Add a schema for kconfig-audit policy overlay files.  Reuse the previously
refactored rule definitions at rule.yml.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 .../schema/policy-overlay-v1.yml              | 49 +++++++++++++++++++
 tools/kconfig-audit/schema/rule.yml           |  6 +--
 2 files changed, 52 insertions(+), 3 deletions(-)
 create mode 100644 tools/kconfig-audit/schema/policy-overlay-v1.yml

diff --git a/tools/kconfig-audit/schema/policy-overlay-v1.yml b/tools/kconfig-audit/schema/policy-overlay-v1.yml
new file mode 100644
index 000000000000..d95e9197a53c
--- /dev/null
+++ b/tools/kconfig-audit/schema/policy-overlay-v1.yml
@@ -0,0 +1,49 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+"$schema": "https://json-schema.org/draft-07/schema#"
+
+title: kconfig-audit policy schema
+type: object
+required: [api_version, kind]
+additionalProperties: false
+
+properties:
+  api_version:
+    type: string
+    const: kconfig-audit.kernel.org/v1
+
+  kind:
+    type: string
+    const: PolicyOverlay
+
+  # Optional base policy `docs_url` override
+  docs_url:
+    type: string
+    format: uri
+
+  #
+  # Full policy files require `expected` and `severity` for each rule.
+  # Meanwhile, policy overlay files can contain partial rule entries
+  # without restating fields they do not override.  Thus, do not require
+  # such fields here.
+  #
+  # For example, a PREEMPT_RT policy can have:
+  #
+  # rules:
+  #  - name: CONFIG_DRM
+  #    expected: disabled
+  #    severity: info
+  #    docs_hint: config
+  #
+  # and its overlay can just be:
+  #
+  # rules:
+  #  - name: CONFIG_DRM
+  #    expected: neutral
+  #
+  rules:
+    type: array
+    minItems: 1
+    items:
+      allOf:
+        - $ref: "rule.yml#/definitions/rule"
diff --git a/tools/kconfig-audit/schema/rule.yml b/tools/kconfig-audit/schema/rule.yml
index a6b1bfdb435b..db839d992d7b 100644
--- a/tools/kconfig-audit/schema/rule.yml
+++ b/tools/kconfig-audit/schema/rule.yml
@@ -56,9 +56,9 @@ definitions:
       #
       #   enabled  option is expected to be enabled (built-in or module).
       #   disabled option is expected to be either absent or unset.
-      #   neutral  option can be enabled or disabled. This is used to exempt
-      #            one or more symbols from a `name_pattern` rule.
-      #
+      #   neutral  option can be enabled or disabled. This is to be used
+      #            by overlays, or to exempt one or more symbols from a
+      #            `name_pattern` rule.
       expected:
         type: string
         enum: [enabled, disabled, neutral]
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 07/11] kconfig-audit: Add support for policy overlays
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
                   ` (5 preceding siblings ...)
  2026-12-03 22:49 ` [PATCH v2 06/11] kconfig-audit: Introduce policy overlays schema Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  2026-12-03 22:49 ` [PATCH v2 08/11] Documentation: kconfig-audit: Describe " Ahmed S. Darwish
                   ` (3 subsequent siblings)
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

A kconfig-audit policy overlay is a YAML file applied on top of an existing
policy file.  Overlays are intended for distribution kernel packaging
scripts, CI environments, and board support packages; where the base rules
may need local adjustments.  Overlays may override any rule's field.  They
may also update the documentation URL or introduce totally new rules.

Add support for such an overlay mechanism at the kconfig-audit Python code.

Introduce a data model for rule overlays first, then extend the checker's
logic in terms of that.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 tools/kconfig-audit/audit.py | 210 ++++++++++++++++++++++++++++++++++-
 1 file changed, 208 insertions(+), 2 deletions(-)

diff --git a/tools/kconfig-audit/audit.py b/tools/kconfig-audit/audit.py
index 94ff427715d1..ba6ba86f2791 100755
--- a/tools/kconfig-audit/audit.py
+++ b/tools/kconfig-audit/audit.py
@@ -9,7 +9,7 @@
 #     $ audit.py list-policies
 #     $ audit.py list-api-versions
 #
-#     $ audit.py check -c path/to/.config -p preempt_rt
+#     $ audit.py check -c path/to/.config -p preempt_rt [-o path/to/overlay.yml]
 #
 # Development rules:
 #
@@ -31,6 +31,9 @@
 #       Policy            # internal model, typed policy rules repo
 #       PolicyFile        # parser
 #
+#       PolicyOverlay     # internal model, typed overlays repo
+#       PolicyOverlayFile # parser
+#
 #       Schema            # internal model, dictionary-like
 #       SchemaFile        # parser
 #
@@ -78,7 +81,9 @@ import textwrap
 from dataclasses import dataclass, field
 from enum import Enum, auto
 from pathlib import Path
-from typing import Any, ClassVar, Final, Mapping, NoReturn, Optional, Protocol
+from typing import (
+    Any, ClassVar, Final, Mapping, NoReturn, Optional, Protocol, Union,
+)
 
 #
 # Initial sanity checks:
@@ -546,6 +551,195 @@ class PolicyFile(VersionedYamlFile):
         # Schema should guard against this
         Helpers.unreachable('YAML rule entry without `name` or `name_pattern`')
 
+#
+# Policy overlays model:
+#
+
+@dataclass(frozen=True)
+class SymbolOverlay:
+    """Overlay for a .config symbol rule"""
+
+    symbol: str
+
+    @property
+    def rule_id(self) -> str:
+        return self.symbol
+
+@dataclass(frozen=True)
+class PatternOverlay:
+    """Overlay for a .config regex pattern rule"""
+
+    symbol_regex: str
+
+    @property
+    def rule_id(self) -> str:
+        return self.symbol_regex
+
+OverlayTarget = Union[SymbolOverlay, PatternOverlay]
+
+@dataclass
+class RuleOverlay:
+    """Typed overlay for a (symbol or regex) .config rule"""
+
+    target: OverlayTarget
+    expected: Optional[ExpectedValue]
+    severity: Optional[Severity]
+    rationale: Optional[str]
+    docs_hint: Optional[str]
+
+    @property
+    def rule_id(self) -> str:
+        return self.target.rule_id
+
+@dataclass
+class PolicyOverlay:
+    """Policy overlays repository / data model"""
+
+    docs_url: Optional[str]
+
+    # Store rule overlays in a dictionary to easily detect duplicates
+    rules: dict[OverlayTarget, RuleOverlay]
+
+    def add_rule(self, rule: RuleOverlay) -> None:
+        """Add the given rule overly to the overlays repository"""
+        target = rule.target
+
+        if target in self.rules:
+            if isinstance(target, SymbolOverlay):
+                error(
+                    f'Duplicate overlay rule: {rule.rule_id}',
+                    os.EX_DATAERR,
+                )
+            if isinstance(target, PatternOverlay):
+                error(
+                    f'Duplicate overlay pattern: {rule.rule_id}',
+                    os.EX_DATAERR,
+                )
+            raise TypeError(f'Unsupported target type: {type(target).__name__}')
+
+        self.rules[target] = rule
+
+class PolicyOverlayFile(VersionedYamlFile):
+    """YAML overlay files parser (to PolicyOverlay)"""
+
+    SCHEMAS = {
+        VersionedYamlFile.AUDIT_API_V1: 'policy-overlay-v1.yml',
+    }
+
+    def parse(self) -> PolicyOverlay:
+        """Parse the YAML overlay file into a typed PolicyOverlay"""
+        docs_url = self.yaml.get('docs_url')
+        overlay = PolicyOverlay(docs_url, {})
+
+        for rule_mapping in self.yaml.get('rules', []):
+            overlay.add_rule(self._parse_rule(rule_mapping))
+
+        return overlay
+
+    def _parse_rule(self, rule: YamlDict) -> RuleOverlay:
+        """Parse passed single YAML overlay rule (to RuleOverlay)"""
+        if 'name' in rule:
+            symbol = rule['name']
+            target: OverlayTarget = SymbolOverlay(symbol)
+        elif 'name_pattern' in rule:
+            regex = rule['name_pattern']
+            target = PatternOverlay(regex)
+        else:
+            Helpers.unreachable('Overlay rule without `name` or `name_pattern`')
+
+        expected = (
+            ExpectedValue[rule['expected']]
+            if 'expected' in rule else None
+        )
+        severity = (
+            Severity[rule['severity']]
+            if 'severity' in rule else None
+        )
+
+        return RuleOverlay(
+            target,
+            expected,
+            severity,
+            rule.get('rationale'),
+            rule.get('docs_hint'),
+        )
+
+class Overlayer:
+    """Apply a parsed policy overlay to a policy"""
+
+    @staticmethod
+    def apply(overlay: PolicyOverlay, policy: Policy) -> Policy:
+        """Apply passed overlay to policy and return the updated policy"""
+        if overlay.docs_url:
+            policy.docs_url = overlay.docs_url
+
+        for rule_overlay in overlay.rules.values():
+            rule = Overlayer._find_rule(rule_overlay, policy)
+            if rule:
+                Overlayer._update_rule(rule_overlay, rule)
+            else:
+                new_rule = Overlayer._new_rule(rule_overlay)
+                policy.add_rule(new_rule)
+
+        return policy
+
+    @staticmethod
+    def _find_rule(overlay: RuleOverlay, policy: Policy) -> Optional[Rule]:
+        """Find the actual policy rule targeted by passed rule overlay"""
+        if isinstance(overlay.target, SymbolOverlay):
+            return policy.get_symbol_rule(overlay.rule_id)
+
+        if isinstance(overlay.target, PatternOverlay):
+            return policy.get_pattern_rule(overlay.rule_id)
+
+        Helpers.unreachable('Unknown overlay target type')
+
+    @staticmethod
+    def _update_rule(overlay: RuleOverlay, rule: Rule) -> None:
+        """Apply an overlay's specified fields to an existing rule"""
+        if overlay.expected:
+            rule.expected = overlay.expected
+
+        if overlay.severity:
+            rule.severity = overlay.severity
+
+        if overlay.rationale:
+            rule.rationale = overlay.rationale
+
+        if overlay.docs_hint:
+            rule.docs_hint = overlay.docs_hint
+            rule._normalize_docs_hint()
+
+    @staticmethod
+    def _new_rule(overlay: RuleOverlay) -> Rule:
+        """Create a new policy rule from an overlay that has no matching rule"""
+
+        # A policy overlay over a base rule has all required fields
+        # provided by its parent. New rules have no parent, and thus all
+        # required fields must be manually checked.
+        if not overlay.expected:
+            error(
+                f'`expected` is missing from {overlay.rule_id}',
+                os.EX_DATAERR,
+            )
+        if not overlay.severity:
+            error(
+                f'`severity` is missing from {overlay.rule_id}',
+                os.EX_DATAERR,
+            )
+
+        args = (
+            overlay.expected,
+            overlay.severity,
+            overlay.rationale,
+            overlay.docs_hint,
+        )
+
+        if isinstance(overlay.target, SymbolOverlay):
+            return SymbolRule(*args, overlay.rule_id)
+
+        return PatternRule(*args, re.compile(overlay.rule_id))
+
 #
 # Error reporting model:
 #
@@ -904,6 +1098,14 @@ def parse_args(policies: list[str]) -> argparse.Namespace:
         help='policy file to check against',
     )
 
+    check_parser.add_argument(
+        '-o',
+        '--overlay',
+        metavar='OVERLAY_FILE',
+        type=Path,
+        help='policy overlay file to apply after the selected policy',
+    )
+
     return parser.parse_args()
 
 def main() -> None:
@@ -932,6 +1134,10 @@ def main() -> None:
         policy_f = policy_dir / f'{args.policy}.yml'
     policy = PolicyFile(policy_f, schema_dir).parse()
 
+    if args.overlay:
+        overlay = PolicyOverlayFile(args.overlay, schema_dir).parse()
+        policy = Overlayer.apply(overlay, policy)
+
     checker = Checker(kconfig, policy)
     report = checker.make_report()
 
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 08/11] Documentation: kconfig-audit: Describe policy overlays
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
                   ` (6 preceding siblings ...)
  2026-12-03 22:49 ` [PATCH v2 07/11] kconfig-audit: Add support for policy overlays Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  2026-12-03 22:49 ` [PATCH v2 09/11] MAINTAINERS: Add entry for kernel configuration audit Ahmed S. Darwish
                   ` (2 subsequent siblings)
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Document kconfig-audit's policy overlays structure and usage.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 Documentation/tools/kconfig-audit.rst | 128 ++++++++++++++++++++++++--
 1 file changed, 118 insertions(+), 10 deletions(-)

diff --git a/Documentation/tools/kconfig-audit.rst b/Documentation/tools/kconfig-audit.rst
index 5b8e2fa842b1..e83eb56e43ed 100644
--- a/Documentation/tools/kconfig-audit.rst
+++ b/Documentation/tools/kconfig-audit.rst
@@ -26,6 +26,10 @@ Check a ``.config`` against a policy known to the checker::
 
    audit.py check -c path/to/.config -p preempt_rt
 
+An optional overlay may be supplied with ``-o``::
+
+   audit.py check -c path/to/.config -p preempt_rt -o path/to/overlay.yml
+
 Example invocation from within the kernel tree:
 
 .. code-block:: shell
@@ -121,6 +125,24 @@ The supplied PREEMPT_RT policy resides in the kernel source tree at::
 For field-by-field descriptions of the policy's top-level and rule fields,
 see :ref:`Policy file reference <policy-file-reference>`.
 
+Policy overlays format
+======================
+
+Policy overlay files are YAML documents applied on top of the requested
+configuration policy.  A policy overlay typically looks like:
+
+.. code-block:: yaml
+
+   api_version: kconfig-audit.kernel.org/v1
+   kind: PolicyOverlay
+
+   rules:
+     - name: CONFIG_DRM
+       severity: high
+
+where in the above case, the base policy's ``CONFIG_DRM`` rule severity is
+overriden to high.
+
 Rule matching
 =============
 
@@ -285,10 +307,86 @@ Duplicate exact symbol rules are rejected.  The policy below:
 
 is considered malformed.
 
+Writing overlay files
+=====================
+
+Overlays are intended for local policy, distribution kernel packaging, CI
+environments, and board support packages.  Use an overlay to adjust the
+behaviour of a mainline kernel configuration policy.
+
+Overriding an existing rule
+---------------------------
+
+An overlay identifies an existing rule by its exact ``name`` or exact
+``name_pattern`` string.  It changes only the fields it supplies.  Omitted
+fields keep their values from the base policy.
+
+For example, if the mainline PREEMPT_RT policy contains below rules:
+
+.. code-block:: yaml
+
+   rules:
+     - name: CONFIG_DRM
+       expected: disabled
+       severity: info
+
+     - name: CONFIG_EFI_DISABLE_RUNTIME
+       expected: enabled
+       severity: medium
+
+A board support package may override such rules with an overlay like:
+
+.. code-block:: yaml
+
+   api_version: kconfig-audit.kernel.org/v1
+   kind: PolicyOverlay
+
+   rules:
+     - name: CONFIG_DRM
+       expected: neutral
+       rationale:
+         This product requires a display controller and accepts the latency
+         cost.
+
+     - name: CONFIG_EFI_DISABLE_RUNTIME
+       expected: disabled
+       rationale:
+         The efi_runtime workqueue is pinned to housekeeping CPU#0.
+
+Note that an overlay ``name_pattern`` does not select every base rule whose
+regex matches the same symbols.  It selects only a base rule with the
+*identical* regular expression pattern text.  If no base rule has that
+target, the overlay creates a new rule.
+
+Adding a new rule
+-----------------
+
+When an overlay target is not in the base policy, a new rule is created.
+In that case, the new rule must provide both ``expected`` and ``severity``
+as well.  Below is an example overlay file which adds a new rule:
+
+.. code-block:: yaml
+
+   api_version: kconfig-audit.kernel.org/v1
+   kind: PolicyOverlay
+
+   rules:
+     - name: CONFIG_USB_STORAGE
+       expected: disabled
+       severity: high
+       rationale: This appliance does not accept removable storage.
+
+Overlay behavior
+----------------
+
+An overlay cannot delete a base rule.  Use ``expected: neutral`` to exempt
+a symbol from policy checking.  To retain inherited values, omit those
+fields.
+
 .. _policy-file-reference:
 
-Policy file reference
-=====================
+Policy files reference
+======================
 
 Top-level fields
 ----------------
@@ -304,11 +402,16 @@ tag is supported so far::
 ``kind``
 ++++++++
 
-*Required*.  Identifies the YAML document's type.  For a configuration
-policy file, the value must be::
+*Required*.  Identifies the YAML document's type.
+
+For a configuration policy file, the value must be::
 
    Policy
 
+For a policy overlay file, the value must be::
+
+   PolicyOverlay
+
 ``docs_url``
 ++++++++++++
 
@@ -323,7 +426,7 @@ A rule may then provide ``docs_hint`` to form a full rationale URL.
 ``rules``
 +++++++++
 
-*Required*.  A non-empty list of rule entries.
+*Required for policy files*.  A non-empty list of rule entries.
 
 Each rule describes either one exact configuration symbol or a pattern that
 matches several symbols.  See :ref:`Rule fields <rule-fields>`.
@@ -408,10 +511,12 @@ an exact ``name`` rule.
 ``expected``
 ++++++++++++
 
-*Required*.  Describes the expected state of the matching symbol or
-symbols.
+*Required for all rules in policy files*.
+
+*Required for newly-added rules in policy overlays*.
 
-Allowed values are:
+Describes the expected state of the matching symbol or symbols.  Allowed
+values are:
 
 ``enabled``
    The symbol must be set to ``y`` or ``m``.
@@ -441,9 +546,12 @@ Allowed values are:
 ``severity``
 ++++++++++++
 
-*Required*.  Describes how serious a rule violation is.
+*Required for all rules in policy files*.
+
+*Required for newly-added rules in policy overlays*.
 
-Allowed values are, from highest to lowest::
+Describes how serious a rule violation is.  Allowed values are, from
+highest to lowest::
 
     fatal
     high
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 09/11] MAINTAINERS: Add entry for kernel configuration audit
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
                   ` (7 preceding siblings ...)
  2026-12-03 22:49 ` [PATCH v2 08/11] Documentation: kconfig-audit: Describe " Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-03 22:49 ` [PATCH v2 10/11] kconfig: Introduce auditconfig target Ahmed S. Darwish
  2026-12-03 22:49 ` [PATCH v2 11/11] Documentation: Describe auditconfig build target Ahmed S. Darwish
  10 siblings, 0 replies; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Add a maintainer entry for kconfig-audit.

Put the PREEMPT_RT kernel configuration policy under Real-time Linux.

Note, include kernel-configuration.rst under the kconfig-audit entry as
well, beside its default inclusion under 'Real-time Linux.'  kconfig-audit
produces multiple links (with HTML fragments) to that document and I would
like to make sure that this keeps working in the future.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
Link: https://msgid.link/avWy2r1BcDatzwo1@lx-t490
Link: https://msgid.link/20261112175042.GD4107043@ax162
Link: https://msgid.link/awXN9RY3x5xEGFe4@lx-t490
---
 MAINTAINERS | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 84cb98ef4c49..93fe8d31b7fe 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -14475,6 +14475,15 @@ F:	scripts/mod/
 F:	scripts/package/
 F:	usr/
 
+KERNEL CONFIGURATION AUDIT
+M:	Ahmed S. Darwish <darwi@linutronix.de>
+R:	Nathan Chancellor <nathan@kernel.org>
+L:	linux-kbuild@vger.kernel.org
+S:	Maintained
+F:	tools/kconfig-audit/
+F:	Documentation/tools/kconfig-audit.rst
+F:	Documentation/core-api/real-time/kernel-configuration.rst
+
 KERNEL HARDENING (not covered by other areas)
 M:	Kees Cook <kees@kernel.org>
 R:	Gustavo A. R. Silva <gustavoars@kernel.org>
@@ -23597,6 +23606,7 @@ M:	Steven Rostedt <rostedt@goodmis.org>
 L:	linux-rt-devel@lists.linux.dev
 S:	Supported
 F:	Documentation/core-api/real-time/
+F:	tools/kconfig-audit/policy/preempt_rt.yml
 K:	PREEMPT_RT
 
 REALTEK AUDIO CODECS
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 10/11] kconfig: Introduce auditconfig target
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
                   ` (8 preceding siblings ...)
  2026-12-03 22:49 ` [PATCH v2 09/11] MAINTAINERS: Add entry for kernel configuration audit Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  2026-12-03 22:49 ` [PATCH v2 11/11] Documentation: Describe auditconfig build target Ahmed S. Darwish
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Add an auditconfig target to check the current .config against a selected
kconfig-audit policy.  Accept an optional overlay through OVERLAY=.

Use kconfig-audit to perform all sanity checks.

List the target and its usage in make help.

Example usage:

   make POLICY=preempt_rt auditconfig

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 scripts/kconfig/Makefile | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/scripts/kconfig/Makefile b/scripts/kconfig/Makefile
index 5baf1c44ffa2..b216761c534f 100644
--- a/scripts/kconfig/Makefile
+++ b/scripts/kconfig/Makefile
@@ -125,6 +125,28 @@ testconfig: $(obj)/conf
 	$(if $(findstring 1,$(KBUILD_VERBOSE)),--capture=no)
 clean-files += tests/.cache
 
+auditconfig := $(PYTHON3) -B $(srctree)/tools/kconfig-audit/audit.py
+auditconfig_overlay = $(if $(OVERLAY),-o "$(OVERLAY)")
+
+list_auditconfig_rules =						\
+	echo -n >&2 "Available POLICY: ";				\
+	$(auditconfig) list-policies >&2;				\
+	echo >&2
+
+PHONY += auditconfig
+auditconfig:
+	$(Q)if [ -z "$(POLICY)" ]; then					\
+		echo >&2 "Usage: make POLICY=<profile> [OVERLAY=<overlay>] auditconfig"; \
+		$(list_auditconfig_rules);				\
+		exit 2;							\
+	fi
+	$(Q)if ! $(auditconfig) list-policies | grep -qw "$(POLICY)"; then	\
+		echo >&2 "Unknown POLICY profile = $(POLICY)";		\
+		$(list_auditconfig_rules);				\
+		exit 2;							\
+	fi
+	$(Q)$(auditconfig) check -c "$(KCONFIG_CONFIG)" -p "$(POLICY)" $(auditconfig_overlay)
+
 # Help text used by make help
 help:
 	@echo  'Configuration targets:'
@@ -154,6 +176,9 @@ help:
 	@echo  '                    default value without prompting'
 	@echo  '  tinyconfig	  - Configure the tiniest possible kernel'
 	@echo  '  testconfig	  - Run Kconfig unit tests (requires python3 and pytest)'
+	@echo  '  auditconfig	  - Check current config against sanity rules specified by POLICY'
+	@echo  '                    Example usage: "make POLICY=preempt_rt auditconfig"'
+	@echo  '                    (requires python3, PyYAML, and jsonschema)'
 	@echo  ''
 	@echo  'Configuration topic targets:'
 	@$(foreach f, $(all-config-fragments), \
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 11/11] Documentation: Describe auditconfig build target
  2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
                   ` (9 preceding siblings ...)
  2026-12-03 22:49 ` [PATCH v2 10/11] kconfig: Introduce auditconfig target Ahmed S. Darwish
@ 2026-12-03 22:49 ` Ahmed S. Darwish
  2026-12-04 22:50   ` sashiko-bot
  10 siblings, 1 reply; 22+ messages in thread
From: Ahmed S. Darwish @ 2026-12-03 22:49 UTC (permalink / raw)
  To: Nathan Chancellor, Nicolas Schier, Julian Braha, Emanuele Rocca,
	Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-doc, linux-kernel, Ahmed S. Darwish

Document the auditconfig target, its POLICY and OVERLAY arguments, and the
diagnostics it reports.

Signed-off-by: Ahmed S. Darwish <darwi@linutronix.de>
---
 Documentation/admin-guide/README.rst  | 29 +++++++++++++++++++++++++++
 Documentation/tools/kconfig-audit.rst |  3 +++
 2 files changed, 32 insertions(+)

diff --git a/Documentation/admin-guide/README.rst b/Documentation/admin-guide/README.rst
index 77fec1de6dc8..6f78988d4005 100644
--- a/Documentation/admin-guide/README.rst
+++ b/Documentation/admin-guide/README.rst
@@ -256,6 +256,35 @@ Configuring the kernel
       should probably answer 'n' to the questions for "development",
       "experimental", or "debugging" features.
 
+Checking the kernel configuration
+---------------------------------
+
+The kconfig build system can validate the generated kernel ``.config``
+against a selected rules profile. Running ``make auditconfig`` prints
+usage information and the available profiles::
+
+  Usage: make POLICY=<profile> [OVERLAY=<overlay>] auditconfig
+  Available POLICY: preempt_rt
+
+For example, to validate the current configuration against the PREEMPT_RT
+profile, run::
+
+  make POLICY=preempt_rt auditconfig
+
+``auditconfig`` reports kconfig options whose values do not match the
+selected rules profile. Each diagnostic includes a severity, such as
+``FATAL`` or ``INFO``, plus the suggested configuration change.
+
+Apply the reported changes as needed and run ``make auditconfig`` again,
+against the same rules, until no relevant diagnostics remain.
+
+The ``OVERLAY=`` parameter specifies an overlay file whose rules overrides
+the built-in mainline profile selected by ``POLICY=``. It is intended for
+distributions kernel packaging scripts, CI systems, and board support
+packages.
+
+For more information, see Documentation/tools/kconfig-audit.rst
+
 Compiling the kernel
 --------------------
 
diff --git a/Documentation/tools/kconfig-audit.rst b/Documentation/tools/kconfig-audit.rst
index e83eb56e43ed..7c1280e7e352 100644
--- a/Documentation/tools/kconfig-audit.rst
+++ b/Documentation/tools/kconfig-audit.rst
@@ -37,6 +37,9 @@ Example invocation from within the kernel tree:
    ~/linux$ make defconfig
    ~/linux$ tools/kconfig-audit/audit.py check -c .config -p preempt_rt
 
+As described in Documentation/admin-guide/README.rst, the checker is also
+used by ``make auditconfig``.
+
 External dependencies
 =====================
 
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 01/11] kconfig-audit: Add schema for policy files
  2026-12-03 22:49 ` [PATCH v2 01/11] kconfig-audit: Add schema for policy files Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Low] kconfig-audit: policy schema name pattern rejects lowercase
  Kconfig symbols
- [Low] kconfig-audit: non-canonical https:// URI in Draft-07 $schema
- [Low] kconfig-audit: docs_hint schema pattern allows # in URI
  fragments
--

commit 922516e5e1ce33b868280571209d1adde89b4e80
Author: Ahmed S. Darwish <darwi@linutronix.de>

kconfig-audit: Add schema for policy files

This commit defines the JSON Schema for kconfig-audit policy files in
tools/kconfig-audit/schema/policy-v1.yml and documents the purpose of each
field.

> diff --git a/tools/kconfig-audit/schema/policy-v1.yml b/tools/kconfig-audit/schema/policy-v1.yml
> new file mode 100644
> index 0000000000000..10672226415be
> --- /dev/null
> +++ b/tools/kconfig-audit/schema/policy-v1.yml
> @@ -0,0 +1,139 @@
> +# SPDX-License-Identifier: GPL-2.0-only
> +
> +"$schema": "https://json-schema.org/draft-07/schema#"

[Severity: Low]
Should $schema use the canonical Draft-07 URI
"http://json-schema.org/draft-07/schema#" instead of https://?

Draft-07 identifies its meta-schema with http://, and validators match
$schema as a literal URI identifier rather than following HTTP redirects.
External validators that dispatch on $schema (such as check-jsonschema)
will not recognize the https:// URI as Draft-07 and will reject it or warn.

[ ... ]

> +        #
> +        # Exact kernel configuration symbol to check.
> +        #
> +        # Example: CONFIG_PREEMPT_RT
> +        #
> +        name:
> +          type: string
> +          pattern: '^CONFIG_[A-Z0-9_]+$'

[Severity: Low]
Does this pattern reject valid Kconfig symbols that contain lowercase
letters?

scripts/kconfig/lexer.l allows [A-Za-z0-9_-] in symbol names, and mainline
Kconfig files define symbols such as CONFIG_VFPv3 and CONFIG_SCx200.  Any
policy referencing one of those symbols will fail schema validation;
relaxing the pattern to '^CONFIG_[A-Za-z0-9_-]+$' would match Kconfig.

[ ... ]

> +        # If `docs_hint` is any other string, that string is used directly as
> +        # the HTML fragment identifier.
> +        #
> +        docs_hint:
> +          type: string
> +          anyOf:
> +            - const: config
> +            - pattern: '^\S+$'   # URI fragments cannot have spaces

[Severity: Low]
Can docs_hint accept '#' characters and produce malformed rationale URLs?

Because '#' is non-whitespace, '^\S+$' allows values like "#my-section",
which is an easy mistake given the "#config-drm" example above and causes
the checker to emit a double-hash URL ("##my-section").  Tightening the
pattern to '^[^\s#]+$' and noting to omit a leading '#' would prevent this.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=1

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 02/11] kconfig-audit: Introduce a PREEMPT_RT configuration policy
  2026-12-03 22:49 ` [PATCH v2 02/11] kconfig-audit: Introduce a PREEMPT_RT configuration policy Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 6 potential
issues to consider:
- [Low] kconfig-audit: dead docs_hint anchor for CONFIG_RCU_NOCB_CPU
- [Low] kconfig-audit: SPDX-License-Identifier placed on line 3 instead
  of line 1
- [Low] kconfig-audit: unanchored CONFIG_NO_HZ regex in preempt_rt.yml
  over-matches
- [Low] kconfig-audit: preempt_rt policy flags CONFIG_SLUB_DEBUG at high
  severity
- [Low] kconfig-audit: preempt_rt requires CONFIG_EFI_DISABLE_RUNTIME
  without EFI
- [Low] kconfig-audit: preempt_rt flags DEBUG_ALIGN_RODATA and
  DEBUG_MEMORY_INIT
--

commit 7aa69801eececedf40a26be60e739042d6c45696
Author: Ahmed S. Darwish <darwi@linutronix.de>

kconfig-audit: Introduce a PREEMPT_RT configuration policy

This commit adds a kconfig-audit policy file defining expected kernel
configuration options for PREEMPT_RT kernels, intended to stay aligned
with Documentation/core-api/real-time/kernel-configuration.rst.

> diff --git a/tools/kconfig-audit/policy/preempt_rt.yml b/tools/kconfig-audit/policy/preempt_rt.yml
> new file mode 100644
> index 0000000000000..a9972e3c34534
> --- /dev/null
> +++ b/tools/kconfig-audit/policy/preempt_rt.yml
> @@ -0,0 +1,179 @@
> +# PREEMPT_RT .config sanitization
> +#
> +# SPDX-License-Identifier: GPL-2.0-only

[Severity: Low]
Should SPDX-License-Identifier be on the first line of the file?

Documentation/process/license-rules.rst requires the SPDX tag on the first
comment line for non-shebang files, which checkpatch.pl and license checks
expect.

[ ... ]

> +  - name: CONFIG_EFI_DISABLE_RUNTIME
> +    expected: enabled
> +    severity: medium
> +    docs_hint: config

[Severity: Low]
Will requiring CONFIG_EFI_DISABLE_RUNTIME to be enabled cause false
positives on non-EFI builds?

CONFIG_EFI_DISABLE_RUNTIME depends on CONFIG_EFI in
drivers/firmware/efi/Kconfig, so it is absent from .config on non-EFI
targets.  Because audit.py flags missing symbols when expected is enabled,
non-EFI builds fail the audit even though EFI runtime services are gone.

> +
> +  - name_pattern: CONFIG_NO_HZ(_FULL|_IDLE)?
> +    expected: disabled
> +    severity: medium
> +    docs_hint: config-no-hz-config-no-hz-full

[Severity: Low]
Should this pattern be anchored as ^CONFIG_NO_HZ(_FULL|_IDLE)?$?

KernelConfig.get_matching_symbols() uses unanchored re.search(), so the
optional (_FULL|_IDLE)? suffix matches the empty string and the rule also
matches the hidden CONFIG_NO_HZ_COMMON symbol.  If a PolicyOverlay exempts
CONFIG_NO_HZ_FULL, CONFIG_NO_HZ_COMMON=y still fails the audit.

Similarly, the unanchored CONFIG_DEBUG pattern below has no trailing
underscore and also matches the hidden PowerPC CONFIG_DEBUGGER symbol.

[ ... ]

> +  - name: CONFIG_RCU_NOCB_CPU
> +    expected: enabled
> +    severity: low
> +    docs_hint: config

[Severity: Low]
Does docs_hint: config resolve to a dead link for CONFIG_RCU_NOCB_CPU?

With docs_url pointing to kernel-configuration.html, this generates
#config-rcu-nocb-cpu, but
Documentation/core-api/real-time/kernel-configuration.rst has no section
for CONFIG_RCU_NOCB_CPU.

Because CONFIG_RCU_NOCB_CPU defaults to n and depends on CONFIG_RCU_EXPERT
when CONFIG_NO_HZ_FULL is disabled, most configs will trigger this rule
with no working documentation link or inline rationale.

[ ... ]

> +  - name_pattern: CONFIG_DEBUG
> +    expected: disabled
> +    severity: medium
> +    docs_hint: kernel-debug-options

[Severity: Low]
Should CONFIG_DEBUG_ALIGN_RODATA and CONFIG_DEBUG_MEMORY_INIT have neutral
exemptions under this catch-all rule?

CONFIG_DEBUG_ALIGN_RODATA defaults to y on ARMv7 with STRICT_KERNEL_RWX
and only aligns .rodata in arch/arm/kernel/vmlinux.lds.S for NX hardening,
with zero runtime overhead.  Flagging it advises disabling a link-time
security feature on default ARMv7 PREEMPT_RT configs.

CONFIG_DEBUG_MEMORY_INIT is also preserved when enabling EXPERT and
PREEMPT_RT on top of standard defconfigs, and only compiles __init and
__meminit checks with no normal runtime RT latency impact.

[ ... ]

> +  - name_pattern: CONFIG_SLUB_DEBUG.*
> +    expected: disabled
> +    severity: high
> +    docs_hint: kernel-debug-options

[Severity: Low]
Should this high-severity rule target CONFIG_SLUB_DEBUG_ON rather than
matching CONFIG_SLUB_DEBUG as well?

CONFIG_SLUB_DEBUG defaults to y and is needed for /proc/slabinfo, while
runtime SLUB debug checks remain patched out behind slub_debug_enabled
unless CONFIG_SLUB_DEBUG_ON is set.  Flagging CONFIG_SLUB_DEBUG.* at high
severity fails standard PREEMPT_RT configs that keep SLUB debugging off.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=2

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 03/11] kconfig-audit: Add the configuration checker code
  2026-12-03 22:49 ` [PATCH v2 03/11] kconfig-audit: Add the configuration checker code Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [Medium] kconfig-audit: KernelConfigFile.parse() rejects unprefixed
  hex values
- [Medium] kconfig-audit: _find_pattern_rule_issues() suppresses
  missing-match errors
- [Medium] kconfig-audit: _map_pattern_rules() aborts on overridden
  pattern conflicts
- [Low] kconfig-audit: main() resolve() breaks /dev/stdin and pipe
  .config inputs
--

commit 0d8e21444fcb5c1a080849e8db605e829f900e3e
Author: Ahmed S. Darwish <darwi@linutronix.de>

kconfig-audit: Add the configuration checker code

This commit introduces tools/kconfig-audit/audit.py to parse kernel .config
files and YAML policies into an internal data model and report policy
violations by severity.

> diff --git a/tools/kconfig-audit/audit.py b/tools/kconfig-audit/audit.py
> new file mode 100755
> index 0000000000000..6ff4a56281ad2
> --- /dev/null
> +++ b/tools/kconfig-audit/audit.py

[ ... ]

> +            if val in ('y', 'm'):
> +                config.add_bool_symbol(name, True)
> +            elif re.fullmatch(r'0[xX][0-9a-fA-F]+', val):
> +                config.add_hex_symbol(name, int(val, 16))
> +            elif re.fullmatch(r'-?[0-9]+', val):
> +                config.add_int_symbol(name, int(val))
> +            elif len(val) >= 2 and val[0] == '"' and val[-1] == '"':
> +                config.add_str_symbol(name, val[1:-1])
> +            else:
> +                error(f'Invalid .config assignment: {line}', os.EX_DATAERR)

[Severity: Medium]
Does KernelConfigFile.parse() reject valid Kconfig hex values that omit the
0x prefix?

Kconfig's sym_string_valid() treats the 0x/0X prefix as optional for S_HEX
symbols, and print_symbol_for_dotconfig() writes them verbatim to .config.
An in-tree option like CONFIG_RADIO_GEMTEK_PORT=34c (from
drivers/media/radio/Kconfig) will fail to parse and abort with
os.EX_DATAERR.

Explicit disabled boolean assignments (CONFIG_FOO=n) are also rejected with
os.EX_DATAERR instead of being parsed as BooleanSymbol(name, False).

[ ... ]

> +    def _map_pattern_rules(self) -> PatternRuleMap:
> +        """Map each .config symbol to highest-priority matching pattern rule, if any"""
> +        pattern_map: dict[Symbol, PatternRule] = {}
> +
> +        for symbol in self.kconfig.symbols.values():
> +
> +            # No matching pattern rules for symbol
> +            rules = self.policy.get_pattern_rules_for(symbol.name)
> +            if not rules:
> +                continue
> +
> +            highest_prio = max(rule.pattern_prio for rule in rules)
> +            highest_prio_rules = [
> +                rule for rule in rules if rule.pattern_prio == highest_prio
> +            ]
> +
> +            if len(highest_prio_rules) > 1:
> +                patterns = '\n\t'.join(
> +                    rule.regex.pattern for rule in highest_prio_rules
> +                )
> +                error(
> +                    f'{symbol.name} is covered by multiple pattern rules with '
> +                    f'priority {highest_prio}:\n\t{patterns}',
> +                    os.EX_DATAERR,
> +                )

[Severity: Medium]
Should _map_pattern_rules() skip symbols that already have an exact
SymbolRule?

_find_pattern_rule_issues() gives exact symbol rules precedence over all
pattern rules and never consults pattern_rules_map for them.  Without
skipping those symbols here, a policy that resolves an overlap between two
equal-priority pattern rules via an exact SymbolRule still aborts with
os.EX_DATAERR.

[ ... ]

> +    def _find_pattern_rule_issues(self, rule: PatternRule) -> list[Issue]:
> +        """Check .config against a pattern rule and return any issues"""
> +        wrong_type_symbols: list[str] = []
> +        wrong_value_symbols: list[str] = []
> +
> +        matched_symbols = False
> +
> +        for symbol in self.kconfig.get_matching_symbols(rule.regex):
> +            # Record the regex symbol match before applying overrides
> +            matched_symbols = True
> +
> +            # An exact rule for symbol overrides all pattern rules
> +            if self.policy.get_symbol_rule(symbol.name):
> +                continue
> +
> +            # Higher-priority patterns overrides us
> +            if self.pattern_rules_map.get(symbol) is not rule:
> +                continue
> +
> +            if not isinstance(symbol, BooleanSymbol):
> +                wrong_type_symbols.append(symbol.name)
> +                continue
> +
> +            if Checker._expected_enabled(rule) != symbol.value:
> +                wrong_value_symbols.append(symbol.name)
> +                continue
> +
> +        issues: list[Issue] = []
> +
> +        if Checker._expected_enabled(rule) and not matched_symbols:
> +            if not self.policy.get_symbol_rule_matching(rule.regex):
> +                msg = 'does not match any enabled kconfig symbol'
> +                issues.append(self._make_regex_issue(rule, msg))

[Severity: Medium]
Can _find_pattern_rule_issues() silently pass an expected: enabled
PatternRule when zero matching symbols are enabled in .config?

matched_symbols is set to True before skipping symbols overridden by an
exact SymbolRule or a higher-priority PatternRule.  If .config only has
disabled entries that are overridden by a neutral or disabled rule, every
symbol is skipped and neither a PatternIssue nor a RegexIssue is reported.

Likewise, when no symbols in .config match rule.regex,
get_symbol_rule_matching() suppresses the RegexIssue if any matching
SymbolRule exists, even when that rule is expected: neutral or disabled.

[ ... ]

> +    kconfig_f = args.config.resolve()
> +    kconfig = KernelConfigFile(kconfig_f).parse()

[Severity: Low]
Will args.config.resolve() break piped inputs such as /dev/stdin or shell
process substitution like <(zcat /proc/config.gz)?

On Linux, /dev/fd/N for a pipe is a magic symlink whose readlink() target is
a pseudo-name like pipe:[123456], which Path.resolve() turns into a
nonexistent /proc/<pid>/fd/pipe:[...] path and makes
KernelConfigFile.__init__() fail with ENOENT.

Calling resolve() outside KernelConfigFile.__init__()'s OSError handler also
leaves symlink-loop errors uncaught instead of exiting with os.EX_NOINPUT.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=3

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 04/11] Documentation: Describe kconfig-audit usage and design
  2026-12-03 22:49 ` [PATCH v2 04/11] Documentation: Describe kconfig-audit usage and design Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 4 potential
issues to consider:
- [Low] docs: kconfig-audit exact-rule precedence contradicts
  _map_pattern_rules()
- [Low] docs: kconfig-audit enabled pattern rule misses zero-match
  failure
- [Low] docs: kconfig-audit Invocation section omits -P / --policy-file
  option
- [Low] docs: kconfig-audit omits duplicate name_pattern rule rejection
--

commit b13b53469deef91d63f2604f80547d95c6a4d51c
Author: Ahmed S. Darwish <darwi@linutronix.de>

Documentation: Describe kconfig-audit usage and design

This commit documents kconfig-audit usage, policy format, and dependencies,
links it from the PREEMPT_RT configuration guide, and references the new
documentation in the missing-dependency error message.

> diff --git a/Documentation/tools/kconfig-audit.rst b/Documentation/tools/kconfig-audit.rst
> new file mode 100644
> index 0000000000000..5b8e2fa842b1e
> --- /dev/null
> +++ b/Documentation/tools/kconfig-audit.rst
> @@ -0,0 +1,517 @@

[ ... ]

> +Check a ``.config`` against a policy known to the checker::
> +
> +   audit.py check -c path/to/.config -p preempt_rt

[Severity: Low]
Should this section also document -P / --policy-file?  parse_args() in
tools/kconfig-audit/audit.py supports checking against a custom policy
file, but this option is not mentioned anywhere in the document despite
the policy authoring guide below.

[ ... ]

> +Note that pattern priority conflicts are detected only for symbols present
> +in the checked ``.config``.  An exact ``name`` rule continues to take
> +precedence over all pattern rules for such symbols.

[Severity: Low]
Does this match Checker._map_pattern_rules() in
tools/kconfig-audit/audit.py?

Checker.__post_init__() calls _map_pattern_rules() before
_find_pattern_rule_issues() checks exact rule precedence.  When a symbol
in .config matches multiple highest-priority pattern rules, audit.py
aborts with EX_DATAERR even if an exact name rule covers that symbol.

Either _map_pattern_rules() should skip symbols covered by an exact rule,
or this note should reflect that conflicts are still rejected.

> +
> +Duplicate rules are rejected
> +----------------------------
> +
> +Duplicate exact symbol rules are rejected.  The policy below:

[Severity: Low]
Should this section also mention duplicate name_pattern rules?
Policy.add_rule() in tools/kconfig-audit/audit.py rejects identical
name_pattern strings at parse time with EX_DATAERR, even when they have
different pattern_prio values or match no symbols in .config.

[ ... ]

> +``enabled``
> +   The symbol must be set to ``y`` or ``m``.
> +
> +   For an exact ``name`` rule, a missing symbol fails an ``enabled`` rule.
> +   An explicitly unset symbol also fails.  For a ``name_pattern`` rule, the
> +   rule applies only to symbols matched in the checked ``.config``.

[Severity: Low]
Is this accurate for an enabled name_pattern rule that matches nothing in
.config?

In tools/kconfig-audit/audit.py, Checker._find_pattern_rule_issues()
reports an issue and exits with EX_CONFIG when an expected: enabled
pattern rule matches zero symbols in .config, unless an exact symbol rule
in the policy matches the regex.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=4

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 05/11] kconfig-audit: Split policy schema for component reuse
  2026-12-03 22:49 ` [PATCH v2 05/11] kconfig-audit: Split policy schema for component reuse Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Low] kconfig-audit: deprecated RefResolver in
  SchemaFile._create_validator()
- [Low] kconfig-audit: symlinked schemas break $ref in
  SchemaFile.parse()
- [Low] kconfig-audit: uncaught RefResolutionError in
  Helpers.validate_yaml()
--

commit 754cf81ebb9a7fce9acd73e9326b44ad0a081fd7
Author: Ahmed S. Darwish <darwi@linutronix.de>

kconfig-audit: Split policy schema for component reuse

This commit extracts the common rule schema into schema/rule.yml so
policy-v1.yml can reference it via $ref, and updates audit.py to build a
Draft7Validator with a local file:// RefResolver for sibling schema
files.

> diff --git a/tools/kconfig-audit/audit.py b/tools/kconfig-audit/audit.py
> index eac25740becab..94ff427715d11 100755
> --- a/tools/kconfig-audit/audit.py
> +++ b/tools/kconfig-audit/audit.py

[ ... ]

> @@ -249,12 +249,7 @@ class Helpers:
>      def validate_yaml(yaml: YamlDict, schema: Schema, f_name: str) -> None:
>          """Validate a parsed YAML mapping against passed JSON Schema"""
>          try:
> -            # For regex validation, manually enforce a format checker
> -            jsonschema.validate(
> -                yaml,
> -                schema,
> -                format_checker=jsonschema.FormatChecker(),
> -            )
> +            schema.validator.validate(yaml)
>          except jsonschema.exceptions.ValidationError as e:
>              error(
>                  f'{f_name} does not match its schema\n'

[Severity: Low]
Should validate_yaml() also catch jsonschema.exceptions.RefResolutionError?

Draft7Validator.check_schema() only validates metaschema grammar, so $ref
targets are resolved lazily during schema.validator.validate().  Because
RefResolutionError does not inherit from ValidationError, a broken $ref
escapes with a traceback and exit status 1 instead of os.EX_DATAERR.

[ ... ]

>      def parse(self) -> Schema:
>          """Parse and validate a policy schema file"""
>  
> -        schema = Schema(self.yaml)
> +        rule_schema_f = self.schema_f.parent / 'rule.yml'
> +        rule_schema_y = Helpers.load_yaml(rule_schema_f)
> +
> +        self._check_schema(rule_schema_f, rule_schema_y)
> +        self._check_schema(self.schema_f, self.schema_y)
> +
> +        validator = self._create_validator({
> +            rule_schema_f.resolve().as_uri(): rule_schema_y,
> +        })

[Severity: Low]
Can resolving rule_schema_f and self.schema_f independently break $ref
lookup when schema files are symlinked?

If policy-v1.yml or rule.yml is individually symlinked to a different
directory or basename (as in Nix or symlink-farm packaging), resolving
rule.yml relative to base_uri in _create_validator() will miss the
preloaded store key and fall back to remote loading, failing validation.

Resolving self.schema_f.parent once and deriving both URIs from that
directory would keep base_uri and the store keys aligned.

[ ... ]

> +    def _create_validator(self, store: dict[str, YamlDict]) -> YamlValidator:
> +        """Create a schema validator for resolving sibling '$ref' entries"""
> +
> +        resolver = jsonschema.RefResolver(
> +            base_uri=self.schema_f.resolve().as_uri(),
> +            referrer=self.schema_y,
> +            store=store,
> +        )
> +
> +        return jsonschema.Draft7Validator(
> +            self.schema_y,
> +            resolver=resolver,
> +            # For regex entries validation, manually enforce a format checker
> +            format_checker=jsonschema.FormatChecker(),
> +        )

[Severity: Low]
Will jsonschema.RefResolver and the resolver= argument emit deprecation
warnings on jsonschema >= 4.18.0?

Both were deprecated in favor of referencing.Registry passed via registry=.
Because audit.py runs as __main__, Python's default warning filter prints
both DeprecationWarning messages to stderr on every run, and fails under
python3 -W error or once jsonschema removes RefResolver.

Preferring referencing.Registry when available and falling back to
RefResolver for older jsonschema would avoid the warnings while keeping
compatibility.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=5

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 06/11] kconfig-audit: Introduce policy overlays schema
  2026-12-03 22:49 ` [PATCH v2 06/11] kconfig-audit: Introduce policy overlays schema Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Low] kconfig-audit: overlay schema accepts selector-only no-op rule
  entries
- [Low] kconfig-audit: policy-overlay-v1.yml title omits overlay
--

commit 58352cb3df2432252016c1d667a0a661fb223c7b
Author: Ahmed S. Darwish <darwi@linutronix.de>

kconfig-audit: Introduce policy overlays schema

This commit adds the JSON Schema for kconfig-audit policy overlay files,
reusing the shared rule definitions in rule.yml, and updates the neutral
rule description to mention overlays.

> diff --git a/tools/kconfig-audit/schema/policy-overlay-v1.yml b/tools/kconfig-audit/schema/policy-overlay-v1.yml
> new file mode 100644
> index 0000000000000..d95e9197a53c5
> --- /dev/null
> +++ b/tools/kconfig-audit/schema/policy-overlay-v1.yml
> @@ -0,0 +1,49 @@
> +# SPDX-License-Identifier: GPL-2.0-only
> +
> +"$schema": "https://json-schema.org/draft-07/schema#"
> +
> +title: kconfig-audit policy schema

[Severity: Low]
This title matches policy-v1.yml; should it be "kconfig-audit policy overlay
schema"?

[ ... ]

> +  rules:
> +    type: array
> +    minItems: 1
> +    items:
> +      allOf:
> +        - $ref: "rule.yml#/definitions/rule"

[Severity: Low]
Can an overlay rule entry pass validation with only name or name_pattern and
no override fields?

definitions.rule in rule.yml only requires name or name_pattern and leaves
all override fields optional.  Since audit.py relies on the schema rather
than re-validating during parsing, a selector-only rule (such as forgetting
expected: neutral) silently becomes a no-op against an existing base rule.

Adding minProperties: 2 alongside the rule $ref in allOf would reject
selector-only entries.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=6

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 07/11] kconfig-audit: Add support for policy overlays
  2026-12-03 22:49 ` [PATCH v2 07/11] kconfig-audit: Add support for policy overlays Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [Medium] kconfig-audit: PolicyOverlayFile and Overlayer silently drop
  pattern_prio
- [Low] kconfig-audit: Overlayer._update_rule() ignores empty rationale
  overrides
--

commit 77e7af9fe203f534d6486ee41fb9f2863605bc4c
Author: Ahmed S. Darwish <darwi@linutronix.de>

kconfig-audit: Add support for policy overlays

This commit adds policy overlay support to tools/kconfig-audit/audit.py,
allowing a YAML overlay file to override fields on existing rules, update
docs_url, or add new rules via the -o/--overlay option.

> diff --git a/tools/kconfig-audit/audit.py b/tools/kconfig-audit/audit.py
> index 94ff427715d11..ba6ba86f2791f 100755
> --- a/tools/kconfig-audit/audit.py
> +++ b/tools/kconfig-audit/audit.py

[ ... ]

> @@ -546,6 +551,195 @@ class PolicyFile(VersionedYamlFile):

[ ... ]

> +@dataclass
> +class RuleOverlay:
> +    """Typed overlay for a (symbol or regex) .config rule"""
> +
> +    target: OverlayTarget
> +    expected: Optional[ExpectedValue]
> +    severity: Optional[Severity]
> +    rationale: Optional[str]
> +    docs_hint: Optional[str]

[ ... ]

> +        return RuleOverlay(
> +            target,
> +            expected,
> +            severity,
> +            rule.get('rationale'),
> +            rule.get('docs_hint'),
> +        )

[Severity: Medium]
Does this silently drop pattern_prio from overlay rules?

policy-overlay-v1.yml allows pattern_prio on name_pattern rules via rule.yml,
but RuleOverlay has no pattern_prio field, PolicyOverlayFile._parse_rule()
ignores it, and Overlayer._update_rule() and Overlayer._new_rule() never
propagate it to PatternRule (leaving new rules at priority 0).

A new overlay pattern rule with a higher pattern_prio is downgraded to 0 and
can lose to a higher-priority base pattern rule, letting non-compliant configs
pass, or collide with a priority-0 base rule in Checker._map_pattern_rules()
and abort with os.EX_DATAERR.  Overrides on existing rules are also ignored.

[ ... ]

> +    @staticmethod
> +    def _update_rule(overlay: RuleOverlay, rule: Rule) -> None:
> +        """Apply an overlay's specified fields to an existing rule"""
> +        if overlay.expected:
> +            rule.expected = overlay.expected
> +
> +        if overlay.severity:
> +            rule.severity = overlay.severity
> +
> +        if overlay.rationale:
> +            rule.rationale = overlay.rationale
> +
> +        if overlay.docs_hint:
> +            rule.docs_hint = overlay.docs_hint
> +            rule._normalize_docs_hint()

[Severity: Low]
Should this check overlay.rationale is not None instead of testing truthiness?

rule.yml defines rationale as a string with no minimum length and rejects
null, so an empty string is the only schema-valid way to clear an inherited
rationale.  Because an empty string is falsy, the assignment is skipped and
the base rule's stale rationale remains in the audit report.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=7

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 08/11] Documentation: kconfig-audit: Describe policy overlays
  2026-12-03 22:49 ` [PATCH v2 08/11] Documentation: kconfig-audit: Describe " Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Medium] kconfig-audit: pattern_prio documented for overlays but
  ignored in audit.py
- [Low] Documentation: kconfig-audit: Rule fields intro contradicts
  overlay rules
- [Low] Documentation: kconfig-audit: docs_url global overlay override
  undocumented
--

commit 181019824e3f6389f3fdc27e65e9f5241c313cc3
Author: Ahmed S. Darwish <darwi@linutronix.de>

Documentation: kconfig-audit: Describe policy overlays

This commit documents the format, usage, and field reference for
kconfig-audit policy overlay files in Documentation/tools/kconfig-audit.rst.

> diff --git a/Documentation/tools/kconfig-audit.rst b/Documentation/tools/kconfig-audit.rst
> index 5b8e2fa842b1e..e83eb56e43ede 100644
> --- a/Documentation/tools/kconfig-audit.rst
> +++ b/Documentation/tools/kconfig-audit.rst

[ ... ]

> +Overriding an existing rule
> +---------------------------
> +
> +An overlay identifies an existing rule by its exact ``name`` or exact
> +``name_pattern`` string.  It changes only the fields it supplies.  Omitted
> +fields keep their values from the base policy.

[Severity: Medium]
Does policy overlay support actually honor pattern_prio on name_pattern
rules?

This section and the Policy files reference describe pattern_prio as
supported, and schema/policy-overlay-v1.yml accepts it.  In audit.py,
however, PolicyOverlayFile._parse_rule() drops pattern_prio and
Overlayer._update_rule() / _new_rule() never propagate it.

An overlay that sets pattern_prio to adjust precedence or add a
higher-priority neutral exemption therefore silently gets priority 0,
causing wrong rule precedence or ambiguous-policy errors in
Checker._map_pattern_rules().

Either audit.py should propagate pattern_prio for overlays, or the overlay
schema and documentation should reject and note that it is unsupported.

[ ... ]

> @@ -304,11 +402,16 @@ tag is supported so far::
>  ``kind``
>  ++++++++
>  
> -*Required*.  Identifies the YAML document's type.  For a configuration
> -policy file, the value must be::
> +*Required*.  Identifies the YAML document's type.
> +
> +For a configuration policy file, the value must be::
>  
>     Policy
>  
> +For a policy overlay file, the value must be::
> +
> +   PolicyOverlay
> +
>  ``docs_url``
>  ++++++++++++

[Severity: Low]
Should this section document how docs_url behaves in a PolicyOverlay file?

schema/policy-overlay-v1.yml accepts top-level docs_url in overlays, and
Overlayer.apply() replaces policy.docs_url with it.  Since
Policy.get_docs_url_for() prepends that single base URL to every rule's
docs_hint, setting it in an overlay rewrites links for all inherited rules.

[ ... ]

> @@ -408,10 +511,12 @@ an exact ``name`` rule.
>  ``expected``
>  ++++++++++++
>  
> -*Required*.  Describes the expected state of the matching symbol or
> -symbols.
> +*Required for all rules in policy files*.
> +
> +*Required for newly-added rules in policy overlays*.

[Severity: Low]
Does the Rule fields introduction above this section contradict the new
overlay requirements for expected and severity?

Policy files reference now covers both policy and overlay files, but the
Rule fields intro still states unconditionally that each rule must contain
one expected value and one severity, even though overlay overrides may omit
both.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=8

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 10/11] kconfig: Introduce auditconfig target
  2026-12-03 22:49 ` [PATCH v2 10/11] kconfig: Introduce auditconfig target Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 5 potential
issues to consider:
- [Low] kconfig: auditconfig pipeline masks audit.py startup and
  dependency failures
- [Low] kconfig: auditconfig validates POLICY with grep -qw instead of
  grep -Fxq --
- [Low] kconfig: relative OVERLAY paths fail under O= builds in
  auditconfig
- [Low] kconfig: auditconfig uses echo -n with newline-separated
  list-policies output
- [Low] kconfig: unresolved maintainer objection to auditconfig Makefile
  target
--

commit 6f54ed0a60b4e5e9fac14ed041af880ff3de56ee
Author: Ahmed S. Darwish <darwi@linutronix.de>

kconfig: Introduce auditconfig target

This commit adds an auditconfig Kbuild target in scripts/kconfig/Makefile
to check the current .config against a selected kconfig-audit policy and
optional overlay, and lists the target in make help.

> diff --git a/scripts/kconfig/Makefile b/scripts/kconfig/Makefile
> index 5baf1c44ffa25..b216761c534f8 100644
> --- a/scripts/kconfig/Makefile
> +++ b/scripts/kconfig/Makefile
> @@ -125,6 +125,28 @@ testconfig: $(obj)/conf
>  	$(if $(findstring 1,$(KBUILD_VERBOSE)),--capture=no)
>  clean-files += tests/.cache
>  
> +auditconfig := $(PYTHON3) -B $(srctree)/tools/kconfig-audit/audit.py
> +auditconfig_overlay = $(if $(OVERLAY),-o "$(OVERLAY)")

[Severity: Low]
Will a relative OVERLAY path work in out-of-tree O= builds?

The top-level Makefile re-invokes make with -C $(abs_output), so audit.py
opens OVERLAY relative to the output directory instead of the source or
invocation directory.  A relative path such as OVERLAY=my-overlay.yml then
fails with No such file or directory unless the file is inside the O= tree.

Canonicalizing OVERLAY before changing directories or falling back to
$(srctree)/$(OVERLAY) would handle this.

> +
> +list_auditconfig_rules =						\
> +	echo -n >&2 "Available POLICY: ";				\
> +	$(auditconfig) list-policies >&2;				\
> +	echo >&2

[Severity: Low]
Will echo -n misalign the policy list once more than one policy exists?

audit.py list-policies prints one policy name per line, so the first
policy appears inline after "Available POLICY: " while every subsequent
policy prints unindented at column 0.  Joining the output onto one line or
dropping -n would keep the formatting consistent.

> +
> +PHONY += auditconfig
> +auditconfig:
> +	$(Q)if [ -z "$(POLICY)" ]; then					\
> +		echo >&2 "Usage: make POLICY=<profile> [OVERLAY=<overlay>] auditconfig"; \
> +		$(list_auditconfig_rules);				\
> +		exit 2;							\
> +	fi
> +	$(Q)if ! $(auditconfig) list-policies | grep -qw "$(POLICY)"; then	\

[Severity: Low]
Should this use grep -Fxq -- "$(POLICY)" instead of grep -qw "$(POLICY)"?

Without -F, -x, and --, regex metacharacters like POLICY=preempt.rt or
leading-hyphen values like POLICY=--help bypass the Makefile check and
fall through to audit.py or produce grep errors, and -w would also match a
partial name if a policy stem contains a hyphen.

> +		echo >&2 "Unknown POLICY profile = $(POLICY)";		\
> +		$(list_auditconfig_rules);				\
> +		exit 2;							\
> +	fi

[Severity: Low]
Does this pipeline mask audit.py startup and dependency failures?

When PyYAML or jsonschema is missing, audit.py exits with os.EX_UNAVAILABLE
and empty stdout, which POSIX sh hides behind grep's exit status.  A valid
POLICY is then misreported as unknown, $(list_auditconfig_rules) runs
audit.py again glued onto "Available POLICY: ", and make exits 2.

Capturing "$(auditconfig) list-policies" before checking POLICY (or
letting audit.py validate POLICY directly) would preserve the failure.

> +	$(Q)$(auditconfig) check -c "$(KCONFIG_CONFIG)" -p "$(POLICY)" $(auditconfig_overlay)

[Severity: Low]
As reported by Nicolas Schier on v1 [1], is a top-level auditconfig make
target needed for a standalone tools/ script that does not use Kbuild?

Nicolas recommended keeping argument validation in the script and skipping
Makefile integration so new CLI options do not need to be mapped here.
audit.py already validates -p/--policy via argparse and adds
-P/--policy-file and list-api-versions, which this wrapper omits.

[1] https://lore.kernel.org/r/avQNfFbeoMImmtre@derry.ads.avm.de

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=10

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 11/11] Documentation: Describe auditconfig build target
  2026-12-03 22:49 ` [PATCH v2 11/11] Documentation: Describe auditconfig build target Ahmed S. Darwish
@ 2026-12-04 22:50   ` sashiko-bot
  0 siblings, 0 replies; 22+ messages in thread
From: sashiko-bot @ 2026-12-04 22:50 UTC (permalink / raw)
  To: Ahmed S. Darwish, Nathan Chancellor, Nicolas Schier, Julian Braha,
	Emanuele Rocca, Clark Williams, Steven Rostedt, Ingo Molnar
  Cc: Sebastian Andrzej Siewior, Frederic Weisbecker, John Ogness,
	Derek Barbosa, Zbigniew Jędrzejewski-Szmek, Daan De Meyer,
	Luca Boccassi, linux-rt-devel, debian-kernel, linux-kbuild,
	linux-kernel

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] Documentation: README.rst wrongly says auditconfig prints
  suggested changes
--

commit 26f60e3b3bb3f18437be7251e968b6c973b03400
Author: Ahmed S. Darwish <darwi@linutronix.de>

Documentation: Describe auditconfig build target

This commit documents the make auditconfig build target, its policy and
overlay arguments, and its diagnostic output in
Documentation/admin-guide/README.rst, and adds a cross-reference in
Documentation/tools/kconfig-audit.rst.

> diff --git a/Documentation/admin-guide/README.rst b/Documentation/admin-guide/README.rst
> index 77fec1de6dc86..6f78988d4005c 100644
> --- a/Documentation/admin-guide/README.rst
> +++ b/Documentation/admin-guide/README.rst
> @@ -256,6 +256,35 @@ Configuring the kernel

[ ... ]

> +``auditconfig`` reports kconfig options whose values do not match the
> +selected rules profile. Each diagnostic includes a severity, such as
> +``FATAL`` or ``INFO``, plus the suggested configuration change.
> +
> +Apply the reported changes as needed and run ``make auditconfig`` again,
> +against the same rules, until no relevant diagnostics remain.

[Severity: Low]
Does auditconfig actually print a suggested configuration change?

In tools/kconfig-audit/audit.py, Report.print() and
Checker._find_symbol_rule_issues() only report the severity, the observed
mismatch (such as "is disabled" or "has the wrong type, expected boolean"),
and an optional rationale or documentation link.

For wrong-type symbols, the output does not even state whether the rule
expects the symbol to be enabled or disabled, so users do not get a
suggested change to apply.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203224916.118064-1-darwi@linutronix.de?part=11

^ permalink raw reply	[flat|nested] 22+ messages in thread

end of thread, other threads:[~2026-12-04 22:50 UTC | newest]

Thread overview: 22+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-03 22:49 [PATCH v2 00/11] tools: Introduce a kernel configuration checker Ahmed S. Darwish
2026-12-03 22:49 ` [PATCH v2 01/11] kconfig-audit: Add schema for policy files Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot
2026-12-03 22:49 ` [PATCH v2 02/11] kconfig-audit: Introduce a PREEMPT_RT configuration policy Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot
2026-12-03 22:49 ` [PATCH v2 03/11] kconfig-audit: Add the configuration checker code Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot
2026-12-03 22:49 ` [PATCH v2 04/11] Documentation: Describe kconfig-audit usage and design Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot
2026-12-03 22:49 ` [PATCH v2 05/11] kconfig-audit: Split policy schema for component reuse Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot
2026-12-03 22:49 ` [PATCH v2 06/11] kconfig-audit: Introduce policy overlays schema Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot
2026-12-03 22:49 ` [PATCH v2 07/11] kconfig-audit: Add support for policy overlays Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot
2026-12-03 22:49 ` [PATCH v2 08/11] Documentation: kconfig-audit: Describe " Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot
2026-12-03 22:49 ` [PATCH v2 09/11] MAINTAINERS: Add entry for kernel configuration audit Ahmed S. Darwish
2026-12-03 22:49 ` [PATCH v2 10/11] kconfig: Introduce auditconfig target Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot
2026-12-03 22:49 ` [PATCH v2 11/11] Documentation: Describe auditconfig build target Ahmed S. Darwish
2026-12-04 22:50   ` sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox