tools: Introduce a kernel configuration checker
Subsystems (4)
cover tools: Introduce a kernel configuration checker
Hi,
A month ago in Prague I proposed a kernel configuration checker:
PREEMPT_RT configuration: Best practices with kconfig-checker
https://youtu.be/hqnOmdpGBdQ
This series adds kconfig-checker: a Python tool that checks the kernel .config against a set of YAML rules and reports all issues by severity.
The series also adds:
- a PREEMPT_RT configuration ruleset
- a make checkconfig target
- support for ruleset overlays
Example:
$ make defconfig
$ ./tools/kconfig-checker/check.py check -c .config -r preempt_rt 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 = HIGH
=========================================
* CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE is unset
* Below options are set:
CONFIG_SLUB_DEBUG
Rationale:
https://docs.kernel.org/core-api/real-time/kernel-configuration.html#kernel-debug-options
Configuration Issues with severity = MEDIUM
===========================================
* Below options are set:
CONFIG_CPU_FREQ_GOV_USERSPACE
CONFIG_CPU_FREQ_GOV_ONDEMAND
### ...
### More output
### ...
The same check can be run through make:
$ make RULES=preempt_rt checkconfig
If no ruleset is specified, the target prints the available rulesets:
$ make checkconfig
Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig
Available RULES: preempt_rtThe overlay mechanism allows distributions, CI systems, and Board Support Packages to apply additional policy or override existing mainline rules.
For example:
$ ./tools/kconfig-checker/check.py check \
-c path/to/.config \
-r preempt_rt \
-o path/to/overlay.ymlor:
$ make RULES=preempt_rt OVERLAY=path/to/overlay.yml checkconfig
Patch 09/10 documents the overlay format and gives an example use case.
My goal is to get this into the kernel and have Debian's PREEMPT_RT kernel packaging to use it. I'd also like systemd to use it: its README lists 60 kernel CONFIG_* symbols with different requirements severity.
Thank you!
Ahmed
8<-----
Ahmed S. Darwish (10):
kconfig-checker: Add schema for rule files
kconfig-checker: Introduce PREEMPT_RT configuration rules
kconfig-checker: Add the configuration checker code
kconfig: Introduce checkconfig target
Documentation: Describe kconfig-checker usage and design
kconfig-checker: Split schema to support component reuse
kconfig-checker: Introduce overlays schema
kconfig-checker: Add support for rule overlays
Documentation: Describe kconfig-checker overlays
kconfig: Introduce OVERLAY= for make checkconfig
Documentation/admin-guide/README.rst | 29 + .../real-time/kernel-configuration.rst | 3 + Documentation/tools/index.rst | 1 + Documentation/tools/kconfig_checker.rst | 101 +++ scripts/kconfig/Makefile | 25 + tools/kconfig-checker/check.py | 686 ++++++++++++++++++ tools/kconfig-checker/rules/preempt_rt.yml | 169 +++++ tools/kconfig-checker/schemas/base.yml | 114 +++ tools/kconfig-checker/schemas/overlay.yml | 28 + tools/kconfig-checker/schemas/rules.yml | 20 + 10 files changed, 1176 insertions(+)
create mode 100644 Documentation/tools/kconfig_checker.rst create mode 100755 tools/kconfig-checker/check.py create mode 100644 tools/kconfig-checker/rules/preempt_rt.yml create mode 100644 tools/kconfig-checker/schemas/base.yml create mode 100644 tools/kconfig-checker/schemas/overlay.yml create mode 100644 tools/kconfig-checker/schemas/rules.yml
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
Signature · 1 line
2.56.0
PATCH 1/10 kconfig-checker: Add schema for rule files
The kconfig-checker YAML rule files describes which kernel .config symbols are expected to be enabled or disabled. Introduce a schema for such files.
Describe and add rational for each element in the schema as well.
--- tools/kconfig-checker/schema.yml | 115 +++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 tools/kconfig-checker/schema.yml
tools/kconfig-checker/schema.yml new file +115 -0
@@ -0,0 +1,115 @@ +# SPDX-License-Identifier: GPL-2.0-only + +"$schema": "https://json-schema.org/draft-07/schema" + +title: Schema for kconfig-checker rule files +type: object +required: [rules] +additionalProperties: false + +properties: + # + # 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] + 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 + + # + # Expected value for the matching kernel configuration option. + # + # Values: + # + # y option is expected to be enabled (built-in or module). + # n option is expected to be disabled or unset. + # allowed option is permitted and must not be reported as a violation. + # This is used to exempt a specific symbol from a broader + # `name_pattern` rule with `expected: n`. + # + expected: + type: string + enum: [y, n, allowed] + + # + # 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: n + # 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
Signature · 1 line
2.56.0
Julian Braha
reviewerRe: [PATCH v1 01/10] kconfig-checker: Add schema for rule files
Quoted 61 lines · Ahmed S. Darwish
The kconfig-checker YAML rule files describes which kernel .config symbols are expected to be enabled or disabled. Introduce a schema for such files.
Describe and add rational for each element in the schema as well.
Signed-off-by Ahmed S. Darwish <[email protected]>--- tools/kconfig-checker/schema.yml | 115 +++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 tools/kconfig-checker/schema.ymltools/kconfig-checker/schema.yml new file +44
-0@@ -0,0 +1,115 @@ +# SPDX-License-Identifier: GPL-2.0-only + +"$schema": "https://json-schema.org/draft-07/schema" + +title: Schema for kconfig-checker rule files +type: object +required: [rules] +additionalProperties: false + +properties: + # + # 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] + 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_.* + #
tools/kconfig-checker/schema.yml line 54
Quoted 10 lines
tools/kconfig-checker/schema.yml new file +10
-0+ name_pattern: + type: string + format: regex + + # + # Expected value for the matching kernel configuration option. + # + # Values: + # + # y option is expected to be enabled (built-in or module).
Kconfig's tristates use 3-state logic. It seems like you're approximating 'm' as 'y'?
These are meaningfully different values :/
tools/kconfig-checker/schema.yml line 62
Quoted 8 lines
tools/kconfig-checker/schema.yml new file +8
-0+ # n option is expected to be disabled or unset. + # allowed option is permitted and must not be reported as a violation. + # This is used to exempt a specific symbol from a broader + # `name_pattern` rule with `expected: n`. + # + expected: + type: string + enum: [y, n, allowed]
What if a user wants to specify that the value can be 'n' or 'y', but not 'm'?
- Julian Braha
Re: [PATCH v1 01/10] kconfig-checker: Add schema for rule files
Hi Julian,
Thanks for all the feedback!
Quoted 5 lines · Julian Braha
Quoted 3 lines · Ahmed S. Darwish
tools/kconfig-checker/schema.yml new file +0
-0
...
Quoted 11 lines
tools/kconfig-checker/schema.yml line 54
Quoted 7 lines
tools/kconfig-checker/schema.yml new file +7
-0+ + # + # Expected value for the matching kernel configuration option. + # + # Values: + # + # y option is expected to be enabled (built-in or module).Kconfig's tristates use 3-state logic. It seems like you're approximating 'm' as 'y'?
You're correct.
'y' is deceiving, even with the comment beside it saying that it implies either a built-in or a module.
I guess it would be better to have the expected values like:
expected:
type: string
enum: [enabled, disabled, allowed]
As a bonus, 'enabled' and 'disabled' rhymes well with 'allowed'.
So the policies can be:
- name: CONFIG_PREEMPT_RT
expected: enabled
... - name: CONFIG_NO_HZ_FULL
expected: disabled
... - name: CONFIG_DEBUG_FS
expected: allowed
...I think that's much cleaner.
Quoted 1 line
These are meaningfully different values :/
I wrote some policies beside the PREEMPT_RT one, and the main requirement was always that a certain kernel feature is either enabled or disabled.
In the future, I can add;
expected:
type: string
enum: [enabled, disabled, allowed, builtin-only, module]
But so far, there was no need for that.
Quoted 11 lines
tools/kconfig-checker/schema.yml line 62
Quoted 8 lines
tools/kconfig-checker/schema.yml new file +8
-0+ # n option is expected to be disabled or unset. + # allowed option is permitted and must not be reported as a violation. + # This is used to exempt a specific symbol from a broader + # `name_pattern` rule with `expected: n`. + # + expected: + type: string + enum: [y, n, allowed]What if a user wants to specify that the value can be 'n' or 'y', but not 'm'?
Is this a real-world use case?
I did not encounter a need for making the expected values that complex before.
Thanks!
--
Ahmed S. Darwish
Linutronix GmbH
PATCH 2/10 kconfig-checker: Introduce PREEMPT_RT configuration rules
In reply to Ahmed S. DarwishIntroduce a kconfig-checker PREEMPT_RT rules file, matching what is at Documentation/core-api/real-time/kernel-configuration.rst.
This will allow the tool to mechanically check the kernel's .config at a later step.
--- tools/kconfig-checker/rules/preempt_rt.yml | 169 +++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 tools/kconfig-checker/rules/preempt_rt.yml
tools/kconfig-checker/rules/preempt_rt.yml new file +169 -0
@@ -0,0 +1,169 @@ +# PREEMPT_RT .config sanitization +# +# SPDX-License-Identifier: GPL-2.0-only +# +# List all config options in alphabetic order, per group +--- + +docs_url: https://docs.kernel.org/core-api/real-time/kernel-configuration.html +rules: + - name: CONFIG_CPU_FREQ + expected: y + severity: high + docs_hint: config + + - name: CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE + expected: y + severity: high + docs_hint: config + + - name_pattern: CONFIG_CPU_FREQ_GOV_(CONSERVATIVE|ONDEMAND|POWERSAVE|USERSPACE) + expected: n + severity: medium + docs_hint: non-performance-cpu-frequency-governors + + - name: CONFIG_CPU_FREQ_GOV_SCHEDUTIL + expected: n + severity: medium + docs_hint: non-performance-cpu-frequency-governors + + - name: CONFIG_CPU_IDLE + expected: y + severity: info + docs_hint: config + + - name: CONFIG_DRM + expected: n + severity: info + docs_hint: config + + - name: CONFIG_EFI_DISABLE_RUNTIME + expected: y + severity: medium + docs_hint: config + + - name: CONFIG_NO_HZ + expected: n + severity: medium + docs_hint: config-no-hz-config-no-hz-full + + - name: CONFIG_NO_HZ_FULL + expected: n + severity: medium + docs_hint: config-no-hz-config-no-hz-full + + - name: CONFIG_PREEMPT_RT + expected: y + severity: fatal + docs_hint: config + + # + # Tracing + # + + - name: CONFIG_DYNAMIC_FTRACE + expected: y + severity: info + docs_hint: config-tracing-and-tracing-options + + - name: CONFIG_FUNCTION_GRAPH_TRACER + expected: y + severity: info + docs_hint: config-tracing-and-tracing-options + + - name: CONFIG_HWLAT_TRACER + expected: y + severity: info + docs_hint: config-tracing-and-tracing-options + + - name: CONFIG_IRQSOFF_TRACER + expected: n + severity: high + docs_hint: config-irqsoff-tracer-and-config-preempt-tracer + + - name: CONFIG_KPROBE_EVENTS + expected: y + severity: info + docs_hint: config-tracing-and-tracing-options + + - name: CONFIG_PREEMPT_TRACER + expected: n + severity: high + docs_hint: config-irqsoff-tracer-and-config-preempt-tracer + + - name: CONFIG_SCHED_TRACER + expected: y + severity: info + docs_hint: config-tracing-and-tracing-options + + - name: CONFIG_TRACING + expected: y + severity: info + docs_hint: config-tracing-and-tracing-options + + - name: CONFIG_UPROBE_EVENTS + expected: y + severity: info + docs_hint: config-tracing-and-tracing-options + + # + # Debugging + # + + - name_pattern: CONFIG_DEBUG_.* + expected: n + severity: medium + docs_hint: kernel-debug-options + + - name: CONFIG_DEBUG_ATOMIC_SLEEP + expected: allowed + severity: low + + - name: CONFIG_DEBUG_BOOT_PARAMS + expected: allowed + severity: low + + - name: CONFIG_DEBUG_BUGVERBOSE + expected: allowed + severity: low + + - name: CONFIG_DEBUG_FS + expected: allowed + severity: low + + - name: CONFIG_DEBUG_FS_ALLOW_ALL + expected: allowed + severity: low + + - name: CONFIG_DEBUG_INFO + expected: allowed + severity: low + + - name: CONFIG_DEBUG_INFO_NONE + expected: allowed + severity: low + + - name: CONFIG_DEBUG_KERNEL + expected: allowed + severity: low + + - name: CONFIG_DEBUG_MISC + expected: allowed + severity: low + rationale: + A menu option which enables the display of other debug symbols. + + - name: CONFIG_LOCKUP_DETECTOR + expected: n + severity: high + docs_hint: config + + - name: CONFIG_PROVE_LOCKING + expected: n + severity: high + docs_hint: config + + - name_pattern: CONFIG_SLUB_DEBUG.* + expected: n + severity: high + docs_hint: kernel-debug-options
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v1 02/10] kconfig-checker: Introduce PREEMPT_RT configuration rules
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] kconfig-checker: incomplete CONFIG_DEBUG_INFO and CONFIG_DEBUG_FS exemptions - [Medium]…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] kconfig-checker: incomplete CONFIG_DEBUG_INFO and CONFIG_DEBUG_FS exemptions
- [Medium] kconfig-checker: missing CONFIG_NO_HZ_IDLE rule in preempt_rt.yml
- [Low] kconfig-checker: wrong rationale and exemption for CONFIG_DEBUG_MISC
--
commit e938c2a281eebdc8d9e5b3bc80f568d54980b699
Author: Ahmed S. Darwish <[email protected]>
kconfig-checker: Introduce PREEMPT_RT configuration rules
This commit adds a PREEMPT_RT configuration rules file for kconfig-checker based on the real-time kernel configuration documentation.
Quoted 5 lines
tools/kconfig-checker/rules/preempt_rt.yml new file +0
-0
[ ... ]
tools/kconfig-checker/rules/preempt_rt.yml line 53
Quoted 9 lines
tools/kconfig-checker/rules/preempt_rt.yml new file +9
-0+ - name: CONFIG_NO_HZ + expected: n + severity: medium + docs_hint: config-no-hz-config-no-hz-full + + - name: CONFIG_NO_HZ_FULL + expected: n + severity: medium + docs_hint: config-no-hz-config-no-hz-full
[Severity: Medium]
Should this also check CONFIG_NO_HZ_IDLE?
In kernel/time/Kconfig, CONFIG_NO_HZ is only a legacy compatibility symbol used as a default hint, while the active "Timer tick handling" choice symbol for tickless idle is CONFIG_NO_HZ_IDLE (which selects CONFIG_NO_HZ_COMMON without setting CONFIG_NO_HZ). A .config that selects CONFIG_NO_HZ_IDLE=y with CONFIG_NO_HZ unset will pass kconfig-checker without reporting that tickless idle is enabled.
[ ... ]
Quoted 8 lines
tools/kconfig-checker/rules/preempt_rt.yml new file +8
-0+ # + # Debugging + # + + - name_pattern: CONFIG_DEBUG_.* + expected: n + severity: medium + docs_hint: kernel-debug-options
[ ... ]
Quoted 5 lines
tools/kconfig-checker/rules/preempt_rt.yml new file +5
-0+ - name: CONFIG_DEBUG_FS + expected: allowed + severity: low + + - name: CONFIG_DEBUG_FS_ALLOW_ALL
tools/kconfig-checker/rules/preempt_rt.yml line 144
Quoted 10 lines
tools/kconfig-checker/rules/preempt_rt.yml new file +10
-0+ expected: allowed + severity: low + + - name: CONFIG_DEBUG_INFO + expected: allowed + severity: low + + - name: CONFIG_DEBUG_INFO_NONE + expected: allowed + severity: low
[Severity: Medium]
Will any .config with CONFIG_DEBUG_INFO=y or CONFIG_DEBUG_FS_ALLOW_NONE=y still fail against the CONFIG_DEBUG_.* pattern rule?
In lib/Kconfig.debug, CONFIG_DEBUG_INFO is a promptless bool selected by the mandatory DWARF version choice (such as CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT) and forces a mandatory compression choice (such as CONFIG_DEBUG_INFO_COMPRESSED_NONE). Because only the exact symbols CONFIG_DEBUG_INFO and CONFIG_DEBUG_INFO_NONE are exempted here (whereas Documentation/core-api/real-time/kernel-configuration.rst allows the wildcard CONFIG_DEBUG_INFO*), enabling CONFIG_DEBUG_INFO=y always leaves companion CONFIG_DEBUG_INFO_* symbols that trigger medium-severity violations under CONFIG_DEBUG_.*.
Similarly, enabling CONFIG_DEBUG_FS=y requires choosing either CONFIG_DEBUG_FS_ALLOW_ALL or CONFIG_DEBUG_FS_ALLOW_NONE, so omitting CONFIG_DEBUG_FS_ALLOW_NONE flags the more restrictive debugfs access mode as a violation.
tools/kconfig-checker/rules/preempt_rt.yml line 154
Quoted 9 lines
tools/kconfig-checker/rules/preempt_rt.yml new file +9
-0+ - name: CONFIG_DEBUG_KERNEL + expected: allowed + severity: low + + - name: CONFIG_DEBUG_MISC + expected: allowed + severity: low + rationale: + A menu option which enables the display of other debug symbols.
[Severity: Low]
Is this rationale meant for CONFIG_DEBUG_KERNEL rather than CONFIG_DEBUG_MISC?
In lib/Kconfig.debug, CONFIG_DEBUG_KERNEL is the menu option that gates other debug options (and is listed as allowed in Documentation/core-api/real-time/kernel-configuration.rst), whereas CONFIG_DEBUG_MISC enables miscellaneous runtime debug checks in the kernel and is not listed as allowed in the documentation.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Re: [PATCH v1 02/10] kconfig-checker: Introduce PREEMPT_RT configuration rules
Quoted 4 lines · On Sat, 07 Nov 2026, [email protected] wrote:
[Severity: Medium]
Should this also checkCONFIG_NO_HZ_IDLE?
Correct, it should be added, as legacy "compatible" CONFIG_NO_HZ might be removed in the future.
Quoted 5 lines
[Severity: Medium]
Will any .config withCONFIG_DEBUG_INFO=yorCONFIG_DEBUG_FS_ALLOW_NONE=ystill fail against the CONFIG_DEBUG_.* pattern rule?
Correct, both CONFIG_DEBUG_FS_ALLOW_NONE and CONFIG_DEBUG_INFO.* should be handled.
Quoted 5 lines
[Severity: Low]
Is this rationale meant forCONFIG_DEBUG_KERNELrather thanCONFIG_DEBUG_MISC?
Correct!
Thanks,
Ahmed
Re: [PATCH v1 02/10] kconfig-checker: Introduce PREEMPT_RT configuration rules
In reply to Ahmed S. DarwishHi Ahmed,
thanks for this useful tool!
tools/kconfig-checker/rules/preempt_rt.yml line 18
Quoted 4 lines · Ahmed S. Darwish
tools/kconfig-checker/rules/preempt_rt.yml new file +4
-0+ - name: CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE + expected: y + severity: high + docs_hint: config
The docs mention the following for CPU_FREQ_DEFAULT_GOV_PERFORMANCE:
| This is not an absolute rule. Some setups might prefer to clock the | CPU to lower speeds due to thermal packaging or other requirements. The | key is that the CPU frequency remains constant once set.
Yet having the rule "severity: high" will presumably make kconfig-checker require CPU_FREQ_DEFAULT_GOV_PERFORMANCE=y in order for validation to pass?
tools/kconfig-checker/rules/preempt_rt.yml line 23
Quoted 4 lines
tools/kconfig-checker/rules/preempt_rt.yml new file +4
-0+ - name_pattern: CONFIG_CPU_FREQ_GOV_(CONSERVATIVE|ONDEMAND|POWERSAVE|USERSPACE) + expected: n + severity: medium + docs_hint: non-performance-cpu-frequency-governors
Similarly, by reading your docs, it seems to me that the worst choice for RT workloads is ONDEMAND.
| The ONDEMAND governor should not be enabled on a real-time system. Its | frequency changes depend on workload behavior and can significantly harm | determinism.
Shouldn't the severity for the CPU_FREQ_GOV_ONDEMAND rule be higher, then?
Re: [PATCH v1 02/10] kconfig-checker: Introduce PREEMPT_RT configuration rules
Hi Emanuele,
Quoted 3 lines · Emanuele Rocca
thanks for this useful tool!
Thanks!
Quoted 7 lines
tools/kconfig-checker/rules/preempt_rt.yml line 18
Quoted 4 lines
tools/kconfig-checker/rules/preempt_rt.yml new file +4
-0+ - name: CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE + expected: y + severity: high + docs_hint: configThe docs mention the following for
CPU_FREQ_DEFAULT_GOV_PERFORMANCE:
Quoted 8 lines
| This is not an absolute rule. Some setups might prefer to clock the | CPU to lower speeds due to thermal packaging or other requirements. The | key is that the CPU frequency remains constant once set.Yet having the rule "severity: high" will presumably make kconfig-checker require CPU_FREQ_DEFAULT_GOV_PERFORMANCE=y in order for validation to pass?
Yeah, the expectation is that the RT policy profile recommends the "absolute best" kind of configuration. If the system integrators knows what they are doing, then they can override that setting in a rule overlay and explain their rationale there.
Quoted 8 lines
tools/kconfig-checker/rules/preempt_rt.yml line 23
Quoted 4 lines
tools/kconfig-checker/rules/preempt_rt.yml new file +4
-0+ - name_pattern: CONFIG_CPU_FREQ_GOV_(CONSERVATIVE|ONDEMAND|POWERSAVE|USERSPACE) + expected: n + severity: medium + docs_hint: non-performance-cpu-frequency-governorsSimilarly, by reading your docs, it seems to me that the worst choice for RT workloads is ONDEMAND.
Quoted 6 lines
| The ONDEMAND governor should not be enabled on a real-time system. Its | frequency changes depend on workload behavior and can significantly harm | determinism.Shouldn't the severity for the
CPU_FREQ_GOV_ONDEMANDrule be higher, then?
That's a very good point, thanks! I'll separate the recommendations severity into:
- CONSERVATIVE and ONDEMAND: these are the worst, as they do change the frequency during the system's lifetime. Thus, rule severity is high.
- POWERSAVE: Frequency is low, but it does not change during the system lifetime. Thus, rule severity is medium.
- USERSPACE: Fine if the user-space program that knows what it's doing and does not switch frequencies haphazardly. Thus, rule severity is medium as well.
Sounds good?
--
Kind regards,
Ahmed S. Darwish
Linutronix GmbH
PATCH 3/10 kconfig-checker: Add the configuration checker code
In reply to Ahmed S. DarwishIntroduce a kernel configuration checker.
Validate the passed kernel .config against a YAML rules file and report problematic configuration issues 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.
Create a proper Python objects data model for the kconfig checker to work with. Confine all direct YAML dictionary access to YAML files loading, validation, and data model construction.
Document the tool's development rules on top.
--- tools/kconfig-checker/check.py | 558 +++++++++++++++++++++++++++++++++ 1 file changed, 558 insertions(+) create mode 100755 tools/kconfig-checker/check.py
tools/kconfig-checker/check.py new file +558 -0
@@ -0,0 +1,558 @@ +#!/usr/bin/env python3 +# +# SPDX-License-Identifier: GPL-2.0-only +# +# Kernel .config checker +# +# Main usage: +# +# $ check.py list-rules +# $ check.py check -c path/to/linux/.config -r preempt_rt +# +# Notes: +# +# - All code is to be fully type-annotated. Before introducing changes, +# please verify type-safety using: +# +# $ mypy --strict --no-warn-return-any check.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. +# +# - The YAML rule files are only treated as a serialization format. After +# loading and schema validation, such rules are parsed into an internal +# data model: Severity, Rule, SymbolRule, PatternRule, Rules, and other +# related python objects. +# +# All checker logic must operate on that typed model, and not on the raw +# YAML dictionaries. +# +# - Minimize external dependencies: this tool is also intended to be run +# from distribution kernel-package scripts in the future. +# +# Script exit codes: +# +# os.EX_CONFIG passed kernel .config does not match rules +# 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 +from enum import Enum, auto +from pathlib import Path +from typing import Any, NoReturn, Optional + +# +# Initial sanity checks: +# + +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) + +# +# Actual script: +# + +class KernelConfig: + """.config file parser""" + + def __init__(self, file: Path): + try: + self.lines = file.read_text().splitlines() + except OSError as e: + error(f'Could not open {file}: {e.strerror}', os.EX_NOINPUT) + + self.symbols = self._parse_symbols() + + def _parse_symbols(self) -> dict[str, str]: + """Extract CONFIG_* symbol assignments from .config""" + symbol_set = re.compile(r'^(CONFIG_[A-Za-z0-9_]+)=([ym])$') + symbol_unset = re.compile(r'^# (CONFIG_[A-Za-z0-9_]+) is not set$') + + symbols: dict[str, str] = {} + for line in self.lines: + line = line.rstrip('\n') + + if m := symbol_set.match(line): + symbols[m.group(1)] = m.group(2) + continue + + if m := symbol_unset.match(line): + symbols[m.group(1)] = 'n' + + return symbols + + def get_symbol_value(self, sym_name: str) -> Optional[str]: + """Return a .config symbol value: 'y', 'm', or 'n'""" + return self.symbols.get(sym_name) + + def get_matching_symbols(self, pa: re.Pattern[str]) -> list[str]: + """Get all CONFIG_* symbol names matching passed regex""" + return [ sym for sym in self.symbols if pa.search(sym) ] + +YamlDict = dict[str, Any] + +class Helpers: + """YAML file access helpers""" + + @staticmethod + def load_yaml(yaml_f: Path) -> YamlDict: + try: + with open(yaml_f, 'r') as f: + return yaml_m.safe_load(f) + except OSError as e: + error(f'Could not open {yaml_f}: {e.strerror}', os.EX_NOINPUT) + except yaml_m.YAMLError as e: + error(f'Invalid YAML syntax at {yaml_f}:\n {e}', os.EX_DATAERR) + + @staticmethod + def validate_yaml(yaml: YamlDict, schema: YamlDict, f_name: str) -> None: + try: + jsonschema.validate(yaml, schema) + except jsonschema.exceptions.ValidationError as e: + error( + f'{f_name} does not match its schema\n' + f'Reason: {e.message}', + os.EX_DATAERR + ) + +class Schema: + """Rules file schema, in json-schema.org format""" + + def __init__(self, schema_f: Path): + self.schema = Helpers.load_yaml(schema_f) + # Validate the schema itself against draft-07 metaschema + jsonschema.Draft7Validator.check_schema(self.schema) + + def as_dict(self) -> YamlDict: + return self.schema + +class ExpectedValue(Enum): + """Expected values for a .config symbol""" + + y = auto() # 'y' implies a built-in or a module; as in schema + n = auto() + allowed = auto() + +class Severity(Enum): + """Rule-check severity""" + + fatal = auto() + high = auto() + medium = auto() + low = auto() + info = auto() + +class Rule: + """Single rule entry""" + + expected: ExpectedValue + severity: Severity + rationale: Optional[str] = None + docs_hint: Optional[str] = None + + def __init__(self, rule: YamlDict) -> None: + self.expected = ExpectedValue[rule['expected']] + self.severity = Severity[rule['severity']] + self.rationale = rule.get('rationale') + self.docs_hint = rule.get('docs_hint') + 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 + +class SymbolRule(Rule): + """Rule entry for one .config symbol""" + + symbol: str + + def __init__(self, rule: YamlDict): + self.symbol = rule['name'] + super().__init__(rule) + + 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() + +class PatternRule(Rule): + """Rule entry for a regex pattern of .config symbols""" + + symbol_regex: re.Pattern[str] + + def __init__(self, rule: YamlDict): + regex = rule['name_pattern'] + try: + self.symbol_regex = re.compile(regex) + except re.error as e: + error(f'Invalid symbol regex {regex}: {e}', os.EX_DATAERR) + + super().__init__(rule) + +@dataclass +class Rules: + """The .config checker rules repository / data model""" + + rules: list[Rule] + 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.symbol_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 .config symbol, if any""" + for rule in self.rules: + if isinstance(rule, PatternRule): + if rule.symbol_regex.pattern == pattern: + return rule + + return None + +class RulesFile: + """YAML rules file access""" + + yaml: YamlDict + + def __init__(self, yaml_f: Path, schema: Schema): + self.yaml = Helpers.load_yaml(yaml_f) + Helpers.validate_yaml(self.yaml, schema.as_dict(), yaml_f.name) + + def parse(self) -> Rules: + """Parse the YAML rules into a python Rules object""" + rules = Rules([]) + + for rule in self.yaml.get('rules', []): + if 'name' in rule: + rules.add_rule(SymbolRule(rule)) + continue + + if 'name_pattern' in rule: + rules.add_rule(PatternRule(rule)) + continue + + rules.docs_url = self.yaml.get('docs_url') + return rules + +@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] + +class Issues: + """Repository of all issues found by the checker""" + + def __init__(self, issues_l: list[Issue]): + # Index all issues by severity + self.issues: dict[Severity, list[Issue]] = { + severity: [] for severity in Severity + } + for issue in issues_l: + 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} is {issue.message}') + print() + + def _print_pattern(self, issue: PatternIssue) -> None: + print(f'* Below options are {issue.message}:\n') + for symbol in issue.symbols: + print(f' {symbol}') + print() + + def _print_issue(self, issue: Issue) -> None: + if isinstance(issue, SymbolIssue): + self._print_symbol(issue) + elif isinstance(issue, PatternIssue): + self._print_pattern(issue) + + 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) + +@dataclass +class Checker: + """The actual kconfig checker machinery""" + + kconfig: KernelConfig + rules: Rules + + def _find_issue_symbol(self, rule: SymbolRule) -> Optional[SymbolIssue]: + """Check the .config against passed rule. Return found issues, if any""" + value = self.kconfig.get_symbol_value(rule.symbol) + docs_url = self.rules.get_docs_url_for(rule) + + if rule.expected == ExpectedValue.y: + if value is None: + return SymbolIssue( + 'not in .config', + docs_url, + rule.severity, + rule.rationale, + rule.symbol, + ) + if value == 'n': + return SymbolIssue( + 'unset', + docs_url, + rule.severity, + rule.rationale, + rule.symbol, + ) + + if rule.expected == ExpectedValue.n: + if value in ('y', 'm'): + return SymbolIssue( + 'set', + docs_url, + rule.severity, + rule.rationale, + rule.symbol, + ) + + return None + + def _find_issue_pattern(self, pattern_rule: PatternRule) -> Optional[PatternIssue]: + """Check the .config against a pattern rule. Return found issues, if any.""" + if pattern_rule.expected == ExpectedValue.allowed: + return None + + violation_type = 'unset' if pattern_rule.expected == ExpectedValue.y else 'set' + docs_url = self.rules.get_docs_url_for(pattern_rule) + + violating_symbols = [] + + for symbol in self.kconfig.get_matching_symbols(pattern_rule.symbol_regex): + symbol_value = self.kconfig.get_symbol_value(symbol) + + if pattern_rule.expected == ExpectedValue.y and symbol_value == 'n': + # Exclude the config symbol if it's explicitly disabled elsewhere + symbol_rule = self.rules.get_symbol_rule(symbol) + if symbol_rule and symbol_rule.expected == ExpectedValue.n: + continue + + violating_symbols.append(symbol) + + if pattern_rule.expected == ExpectedValue.n and symbol_value in ('y', 'm'): + # Exclude the config symbol if it's explicitly allowed elsewhere + symbol_rule = self.rules.get_symbol_rule(symbol) + if symbol_rule and symbol_rule.expected in (ExpectedValue.y, ExpectedValue.allowed): + continue + + violating_symbols.append(symbol) + + if not violating_symbols: + return None + + return PatternIssue( + violation_type, + docs_url, + pattern_rule.severity, + pattern_rule.rationale, + violating_symbols, + ) + + def _find_issue(self, rule: Rule) -> Optional[Issue]: + """Check the .config against passed rule. Return found issues, if any""" + if isinstance(rule, SymbolRule): + return self._find_issue_symbol(rule) + + if isinstance(rule, PatternRule): + return self._find_issue_pattern(rule) + + return None + + def find_issues(self) -> Optional[Report]: + """Check the .config file against required rules""" + issues: list[Issue] = [] + for rule in self.rules.rules: + if issue := self._find_issue(rule): + issues.append(issue) + + if issues: + return Report(Issues(issues)) + + return None + +def parse_args(rules: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser( + prog='check.py', + description='Kernel .config options checker', + ) + + subparsers = parser.add_subparsers( + dest='command', + required=True, + ) + + subparsers.add_parser( + 'list-rules', + help='return available .config rule checking profiles', + ) + + 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', + ) + + check_parser.add_argument( + '-r', + '--rules', + metavar='RULES', + choices=rules, + required=True, + help='rules file to check against', + ) + + return parser.parse_args() + +def main() -> None: + base_dir = Path(__file__).resolve().parent + rules_dir = base_dir / 'rules' + + rules_l = sorted(path.stem for path in rules_dir.glob('*.yml')) + args = parse_args(rules_l) + + if args.command == 'list-rules': + print(*rules_l, sep=', ') + return + + kconfig_f = args.config.resolve() + kconfig = KernelConfig(kconfig_f) + + schema_f = base_dir / 'schema.yml' + schema = Schema(schema_f) + + rules_f = rules_dir / f'{args.rules}.yml' + rules = RulesFile(rules_f, schema).parse() + + checker = Checker(kconfig, rules) + report = checker.find_issues() + + if report: + report.print() + error(f'{kconfig_f} does not match required rules', os.EX_CONFIG) + + print(f'Success: {kconfig_f} matches required rules') + +if __name__ == '__main__': + main()
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v1 03/10] kconfig-checker: Add the configuration checker code
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] kconfig-checker: duplicate and non-exempted rules in _find_issue_pattern() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] kconfig-checker: duplicate and non-exempted rules in _find_issue_pattern()
--
commit 8f6e383a6cf382d507daf59d926387f2a7971370
Author: Ahmed S. Darwish <[email protected]>
kconfig-checker: Add the configuration checker code
This commit introduces a Python-based kernel configuration checker that validates a .config file against YAML rule profiles and reports issues by severity.
Quoted 6 lines
tools/kconfig-checker/check.py new file +0
-0@@ -0,0 +1,558 @@
[ ... ]
Quoted 18 lines
tools/kconfig-checker/check.py new file +18
-0+ def _find_issue_pattern(self, pattern_rule: PatternRule) -> Optional[PatternIssue]: + """Check the .config against a pattern rule. Return found issues, if any.""" + if pattern_rule.expected == ExpectedValue.allowed: + return None + + violation_type = 'unset' if pattern_rule.expected == ExpectedValue.y else 'set' + docs_url = self.rules.get_docs_url_for(pattern_rule) + + violating_symbols = [] + + for symbol in self.kconfig.get_matching_symbols(pattern_rule.symbol_regex): + symbol_value = self.kconfig.get_symbol_value(symbol) + + if pattern_rule.expected == ExpectedValue.y and symbol_value == 'n': + # Exclude the config symbol if it's explicitly disabled elsewhere + symbol_rule = self.rules.get_symbol_rule(symbol) + if symbol_rule and symbol_rule.expected == ExpectedValue.n: + continue
tools/kconfig-checker/check.py line 452
Quoted 10 lines
tools/kconfig-checker/check.py new file +10
-0+ + violating_symbols.append(symbol) + + if pattern_rule.expected == ExpectedValue.n and symbol_value in ('y', 'm'): + # Exclude the config symbol if it's explicitly allowed elsewhere + symbol_rule = self.rules.get_symbol_rule(symbol) + if symbol_rule and symbol_rule.expected in (ExpectedValue.y, ExpectedValue.allowed): + continue + + violating_symbols.append(symbol)
[Severity: Low]
Should _find_issue_pattern() skip any symbol that has an explicit SymbolRule, regardless of symbol_rule.expected?
Only checking for opposing expected values causes two issues: when pattern_rule.expected is ExpectedValue.y, a symbol with a SymbolRule of ExpectedValue.allowed is not exempted and is falsely reported as unset, and when a SymbolRule has the same expected value as the PatternRule (for example, to give a specific symbol its own severity or rationale), the violation is reported twice—once by _find_issue_symbol() and once by _find_issue_pattern().
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH v1 03/10] kconfig-checker: Add the configuration checker code
Quoted 34 lines · On Sat, 07 Nov 2026, [email protected] wrote:
Quoted 19 lines
+ def
_find_issue_pattern(self, pattern_rule: PatternRule)-> Optional[PatternIssue]:tools/kconfig-checker/check.py new file +17
-0+ """Check the .config against a pattern rule. Return found issues, if any.""" + if pattern_rule.expected == ExpectedValue.allowed: + return None + + violation_type = 'unset' if pattern_rule.expected == ExpectedValue.y else 'set' + docs_url = self.rules.get_docs_url_for(pattern_rule) + + violating_symbols = [] + + for symbol in self.kconfig.get_matching_symbols(pattern_rule.symbol_regex): + symbol_value = self.kconfig.get_symbol_value(symbol) + + if pattern_rule.expected == ExpectedValue.y and symbol_value == 'n': + # Exclude the config symbol if it's explicitly disabled elsewhere + symbol_rule = self.rules.get_symbol_rule(symbol) + if symbol_rule and symbol_rule.expected == ExpectedValue.n: + continuetools/kconfig-checker/check.py line 452
Quoted 10 lines
tools/kconfig-checker/check.py new file +10
-0+ + violating_symbols.append(symbol) + + if pattern_rule.expected == ExpectedValue.n and symbol_value in ('y', 'm'): + # Exclude the config symbol if it's explicitly allowed elsewhere + symbol_rule = self.rules.get_symbol_rule(symbol) + if symbol_rule and symbol_rule.expected in (ExpectedValue.y, ExpectedValue.allowed): + continue + + violating_symbols.append(symbol)[Severity: Low]
Should_find_issue_pattern()skip any symbol that has an explicit SymbolRule, regardless of symbol_rule.expected?
Quoted 3 lines
Only checking for opposing expected values causes two issues: when pattern_rule.expected is ExpectedValue.y, a symbol with a SymbolRule of ExpectedValue.allowed is not exempted and is falsely reported as unset,
I think you misunderstand what 'allowed' means.
'expected: allowed', means that an option is permitted. Quoting the schema:
#
# Expected value for the matching kernel configuration option. #
# Values:
#
# y option is expected to be enabled (built-in or module).
# n option is expected to be disabled or unset.
# allowed option is permitted and must not be reported as a violation.
# This is to be used either by overlays, or to exempt a specific
# symbol from a broader name_pattern rule with expected: n.
#
expected:
type: string
enum: [y, n, allowed]
So, for below policy:
- name_pattern: CONFIG_DEBUG_.*
expected: n
- name: CONFIG_DEBUG_ATOMIC_SLEEP
expected: allowed
having a CONFIG_DEBUG_ATOMIC_SLEEP=y should not trigger an audit warning.
But for below policy:
- name_pattern: CONFIG_DEBUG_.*
expected: y
- name: CONFIG_DEBUG_ATOMIC_SLEEP
expected: allowed
having CONFIG_DEBUG_ATOMIC_SLEEP=y should trigger no warning, but having 'CONFIG_DEBUG_ATOMIC_SLEEP is unset' should definitely trigger a warning, even with the second 'expected: allowed' rule.
TLDR; the pattern expected: y / symbol expected: allowed case is not a bug.
Quoted 6 lines
and when a SymbolRule has the same expected value as the PatternRule (for example, to give a specific symbol its own severity or rationale), the violation is reported twice—once by
_find_issue_symbol()and once by_find_issue_pattern().
Hmm, the tool does not handle below case:
- name_pattern: CONFIG_DEBUG_.*
expected: n
serverity: medium
- name: CONFIG_DEBUG_ATOMIC_SLEEP
expected: n
severity: fatal
rationale: Danger! must disable! Danger!
But on a second look, maybe it should... I'll think about it.
Thanks,
Ahmed
Julian Braha
reviewerRe: [PATCH v1 03/10] kconfig-checker: Add the configuration checker code
In reply to Ahmed S. DarwishQuoted 108 lines · Ahmed S. Darwish
Introduce a kernel configuration checker.
Validate the passed kernel .config against a YAML rules file and report problematic configuration issues 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.
Create a proper Python objects data model for the kconfig checker to work with. Confine all direct YAML dictionary access to YAML files loading, validation, and data model construction.
Document the tool's development rules on top.
Signed-off-by Ahmed S. Darwish <[email protected]>--- tools/kconfig-checker/check.py | 558 +++++++++++++++++++++++++++++++++ 1 file changed, 558 insertions(+) create mode 100755 tools/kconfig-checker/check.pytools/kconfig-checker/check.py new file +82
-0@@ -0,0 +1,558 @@ +#!/usr/bin/env python3 +# +# SPDX-License-Identifier: GPL-2.0-only +# +# Kernel .config checker +# +# Main usage: +# +# $ check.py list-rules +# $ check.py check -c path/to/linux/.config -r preempt_rt +# +# Notes: +# +# - All code is to be fully type-annotated. Before introducing changes, +# please verify type-safety using: +# +# $ mypy --strict --no-warn-return-any check.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. +# +# - The YAML rule files are only treated as a serialization format. After +# loading and schema validation, such rules are parsed into an internal +# data model: Severity, Rule, SymbolRule, PatternRule, Rules, and other +# related python objects. +# +# All checker logic must operate on that typed model, and not on the raw +# YAML dictionaries. +# +# - Minimize external dependencies: this tool is also intended to be run +# from distribution kernel-package scripts in the future. +# +# Script exit codes: +# +# os.EX_CONFIG passed kernel .config does not match rules +# 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 +from enum import Enum, auto +from pathlib import Path +from typing import Any, NoReturn, Optional + +# +# Initial sanity checks: +# + +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) + +# +# Actual script: +# + +class KernelConfig: + """.config file parser""" + + def __init__(self, file: Path): + try:
tools/kconfig-checker/check.py line 92
Quoted 10 lines
tools/kconfig-checker/check.py new file +10
-0+ self.lines = file.read_text().splitlines() + except OSError as e: + error(f'Could not open {file}: {e.strerror}', os.EX_NOINPUT) + + self.symbols = self._parse_symbols() + + def _parse_symbols(self) -> dict[str, str]: + """Extract CONFIG_* symbol assignments from .config""" + symbol_set = re.compile(r'^(CONFIG_[A-Za-z0-9_]+)=([ym])$') + symbol_unset = re.compile(r'^# (CONFIG_[A-Za-z0-9_]+) is not set$')
What does this do for Kconfig's int, hex, and string options?
- Julian Braha
Re: [PATCH v1 03/10] kconfig-checker: Add the configuration checker code
Quoted 5 lines · Julian Braha
Quoted 3 lines · Ahmed S. Darwish
tools/kconfig-checker/check.py new file +3
-0+ +class KernelConfig: + """.config file parser"""
...
Quoted 8 lines
tools/kconfig-checker/check.py line 92
Quoted 5 lines
tools/kconfig-checker/check.py new file +5
-0+ + def _parse_symbols(self) -> dict[str, str]: + """Extract CONFIG_* symbol assignments from .config""" + symbol_set = re.compile(r'^(CONFIG_[A-Za-z0-9_]+)=([ym])$') + symbol_unset = re.compile(r'^# (CONFIG_[A-Za-z0-9_]+) is not set$')What does this do for Kconfig's int, hex, and string options?
So far, the tool only supports stating whether an option is enabled, disabled, or have a neutral 'allowed' policy.
But there's nothing stopping us from supporting something like:
- name: CONFIG_PANIC_TIMEOUT
expected: int
expected_value: 10
- name: CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE
expected: hex
expected_value: 0x1
- name: CONFIG_NLS_DEFAULT
expected: string
expected_value: "utf-8"
In v2 of this series, I'll make the schema explicitly versioned. This way, new features like the above can be cleanly added.
P.S., I can definitely implement such support, but I'm a bit hesitant to adding features that are not yet needed by the existing mainline policies.
Thanks!
--
Ahmed S. Darwish
Linutronix GmbH
Julian Braha
reviewerRe: [PATCH v1 03/10] kconfig-checker: Add the configuration checker code
Quoted 26 lines · Ahmed S. Darwish
Quoted 4 lines · Julian Braha
Quoted 3 lines · Ahmed S. Darwish
tools/kconfig-checker/check.py new file +3
-0+ +class KernelConfig: + """.config file parser"""...
Quoted 7 lines
tools/kconfig-checker/check.py line 92
Quoted 5 lines
tools/kconfig-checker/check.py new file +5
-0+ + def _parse_symbols(self) -> dict[str, str]: + """Extract CONFIG_* symbol assignments from .config""" + symbol_set = re.compile(r'^(CONFIG_[A-Za-z0-9_]+)=([ym])$') + symbol_unset = re.compile(r'^# (CONFIG_[A-Za-z0-9_]+) is not set$')What does this do for Kconfig's int, hex, and string options?
So far, the tool only supports stating whether an option is enabled, disabled, or have a neutral 'allowed' policy.
But there's nothing stopping us from supporting something like:
- name:
CONFIG_PANIC_TIMEOUT
expected: int
expected_value: 10- name:
CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE
expected: hex
expected_value:0x1
Quoted 6 lines
- name:
CONFIG_NLS_DEFAULT
expected: string
expected_value: "utf-8"In v2 of this series, I'll make the schema explicitly versioned. This way, new features like the above can be cleanly added.
Adding schema versioning would be great.
Quoted 3 lines
P.S., I can definitely implement such support, but I'm a bit hesitant to adding features that are not yet needed by the existing mainline policies.
I suppose it's not necessary to support these option types at the start, as there are few of them, relatively speaking. But it would be good to add some input validation in case a user attempts this.
So I've finally had some time to sit down and test this:
I created my own policy with these other types, and sure enough, if I specify them as 'disabled' in the policy like this:
rules:
- name: CONFIG_LOG_BUF_SHIFT
expected: n
severity: high
- name: CONFIG_PHYSICAL_START
expected: n
severity: high
- name: CONFIG_DEFAULT_HOSTNAME
expected: n
severity: high
and my .config has these values:
CONFIG_LOG_BUF_SHIFT=17
CONFIG_PHYSICAL_START=0x1000000
CONFIG_DEFAULT_HOSTNAME="example"then the config passes the check -- but it would probably be better to provide a warning or something about these options.
Also, if I modify my policy to set 'expected' to 'y' for these, it reports "not in .config" (which would likely be confusing to the user).
This regex stmt should match all int, hex, and string options for you:
unsupported = re.compile(r'^(CONFIG_[A-Za-z0-9_]+)=[0-9a-fA-F"-]')
by checking the first character of its value.
The included preempt_rt policy worked as expected (nice).
- Julian Braha
Re: [PATCH v1 03/10] kconfig-checker: Add the configuration checker code
Hi Julian,
Quoted 7 lines · Julian Braha
Quoted 4 lines · Ahmed S. Darwish
In v2 of this series, I'll make the schema explicitly versioned. This way, new features like the above can be cleanly added.
Adding schema versioning would be great.
Yup.
Quoted 34 lines
Quoted 3 lines
P.S., I can definitely implement such support, but I'm a bit hesitant to adding features that are not yet needed by the existing mainline policies.I suppose it's not necessary to support these option types at the start, as there are few of them, relatively speaking. But it would be good to add some input validation in case a user attempts this.
So I've finally had some time to sit down and test this:
I created my own policy with these other types, and sure enough, if I specify them as 'disabled' in the policy like this:
rules:
- name:CONFIG_LOG_BUF_SHIFT
expected: n
severity: high- name:
CONFIG_PHYSICAL_START
expected: n
severity: high- name:
CONFIG_DEFAULT_HOSTNAME
expected: n
severity: highand my .config has these values:
CONFIG_LOG_BUF_SHIFT=17 CONFIG_PHYSICAL_START=0x1000000 CONFIG_DEFAULT_HOSTNAME="example"then the config passes the check -- but it would probably be better to provide a warning or something about these options.
Quoted 7 lines
Also, if I modify my policy to set 'expected' to 'y' for these, it reports "not in .config" (which would likely be confusing to the user).
This regex stmt should match all int, hex, and string options for you:
unsupported = re.compile(r'^(CONFIG_[A-Za-z0-9_]+)=[0-9a-fA-F"-]')by checking the first character of its value.
You're definitely correct here, thanks.
If a symbol is expected as enabled or disabled in the policy, but the .config has it as an int, hex, or a string, then the report must include that as a policy mismatch.
So for the above case, the tool should report something like:
* Below option is set as an integer:
CONFIG_LOG_BUF_SHIFT
But it's expected to be disabled instead.
And similarly for the other symbols.
I'll fix that in v2.
Quoted 1 line
The included
preempt_rtpolicy worked as expected (nice).
Glad to hear!
All the best,
--
Ahmed S. Darwish
Linutronix GmbH
PATCH 4/10 kconfig: Introduce checkconfig target
In reply to Ahmed S. DarwishAdd a checkconfig target to validate the current kernel .config against a set of rules. Select the rules using a mandatory RULES= make variable.
Example usage:
make RULES=preempt_rt checkconfig
Use the kconfig-checker to perform all sanity checks.
Document the new target at the 'make help' text.
--- scripts/kconfig/Makefile | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+)
scripts/kconfig/Makefile +23 -0
@@ -125,6 +125,26 @@ testconfig: $(obj)/conf $(if $(findstring 1,$(KBUILD_VERBOSE)),--capture=no) clean-files += tests/.cache +checkconfig := $(PYTHON3) -B $(srctree)/tools/kconfig-checker/check.py +list_checkconfig_rules = \ + echo -n >&2 "Available RULES: "; \ + $(checkconfig) list-rules >&2; \ + echo >&2 + +PHONY += checkconfig +checkconfig: + $(Q)if [ -z "$(RULES)" ]; then \ + echo >&2 "Usage: make RULES=<profile> checkconfig"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)if ! $(checkconfig) list-rules | grep -qw "$(RULES)"; then \ + echo >&2 "Unknown RULES profile = $(RULES)"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" + # Help text used by make help help: @echo 'Configuration targets:'
@@ -154,6 +174,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 ' checkconfig - Check current config against sanity rules specified by RULES' + @echo ' Example usage: "make RULES=preempt_rt checkconfig"' + @echo ' (requires python3, PyYAML, and jsonschema)' @echo '' @echo 'Configuration topic targets:' @$(foreach f, $(all-config-fragments), \
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v1 04/10] kconfig: Introduce checkconfig target
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] kconfig: checkconfig pipeline masks check.py startup and dependency errors --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] kconfig: checkconfig pipeline masks check.py startup and dependency errors
--
commit 984ec26ec37b16ca849857bd7d027d488808c4d2
Author: Ahmed S. Darwish <[email protected]>
kconfig: Introduce checkconfig target
This commit adds a checkconfig Makefile target that invokes tools/kconfig-checker/check.py to validate the kernel configuration against the rules profile specified by RULES, and documents the target in the help output.
Quoted 17 lines
scripts/kconfig/Makefile +9
-0@@ -125,6 +125,26 @@ testconfig: $(obj)/conf $(if $(findstring 1,$(KBUILD_VERBOSE)),--capture=no) clean-files += tests/.cache +checkconfig := $(PYTHON3) -B $(srctree)/tools/kconfig-checker/check.py +list_checkconfig_rules = \ + echo -n >&2 "Available RULES: "; \ + $(checkconfig) list-rules >&2; \ + echo >&2 + +PHONY += checkconfig +checkconfig: + $(Q)if [ -z "$(RULES)" ]; then \
scripts/kconfig/Makefile testconfig: $(obj)/conf · line 146
Quoted 10 lines
scripts/kconfig/Makefile +10
-0+ echo >&2 "Usage: make RULES=<profile> checkconfig"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)if ! $(checkconfig) list-rules | grep -qw "$(RULES)"; then \ + echo >&2 "Unknown RULES profile = $(RULES)"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)"
[Severity: Low]
Does piping $(checkconfig) list-rules into grep mask startup and dependency failures from check.py?
tools/kconfig-checker/check.py imports jsonschema and yaml at module load time before handling list-rules:
tools/kconfig-checker/check.py:
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)
When either module is missing, check.py writes the error to stderr, produces no stdout, and exits with os.EX_UNAVAILABLE. Because the POSIX shell pipeline ignores the exit status of $(checkconfig) list-rules, grep -qw exits 1 on the empty stdout and the negated condition enters the branch. That reports a valid setting such as RULES=preempt_rt as an unknown profile and runs $(list_checkconfig_rules), which invokes check.py a second time and prints a duplicate module error on the same line after "Available RULES: ".
In addition, grep -qw treats $(RULES) as a regular expression with word boundaries against the comma-separated output of list-rules rather than matching an exact profile name, and spawns Python twice on every valid invocation even though check.py check -r already validates the profile name.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Re: [PATCH v1 04/10] kconfig: Introduce checkconfig target
Quoted 21 lines · On Sat, 07 Nov 2026, [email protected] wrote:
Quoted 20 lines
scripts/kconfig/Makefile +19
-0+checkconfig := $(PYTHON3) -B $(srctree)/tools/kconfig-checker/check.py +list_checkconfig_rules = \ + echo -n >&2 "Available RULES: "; \ + $(checkconfig) list-rules >&2; \ + echo >&2 + +PHONY += checkconfig +checkconfig: + $(Q)if [ -z "$(RULES)" ]; then \ + echo >&2 "Usage: make RULES=<profile> checkconfig"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)if ! $(checkconfig) list-rules | grep -qw "$(RULES)"; then \ + echo >&2 "Unknown RULES profile = $(RULES)"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)"
...
Quoted 9 lines
When either module is missing,
check.pywrites the error to stderr, produces no stdout, and exits with os.EX_UNAVAILABLE. Because the POSIX shell pipeline ignores the exit status of $(checkconfig) list-rules, grep -qw exits 1 on the empty stdout and the negated condition enters the branch. That reports a valid setting such as RULES=preempt_rt as an unknown profile and runs $(list_checkconfig_rules), which invokescheck.pya second time and prints a duplicate module error on the same line after "Available RULES: ".
It works, so there is no reason to complicate things.
For example, invoking the make target from a container with old Python:
$ make checkconfig Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig Available RULES: Error: Python 3.9 or later is required
make[2]: *** [scripts/kconfig/Makefile:138: checkconfig] Error 2 make[1]: *** [/home/darwi/linux/Makefile:772: checkconfig] Error 2
make: *** [Makefile:248: __sub-make] Error 2
and:
$ make RULES=nonExistent checkconfig Error: Python 3.9 or later is required Unknown RULES profile = nonExistent Available RULES: Error: Python 3.9 or later is required
make[2]: *** [scripts/kconfig/Makefile:139: checkconfig] Error 2 make[1]: *** [/home/darwi/linux/Makefile:772: checkconfig] Error 2
make: *** [Makefile:248: __sub-make] Error 2
The duplicate error, which is a single line, is no big deal. IMO, it's better than complicating the Makefile for that single edge case.
Quoted 7 lines
In addition, grep -qw treats $(RULES) as a regular expression with word boundaries against the comma-separated output of list-rules rather than matching an exact profile name, and spawns Python twice on every valid invocation even though
check.pycheck -r already validates the profile name.
That's good catch; will fix.
Thanks,
Ahmed
Re: [PATCH v1 04/10] kconfig: Introduce checkconfig target
Quoted 11 lines · Ahmed S. Darwish
Quoted 5 lines · On Sat, 07 Nov 2026, [email protected] wrote:
In addition, grep -qw treats $(RULES) as a regular expression with word boundaries against the comma-separated output of list-rules rather than matching an exact profile name.
That's good catch; will fix.
I've just verified that 'grep -w' considers ',' as a valid word separator:
$ echo 'word1,preempt_rt,word2' | grep -qw preempt_rt
$ echo $?
0So, Sashiko, this is also a non-issue.
Thanks,
Ahmed
Julian Braha
reviewerRe: [PATCH v1 04/10] kconfig: Introduce checkconfig target
In reply to Ahmed S. DarwishQuoted 49 lines · Ahmed S. Darwish
Add a checkconfig target to validate the current kernel .config against a set of rules. Select the rules using a mandatory RULES= make variable.
Example usage:
make RULES=preempt_rt checkconfig
Use the kconfig-checker to perform all sanity checks.
Document the new target at the 'make help' text.
Signed-off-by Ahmed S. Darwish <[email protected]>--- scripts/kconfig/Makefile | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+)scripts/kconfig/Makefile +20
-0@@ -125,6 +125,26 @@ testconfig: $(obj)/conf $(if $(findstring 1,$(KBUILD_VERBOSE)),--capture=no) clean-files += tests/.cache +checkconfig := $(PYTHON3) -B $(srctree)/tools/kconfig-checker/check.py +list_checkconfig_rules = \ + echo -n >&2 "Available RULES: "; \ + $(checkconfig) list-rules >&2; \ + echo >&2 + +PHONY += checkconfig +checkconfig: + $(Q)if [ -z "$(RULES)" ]; then \ + echo >&2 "Usage: make RULES=<profile> checkconfig"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)if ! $(checkconfig) list-rules | grep -qw "$(RULES)"; then \ + echo >&2 "Unknown RULES profile = $(RULES)"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" + # Help text used by make help help: @echo 'Configuration targets:'
scripts/kconfig/Makefile help:
Quoted 10 lines
scripts/kconfig/Makefile +3
-1@@ -154,6 +174,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 ' checkconfig - Check current config against sanity rules specified by RULES' + @echo ' Example usage: "make RULES=preempt_rt checkconfig"' + @echo ' (requires python3, PyYAML, and jsonschema)' @echo '' @echo 'Configuration topic targets:' @$(foreach f, $(all-config-fragments), \ -- 2.56.0
I think this tool may belong in scripts/ due to the kbuild integration, as was mentioned in the past on another tool review:
https://lore.kernel.org/linux-kbuild/20260428183101.GA3304253@ax162/
- Julian Braha
Nathan Chancellor
maintainerRe: [PATCH v1 04/10] kconfig: Introduce checkconfig target
Quoted 64 lines · Julian Braha
Quoted 49 lines · Ahmed S. Darwish
Add a checkconfig target to validate the current kernel .config against a set of rules. Select the rules using a mandatory RULES= make variable.
Example usage:
make RULES=preempt_rt checkconfig
Use the kconfig-checker to perform all sanity checks.
Document the new target at the 'make help' text.
Signed-off-by Ahmed S. Darwish <[email protected]>--- scripts/kconfig/Makefile | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+)scripts/kconfig/Makefile +20
-0@@ -125,6 +125,26 @@ testconfig: $(obj)/conf $(if $(findstring 1,$(KBUILD_VERBOSE)),--capture=no) clean-files += tests/.cache +checkconfig := $(PYTHON3) -B $(srctree)/tools/kconfig-checker/check.py +list_checkconfig_rules = \ + echo -n >&2 "Available RULES: "; \ + $(checkconfig) list-rules >&2; \ + echo >&2 + +PHONY += checkconfig +checkconfig: + $(Q)if [ -z "$(RULES)" ]; then \ + echo >&2 "Usage: make RULES=<profile> checkconfig"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)if ! $(checkconfig) list-rules | grep -qw "$(RULES)"; then \ + echo >&2 "Unknown RULES profile = $(RULES)"; \ + $(list_checkconfig_rules); \ + exit 2; \ + fi + $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" + # Help text used by make help help: @echo 'Configuration targets:'scripts/kconfig/Makefile help:
Quoted 10 lines
scripts/kconfig/Makefile +3
-1@@ -154,6 +174,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 ' checkconfig - Check current config against sanity rules specified by RULES' + @echo ' Example usage: "make RULES=preempt_rt checkconfig"' + @echo ' (requires python3, PyYAML, and jsonschema)' @echo '' @echo 'Configuration topic targets:' @$(foreach f, $(all-config-fragments), \ -- 2.56.0I think this tool may belong in
scripts/due to the kbuild integration, as was mentioned in the past on another tool review:
Yeah, while I would prefer for the script to live in scripts/ due to being called from Kbuild, I am not sure if the rules/schemas belong there? It might be better to keep everything in tools/ for that reason, especially if this may be called externally, but I am open to other thoughts.
Signature · 2 lines
Cheers, Nathan
Re: [PATCH v1 04/10] kconfig: Introduce checkconfig target
Quoted 8 lines · Nathan Chancellor
Quoted 5 lines · Julian Braha
I think this tool may belong in
scripts/due to the kbuild integration, as was mentioned in the past on another tool review:https://lore.kernel.org/linux-kbuild/20260428183101.GA3304253@ax162/
Quoted 8 lines
Yeah, while I would prefer for the script to live in
scripts/due to being called fromKbuild, I am not sure if the rules/schemas belong there?It might be better to keep everything in
tools/for that reason, especially if this may be called externally, but I am open to other thoughts.
I would prefer to keep it under tools/ as well. Because of the PREEMPT_RT policy, and the possible extra policies from ELISA, etc.
This is why one of the development rules at the top of the Python script, at patch 03/10, is:
The tool must not depend on being run inside the kernel source tree. This simplifies invocation, testing and possible future packaging.
So, upon (hopefully) including this tool mainline, I'd send a patch to the Debian kernel team to create a separate Debian package from the kernel sources for it. That is, exactly like what they're now doing with perf.
(v2 of this series will add versioning support to the schemas; thus making
the tool's support for packaging stronger as well.)
Thanks!
--
Ahmed S. Darwish
Linutronix GmbH
Nicolas Schier
maintainerRe: [PATCH v1 04/10] kconfig: Introduce checkconfig target
Quoted 18 lines · Ahmed S. Darwish
Quoted 8 lines · Nathan Chancellor
Quoted 5 lines · Julian Braha
I think this tool may belong in
scripts/due to the kbuild integration, as was mentioned in the past on another tool review:https://lore.kernel.org/linux-kbuild/20260428183101.GA3304253@ax162/
Quoted 8 lines
Yeah, while I would prefer for the script to live in
scripts/due to being called fromKbuild, I am not sure if the rules/schemas belong there?It might be better to keep everything in
tools/for that reason, especially if this may be called externally, but I am open to other thoughts.
Quoted 8 lines
I would prefer to keep it under
tools/as well. Because of thePREEMPT_RTpolicy, and the possible extra policies from ELISA, etc.This is why one of the development rules at the top of the Python script, at patch 03/10, is:
The tool must not depend on being run inside the kernel source tree. This simplifies invocation, testing and possible future packaging.
Then, please move the argument checking from Makefile to the script itself. Handling wrong arguments is good native feature for the script.
As far as I have seen when skimming through the kconfig policy checker code, it does not use any Kbuild variables. So, if it is being placed below tools/ and does not use Kbuild at all, and is expected to be run w/o Linux tree context at all: why do we need an additional top-level Makefile target for it at all (alongside of
'make tools/kconfig-policy-checker')?
Signature · 1 line
Nicolas
Re: [PATCH v1 04/10] kconfig: Introduce checkconfig target
Hi Nicolas,
Quoted 12 lines · Nicolas Schier
Quoted 6 lines · Ahmed S. Darwish
This is why one of the development rules at the top of the Python script, at patch 03/10, is:
The tool must not depend on being run inside the kernel source tree. This simplifies invocation, testing and possible future packaging.
Then, please move the argument checking from
Makefileto the script itself. Handling wrong arguments is good native feature for the script.
The script does its own argument checking, all through Python's native argparse mechanism:
$ ./tools/kconfig-checker/check.py check -h
usage: check.py check [-h] -c KCONFIG_FILE -r RULES [-o OVERLAY_FILE] options:
-h, --help show this help message and exit
-c, --config KCONFIG_FILE
.config file to be checked
-r, --rules RULES rules file to check against
-o, --overlay OVERLAY_FILE
file overlay over picked rules
$ ./tools/kconfig-checker/check.py check -r safety
usage: check.py check [-h] -c KCONFIG_FILE -r RULES [-o OVERLAY_FILE]
check.py check: error: argument -r/--rules: invalid choice: 'safety' (choose from 'preempt_rt')
And that's by design, as an independent tool that can be later packaged.
Regarding the Makefile's own error handling, I'll touch upon that below.
Quoted 6 lines
As far as I have seen when skimming through the kconfig policy checker code, it does not use any
Kbuildvariables. So, if it is being placed belowtools/and does not useKbuildat all, and is expected to be run w/o Linux tree context at all: why do we need an additional top-levelMakefiletarget for it at all (alongside of
'maketools/kconfig-policy-checker')?
The reason is the expected kernel configuration workflow, e.g.:
$ make defconfig # Generate a default .config
$ make debug.config # Add debug options to it
$ make menuconfig # Manually customize it $ make RULES=preempt_rt checkconfig # Validate it
$ make menuconfig # Follow checkconfig advice
$ make RULES=preempt_rt checkconfig # Try again..and so on.
So the "checkconfig" target fits that workflow, even when the checker itself does not depend on any Kbuild internals.
The Makefile-side validation is also there to improve error handling for that workflow:
$ make checkconfig
Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig Available RULES: preempt_rt
make[2]: *** [scripts/kconfig/Makefile:138: checkconfig] Error 2
Without it, the user just sees the lower-level script errors:
$ make checkconfig
usage: check.py check [-h] -c KCONFIG_FILE -r RULES [-o OVERLAY_FILE] check.py check: error: argument -r/--rules: invalid choice: '' (choose from 'preempt_rt')
Both error messages are correct, but the former informs the user, exactly, on how to call the Makefile target. This matches the aforementioned kernel configuration workflow as well.
I hope this clarifies things a bit.
Thank you!
--
Ahmed S. Darwish
Linutronix GmbH
PATCH 5/10 Documentation: Describe kconfig-checker usage and design
In reply to Ahmed S. DarwishDescribe the kconfig-checker design, invocation, and external dependencies.
For PREEMPT_RT users, mention that the checker can now be used for validating a kernel's .config against PREEMPT_RT requirements.
For the kconfig-checker external dependencies error handling code, reference the newly added documentation as well.
--- Documentation/admin-guide/README.rst | 24 +++++++++ .../real-time/kernel-configuration.rst | 3 ++ Documentation/tools/index.rst | 1 + Documentation/tools/kconfig_checker.rst | 50 +++++++++++++++++++ tools/kconfig-checker/check.py | 7 ++- 5 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 Documentation/tools/kconfig_checker.rst
Documentation/admin-guide/README.rst +24 -0
@@ -256,6 +256,30 @@ 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 checkconfig`` prints +usage information and the available profiles:: + + Usage: make RULES=<profile> checkconfig + Available RULES: preempt_rt + +For example, to validate the current configuration against the PREEMPT_RT +profile, run:: + + make RULES=preempt_rt checkconfig + +``checkconfig`` 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 checkconfig`` again, +against the same rules, until no relevant diagnostics remain. + +For more information, see Documentation/tools/kconfig_checker.rst + Compiling the kernel --------------------
Documentation/core-api/real-time/kernel-configuration.rst +3 -0
@@ -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-checker`` tool. See Documentation/tools/kconfig_checker.rst + Configuration options =====================
Documentation/tools/index.rst +1 -0
@@ -10,6 +10,7 @@ more additions are needed here: .. toctree:: :maxdepth: 1 + kconfig_checker rtla/index rv/index python
Documentation/tools/kconfig_checker.rst new file +50 -0
50 lines not on this page · raw message
tools/kconfig-checker/check.py +6 -1
@@ -69,7 +69,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_checker.rst' + error( + f'Missing Python module: {e.name}\n' + f'Check {docs} for how to install required dependencies', + os.EX_UNAVAILABLE + ) # # Actual script:
Signature · 1 line
2.56.0
PATCH 6/10 kconfig-checker: Split schema to support component reuse
In reply to Ahmed S. DarwishNormal rule files require every rule to define both 'expected' and 'severity'. Overlay files are different: an overlay may update only selected fields of an existing rule, so a future overlay schema will permit these fields to be omitted.
Move the common rule definitions into schemas/base.yml and add a strict schemas/rules.yml wrapper for complete rule files.
Teach the checker to build a Draft7Validator with local file:// URIs so that rules.yml can resolve base.yml.
---
tools/kconfig-checker/check.py | 52 ++++++++++++++++---
.../{schema.yml => schemas/base.yml} | 3 +-
tools/kconfig-checker/schemas/rules.yml | 20 +++++++
3 files changed, 65 insertions(+), 10 deletions(-)
rename tools/kconfig-checker/{schema.yml => schemas/base.yml} (97%)
create mode 100644 tools/kconfig-checker/schemas/rules.ymltools/kconfig-checker/check.py +44 -8
@@ -80,6 +80,8 @@ except ModuleNotFoundError as e: # Actual script: # +from jsonschema import Draft7Validator + class KernelConfig: """.config file parser"""
@@ -133,9 +135,9 @@ class Helpers: error(f'Invalid YAML syntax at {yaml_f}:\n {e}', os.EX_DATAERR) @staticmethod - def validate_yaml(yaml: YamlDict, schema: YamlDict, f_name: str) -> None: + def validate_yaml(yaml: YamlDict, validator: Draft7Validator, f_name: str) -> None: try: - jsonschema.validate(yaml, schema) + validator.validate(yaml) except jsonschema.exceptions.ValidationError as e: error( f'{f_name} does not match its schema\n'
@@ -144,12 +146,45 @@ class Helpers: ) class Schema: - """Rules file schema, in json-schema.org format""" + """Rules file schema, in json-schema.org draft-07 format""" + + # Rules schema refer to definitions from this base schema + BASE_SCHEMA = 'base.yml' def __init__(self, schema_f: Path): - self.schema = Helpers.load_yaml(schema_f) - # Validate the schema itself against draft-07 metaschema - jsonschema.Draft7Validator.check_schema(self.schema) + base_schema_f = schema_f.parent / self.BASE_SCHEMA + + # Use file:// URIs so jsonschema can resolve local '$ref' entries + base_schema_uri = base_schema_f.resolve().as_uri() + schema_uri = schema_f.resolve().as_uri() + + base_schema = self._load(base_schema_f) + self.schema = self._load(schema_f) + + self.validator = self._create_validator( + base_schema_uri, base_schema, + schema_uri, self.schema, + ) + + @staticmethod + def _create_validator(base_schema_uri: str, base_schema: YamlDict, + schema_uri: str, schema: YamlDict) -> Draft7Validator: + """Create a schema validator which can resolve local '$ref' URIs""" + resolver = jsonschema.RefResolver( + base_uri=schema_uri, + referrer=schema, + store={ base_schema_uri: base_schema }, + ) + + return Draft7Validator(schema, resolver=resolver) + + @staticmethod + def _load(path: Path) -> YamlDict: + """Load and validate the schema itself against its metaschema""" + schema = Helpers.load_yaml(path) + + Draft7Validator.check_schema(schema) + return schema def as_dict(self) -> YamlDict: return self.schema
@@ -273,7 +308,7 @@ class RulesFile: def __init__(self, yaml_f: Path, schema: Schema): self.yaml = Helpers.load_yaml(yaml_f) - Helpers.validate_yaml(self.yaml, schema.as_dict(), yaml_f.name) + Helpers.validate_yaml(self.yaml, schema.validator, yaml_f.name) def parse(self) -> Rules: """Parse the YAML rules into a python Rules object"""
@@ -533,6 +568,7 @@ def parse_args(rules: list[str]) -> argparse.Namespace: def main() -> None: base_dir = Path(__file__).resolve().parent rules_dir = base_dir / 'rules' + schema_dir = base_dir / 'schemas' rules_l = sorted(path.stem for path in rules_dir.glob('*.yml')) args = parse_args(rules_l)
@@ -544,7 +580,7 @@ def main() -> None: kconfig_f = args.config.resolve() kconfig = KernelConfig(kconfig_f) - schema_f = base_dir / 'schema.yml' + schema_f = schema_dir / 'rules.yml' schema = Schema(schema_f) rules_f = rules_dir / f'{args.rules}.yml'
tools/kconfig-checker/schemas/base.yml renamed from tools/kconfig-checker/schema.yml +1 -2
@@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft-07/schema" -title: Schema for kconfig-checker rule files +title: Base schema for kconfig-checker rule files type: object required: [rules] additionalProperties: false
@@ -24,7 +24,6 @@ properties: oneOf: - required: [name] - required: [name_pattern] - required: [expected, severity] additionalProperties: false properties:
tools/kconfig-checker/schemas/rules.yml new file +20 -0
@@ -0,0 +1,20 @@ +# SPDX-License-Identifier: GPL-2.0-only + +"$schema": "https://json-schema.org/draft-07/schema#" + +title: Schema for kconfig-checker rule files + +allOf: + - $ref: "base.yml" + + # + # The base schema leaves 'expected' and 'severity' optional so that + # overlay files can override only selected fields. In a full rules + # file though, these fields are mandatory for each rule. + # + - type: object + properties: + rules: + type: array + items: + required: [expected, severity]
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v1 06/10] kconfig-checker: Split schema to support component reuse
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Low] kconfig-checker: stale schema path in Documentation/tools/kconfig_checker.rst - [Low]…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Low] kconfig-checker: stale schema path in Documentation/tools/kconfig_checker.rst
- [Low] kconfig-checker: missing type: ignore on Draft7Validator import
- [Low] kconfig-checker: unused Schema.as_dict() method left behind in check.py
--
commit e95d8c61bd1b396a43ce4115372f7685c287a202
Author: Ahmed S. Darwish <[email protected]>
kconfig-checker: Split schema to support component reuse
This commit moves the common rule schema into schemas/base.yml, adds schemas/rules.yml for complete rule files, and updates check.py to resolve local file:// schema references using Draft7Validator.
tools/kconfig-checker/check.py except ModuleNotFoundError as e: · line 83
Quoted 9 lines
tools/kconfig-checker/check.py +1
-0@@ -80,6 +80,8 @@ except ModuleNotFoundError as e: # Actual script: # +from jsonschema import Draft7Validator
[Severity: Low]
Does this import need a "# type: ignore" comment to match the earlier "import jsonschema" statement? Without it, running "mypy --strict --no-warn-return-any check.py" as documented in the file header fails with a missing-stubs error (or fails on the earlier "# type: ignore" when types-jsonschema is installed).
[ ... ]
tools/kconfig-checker/check.py class RulesFile: · line 311
Quoted 8 lines
tools/kconfig-checker/check.py +1
-1def as_dict(self) -> YamlDict: return self.schema@@ -273,7 +308,7 @@ class RulesFile: def __init__(self, yaml_f: Path, schema: Schema): self.yaml = Helpers.load_yaml(yaml_f) - Helpers.validate_yaml(self.yaml, schema.as_dict(), yaml_f.name) + Helpers.validate_yaml(self.yaml, schema.validator, yaml_f.name)
[Severity: Low]
This isn't a bug, but now that RulesFile.__init__() and Helpers.validate_yaml() take schema.validator instead of schema.as_dict(), Schema.as_dict() has no remaining callers in this patch or later in the series and could be removed.
[ ... ]
Quoted 9 lines
tools/kconfig-checker/check.py +1
-0@@ -533,6 +568,7 @@ def parse_args(rules: list[str]) -> argparse.Namespace: def main() -> None: base_dir = Path(__file__).resolve().parent rules_dir = base_dir / 'rules' + schema_dir = base_dir / 'schemas' rules_l = sorted(path.stem for path in rules_dir.glob('*.yml')) args = parse_args(rules_l)
tools/kconfig-checker/check.py def main() -> None: · line 583
Quoted 5 lines
tools/kconfig-checker/check.py +1
-1@@ -544,7 +580,7 @@ def main() -> None: kconfig_f = args.config.resolve() kconfig = KernelConfig(kconfig_f) - schema_f = base_dir / 'schema.yml' + schema_f = schema_dir / 'rules.yml'
[Severity: Low]
Should Documentation/tools/kconfig_checker.rst also be updated here now that tools/kconfig-checker/schema.yml has moved to tools/kconfig-checker/schemas/base.yml and tools/kconfig-checker/schemas/rules.yml? Later commit "Documentation:
Describe kconfig-checker overlays" updates that section to reference tools/kconfig-checker/base.yml and tools/kconfig-checker/rules.yml, omitting the schemas/ directory component.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Re: [PATCH v1 06/10] kconfig-checker: Split schema to support component reuse
Quoted 6 lines · On Sat, 07 Nov 2026, [email protected] wrote:
Quoted 1 line
+from jsonschema import Draft7Validator
[Severity: Low]
Does this import need a "# type: ignore" comment to match the earlier "import jsonschema" statement?
I don't think so, as mypy does not complain in this situation:
$ mypy --version
mypy 2.4.0 (compiled: no)
$ mypy --strict --no-warn-return-any tools/kconfig-checker/check.py
Success: no issues found in 1 source file
So I'll keep this as-is.
Quoted 5 lines
[Severity: Low]
Schema.as_dict()has no remaining callers in this patch or later in the series and could be removed.
Correct, will remove it.
Quoted 7 lines
[Severity: Low]
ShouldDocumentation/tools/kconfig_checker.rstalso be updated here now thattools/kconfig-checker/schema.ymlhas moved totools/kconfig-checker/schemas/base.ymlandtools/kconfig-checker/schemas/rules.yml?
Correct, the documentation should be updated in this very same patch (instead of updating the docs two patches foreward.)
Thanks,
Ahmed
PATCH 7/10 kconfig-checker: Introduce overlays schema
In reply to Ahmed S. DarwishKeep expected and severity as optional for every rule.
This allows overlay files to be partial by design: they may override only selected fields of an existing rule.
--- tools/kconfig-checker/schemas/base.yml | 4 ++-- tools/kconfig-checker/schemas/overlay.yml | 28 +++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 tools/kconfig-checker/schemas/overlay.yml
tools/kconfig-checker/schemas/base.yml +2 -2
@@ -53,8 +53,8 @@ properties: # y option is expected to be enabled (built-in or module). # n option is expected to be disabled or unset. # allowed option is permitted and must not be reported as a violation. - # This is used to exempt a specific symbol from a broader - # `name_pattern` rule with `expected: n`. + # This is to be used either by overlays, or to exempt a specific + # symbol from a broader `name_pattern` rule with `expected: n`. # expected: type: string
tools/kconfig-checker/schemas/overlay.yml new file +28 -0
@@ -0,0 +1,28 @@ +# SPDX-License-Identifier: GPL-2.0-only + +"$schema": "https://json-schema.org/draft-07/schema#" + +title: Schema for kconfig-checker overlay files + +# +# Full rule files require 'expected' and 'severity' for every rule. +# Overlay files are partial by design: they may override only selected +# fields of an existing rule, so such fields are not required here. +# +# For example, preempt_rt.yml: +# +# rules: +# - name: CONFIG_DRM +# expected: n +# severity: info +# docs_hint: config +# +# and a custom-overlay.yml: +# +# rules: +# - name: CONFIG_DRM +# expected: allow +# + +allOf: + - $ref: "base.yml"
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v1 07/10] kconfig-checker: Introduce overlays schema
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] kconfig-checker: overlay.yml example uses invalid expected value allow --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] kconfig-checker: overlay.yml example uses invalid expected value allow
--
commit a10c99db2994945ab80143ea62fe4f2801513046
Author: Ahmed S. Darwish <[email protected]>
kconfig-checker: Introduce overlays schema
This commit introduces a JSON schema for kconfig-checker overlay files that references base.yml without requiring expected and severity on every rule.
Quoted 6 lines
tools/kconfig-checker/schemas/overlay.yml new file +0
-0@@ -0,0 +1,28 @@
[ ... ]
tools/kconfig-checker/schemas/overlay.yml line 24
Quoted 5 lines
tools/kconfig-checker/schemas/overlay.yml new file +5
-0+# and a custom-overlay.yml: +# +# rules: +# - name: CONFIG_DRM +# expected: allow
[Severity: Low]
Should this example use "expected: allowed" instead of "expected: allow"? base.yml restricts expected to y, n, or allowed, so an overlay written from this example fails schema validation.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Re: [PATCH v1 07/10] kconfig-checker: Introduce overlays schema
Quoted 9 lines · On Sat, 07 Nov 2026, [email protected] wrote:
tools/kconfig-checker/schemas/overlay.yml line 24
Quoted 6 lines
tools/kconfig-checker/schemas/overlay.yml new file +5
-0+# and a custom-overlay.yml: +# +# rules: +# - name: CONFIG_DRM +# expected: allow[Severity: Low]
Quoted 5 lines
Should this example use "expected: allowed" instead of "expected: allow"?
base.yml restricts expected to y, n, or allowed, so an overlay written from this example fails schema validation.
Correct, it should be 'allowed' in that comment above; will fix.
Thanks,
Ahmed
PATCH 8/10 kconfig-checker: Add support for rule overlays
In reply to Ahmed S. DarwishAn kconfig-checker overlay is a YAML file applied on top of an existing rules 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 checker.
--- tools/kconfig-checker/check.py | 89 +++++++++++++++++++++++++++++++++- 1 file changed, 88 insertions(+), 1 deletion(-)
tools/kconfig-checker/check.py +88 -1
@@ -7,7 +7,7 @@ # Main usage: # # $ check.py list-rules -# $ check.py check -c path/to/linux/.config -r preempt_rt +# $ check.py check -c path/to/linux/.config -r preempt_rt [-o path/to/overlay.yml] # # Notes: #
@@ -225,6 +225,48 @@ class Rule: if self.docs_hint: self.docs_hint = '#' + self.docs_hint + def overlay(self, overlay: YamlDict) -> None: + """Overlay passed yaml structure over existing data""" + if 'expected' in overlay: + self.expected = ExpectedValue[overlay['expected']] + + if 'severity' in overlay: + self.severity = Severity[overlay['severity']] + + if 'rationale' in overlay: + self.rationale = overlay['rationale'] + + if 'docs_hint' in overlay: + self.docs_hint = overlay['docs_hint'] + self._normalize_docs_hint() + + @staticmethod + def _ensure_required_fields(rule: YamlDict, rule_id: str) -> None: + """Ensure that passed rule has all required fields""" + + # Normal rule files require every rule to define both 'expected' + # and 'severity'. + # + # Overlay files are different: an overlay may update only selected + # fields of an existing rule, so the overlay schema permits these + # fields to be omitted. + # + # However, an overlay may also introduce a completely new rule, + # where such a rule has no existing base rule to inherit from. + # Manually check all required fields existence in that case. + + if 'expected' not in rule: + error( + f'Required field `expected` is missing from {rule_id}', + os.EX_DATAERR + ) + + if 'severity' not in rule: + error( + f'Required field `severity` is missing from {rule_id}', + os.EX_DATAERR + ) + class SymbolRule(Rule): """Rule entry for one .config symbol"""
@@ -232,6 +274,8 @@ class SymbolRule(Rule): def __init__(self, rule: YamlDict): self.symbol = rule['name'] + + super()._ensure_required_fields(rule, f'symbol {self.symbol}') super().__init__(rule) def _normalize_docs_hint(self) -> None:
@@ -253,6 +297,7 @@ class PatternRule(Rule): except re.error as e: error(f'Invalid symbol regex {regex}: {e}', os.EX_DATAERR) + super()._ensure_required_fields(rule, f'pattern {regex}') super().__init__(rule) @dataclass
@@ -333,6 +378,36 @@ class Issue: severity: Severity rationale: Optional[str] +class OverlayFile: + """YAML overlay file access""" + + overlays: YamlDict + + def __init__(self, overlay_f: Path, schema: Schema): + self.overlays = Helpers.load_yaml(overlay_f) + Helpers.validate_yaml(self.overlays, schema.validator, overlay_f.name) + + def apply(self, rules: Rules) -> Rules: + if 'docs_url' in self.overlays: + rules.docs_url = self.overlays['docs_url'] + + for overlay in self.overlays.get('rules', []): + if 'name' in overlay: + if rule := rules.get_symbol_rule(overlay['name']): + rule.overlay(overlay) + else: + rules.add_rule(SymbolRule(overlay)) + continue + + if 'name_pattern' in overlay: + if prule := rules.get_pattern_rule(overlay['name_pattern']): + prule.overlay(overlay) + else: + rules.add_rule(PatternRule(overlay)) + continue + + return rules + @dataclass class SymbolIssue(Issue): """Checker issue concerning a single .config symbol"""
@@ -563,6 +638,14 @@ def parse_args(rules: list[str]) -> argparse.Namespace: help='rules file to check against', ) + check_parser.add_argument( + '-o', + '--overlay', + metavar='OVERLAY_FILE', + type=Path, + help='file overlay over picked rules', + ) + return parser.parse_args() def main() -> None:
@@ -586,6 +669,10 @@ def main() -> None: rules_f = rules_dir / f'{args.rules}.yml' rules = RulesFile(rules_f, schema).parse() + if args.overlay: + schema = Schema(schema_dir / 'overlay.yml') + rules = OverlayFile(args.overlay, schema).apply(rules) + checker = Checker(kconfig, rules) report = checker.find_issues()
Signature · 1 line
2.56.0
PATCH 9/10 Documentation: Describe kconfig-checker overlays
In reply to Ahmed S. Darwish--- Documentation/tools/kconfig_checker.rst | 57 +++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-)
Documentation/tools/kconfig_checker.rst +54 -3
@@ -18,8 +18,12 @@ The checker can be invoked from anywhere in the file system:: check.py check -c path/to/.config -r preempt_rt -As described in Documentation/admin-guide/README.rst, it is also used by -``make checkconfig``. +An optional overlay may be supplied with ``-o``:: + + check.py check -c path/to/.config -r preempt_rt -o path/to/overlay.yml + +As described in Documentation/admin-guide/README.rst, the checker is also +used by ``make checkconfig``. External dependencies =====================
@@ -47,4 +51,51 @@ The checker's rule files are written in YAML, and are stored in:: The schema for these files is fully documented in:: - tools/kconfig-checker/schema.yml + tools/kconfig-checker/base.yml + tools/kconfig-checker/rules.yml + +Overlays +======== + +An overlay is a YAML file applied on top of an existing mainline rule +profile. Overlays are intended for local policy, distribution kernel +packaging, CI environments, and board support packages. + +An overlay may override fields of an existing rule. For example, if the +mainline PREEMPT_RT profile contains these rules: + +.. code-block:: yaml + + rules: + + - name: CONFIG_DRM + expected: n + severity: info + docs_hint: config + + - name: CONFIG_EFI_DISABLE_RUNTIME + expected: y + severity: medium + docs_hint: config + +A board support package may override such rules with an overlay like: + +.. code-block:: yaml + + rules: + + - name: CONFIG_DRM + expected: allowed + rationale: + This product requires a display controller and accepts the latency + cost. + + - name: CONFIG_EFI_DISABLE_RUNTIME + expected: n + rationale: + The efi_runtime workqueue is pinned to housekeeping CPU#0. + +.. note:: + + If a rule is generally useful to kernel users, please submit it to the + mainline profile instead of carrying it as a local overlay.
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v1 09/10] Documentation: Describe kconfig-checker overlays
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Low] docs: kconfig_checker: missing schemas/ directory in schema file paths - [Low] docs: kconfig_checker…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Low] docs: kconfig_checker: missing schemas/ directory in schema file paths
- [Low] docs: kconfig_checker: empty commit message body
--
commit a4e08eff4d708d44ce736f88aa1913f31f9a424d
Author: Ahmed S. Darwish <[email protected]>
Quoted 3 lines
Documentation: Describe kconfig-checker overlays
Signed-off-by Ahmed S. Darwish <[email protected]>
[Severity: Low]
Could a commit message body be added to describe the new overlay documentation and the schema file path updates?
Quoted 4 lines
Documentation/tools/kconfig_checker.rst +0
-0
[ ... ]
Documentation/tools/kconfig_checker.rst The checker's rule files are written in YAML, and are stored in:: · line 55
Quoted 7 lines
Documentation/tools/kconfig_checker.rst +2
-1@@ -47,4 +51,51 @@ The checker's rule files are written in YAML, and are stored in:: The schema for these files is fully documented in:: - tools/kconfig-checker/schema.yml + tools/kconfig-checker/base.yml + tools/kconfig-checker/rules.yml
[Severity: Low]
Are the schema file paths here missing the schemas/ directory component?
Commit "kconfig-checker: Split schema to support component reuse" and commit "kconfig-checker: Introduce overlays schema" placed these files under tools/kconfig-checker/schemas/ (base.yml, rules.yml, and overlay.yml).
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Re: [PATCH v1 09/10] Documentation: Describe kconfig-checker overlays
Quoted 4 lines · On Sat, 07 Nov 2026, [email protected] wrote:
Could a commit message body be added to describe the new overlay documentation and the schema file path updates?
I'll add a filler.
Quoted 10 lines
Documentation/tools/kconfig_checker.rst The checker's rule files are written in YAML, and are stored in:: · line 55
Quoted 6 lines
The schema for these files is fully documented in::
Documentation/tools/kconfig_checker.rst +2
-1- tools/kconfig-checker/schema.yml + tools/kconfig-checker/base.yml + tools/kconfig-checker/rules.yml[Severity: Low]
Are the schema file paths here missing the schemas/ directory component?
Correct, that's a documentation bug.
It should indeed be:
tools/kconfig-checker/schemas/base.yml
tools/kconfig-checker/schemas/rules.yml
Thanks,
Ahmed
PATCH 10/10 kconfig: Introduce OVERLAY= for make checkconfig
In reply to Ahmed S. DarwishFor the kconfig checkconfig target, allow passing a rules overlay file through an OVERLAY= parameter. This is mostly intended for distribution kernel packaging scripts, CI systems, and board support packages.
Document this parameter at the kernel's administration guide.
Note, the detailed overlay semantics are already explained at Documentation/tools/kconfig_checker.rst
--- Documentation/admin-guide/README.rst | 7 ++++++- scripts/kconfig/Makefile | 6 ++++-- 2 files changed, 10 insertions(+), 3 deletions(-)
Documentation/admin-guide/README.rst +6 -1
@@ -263,7 +263,7 @@ The kconfig build system can validate the generated kernel ``.config`` against a selected rules profile. Running ``make checkconfig`` prints usage information and the available profiles:: - Usage: make RULES=<profile> checkconfig + Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig Available RULES: preempt_rt For example, to validate the current configuration against the PREEMPT_RT
@@ -278,6 +278,11 @@ selected rules profile. Each diagnostic includes a severity, such as Apply the reported changes as needed and run ``make checkconfig`` 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 ``RULES=``. It is intended for +distributions kernel packaging scripts, CI systems, and board support +packages. + For more information, see Documentation/tools/kconfig_checker.rst Compiling the kernel
scripts/kconfig/Makefile +4 -2
@@ -126,6 +126,8 @@ testconfig: $(obj)/conf clean-files += tests/.cache checkconfig := $(PYTHON3) -B $(srctree)/tools/kconfig-checker/check.py +checkconfig_overlay = $(if $(OVERLAY),-o "$(OVERLAY)") + list_checkconfig_rules = \ echo -n >&2 "Available RULES: "; \ $(checkconfig) list-rules >&2; \
@@ -134,7 +136,7 @@ list_checkconfig_rules = \ PHONY += checkconfig checkconfig: $(Q)if [ -z "$(RULES)" ]; then \ - echo >&2 "Usage: make RULES=<profile> checkconfig"; \ + echo >&2 "Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig"; \ $(list_checkconfig_rules); \ exit 2; \ fi
@@ -143,7 +145,7 @@ checkconfig: $(list_checkconfig_rules); \ exit 2; \ fi - $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" + $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(checkconfig_overlay) # Help text used by make help help:
Signature · 1 line
2.56.0
Nicolas Schier
maintainerRe: [PATCH v1 10/10] kconfig: Introduce OVERLAY= for make checkconfig
Quoted 63 lines · Ahmed S. Darwish
For the kconfig checkconfig target, allow passing a rules overlay file through an OVERLAY= parameter. This is mostly intended for distribution kernel packaging scripts, CI systems, and board support packages.
Document this parameter at the kernel's administration guide.
Note, the detailed overlay semantics are already explained at
Documentation/tools/kconfig_checker.rstSigned-off-by Ahmed S. Darwish <[email protected]>--- Documentation/admin-guide/README.rst | 7 ++++++- scripts/kconfig/Makefile | 6 ++++-- 2 files changed, 10 insertions(+), 3 deletions(-)Documentation/admin-guide/README.rst +6
-1@@ -263,7 +263,7 @@ The kconfig build system can validate the generated kernel ``.config`` against a selected rules profile. Running ``make checkconfig`` prints usage information and the available profiles:: - Usage: make RULES=<profile> checkconfig + Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig Available RULES: preempt_rt For example, to validate the current configuration against the PREEMPT_RT@@ -278,6 +278,11 @@ selected rules profile. Each diagnostic includes a severity, such as Apply the reported changes as needed and run ``make checkconfig`` 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 ``RULES=``. It is intended for +distributions kernel packaging scripts, CI systems, and board support +packages. + For more information, see Documentation/tools/kconfig_checker.rst Compiling the kernelscripts/kconfig/Makefile +3
-1@@ -126,6 +126,8 @@ testconfig: $(obj)/conf clean-files += tests/.cache checkconfig := $(PYTHON3) -B $(srctree)/tools/kconfig-checker/check.py +checkconfig_overlay = $(if $(OVERLAY),-o "$(OVERLAY)") + list_checkconfig_rules = \ echo -n >&2 "Available RULES: "; \ $(checkconfig) list-rules >&2; \@@ -134,7 +136,7 @@ list_checkconfig_rules = \ PHONY += checkconfig checkconfig: $(Q)if [ -z "$(RULES)" ]; then \ - echo >&2 "Usage: make RULES=<profile> checkconfig"; \ + echo >&2 "Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig"; \ $(list_checkconfig_rules); \ exit 2; \ fi
scripts/kconfig/Makefile checkconfig: · line 148
Quoted 5 lines
scripts/kconfig/Makefile +1
-1@@ -143,7 +145,7 @@ checkconfig: $(list_checkconfig_rules); \ exit 2; \ fi - $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" + $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(checkconfig_overlay)
Please add the optional overlay arguments right here:
$(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(addprefix -o , "$(OVERLAY)")
<bike-shedding>
... or let kconfig-policy-checker read the 'OVERLAY' environment variable itself.
</bike-shedding>
Signature · 1 line
Nicolas
Re: [PATCH v1 10/10] kconfig: Introduce OVERLAY= for make checkconfig
Hi Nicolas,
Quoted 5 lines · Nicolas Schier
Please add the optional overlay arguments right here:
$(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(addprefix -o , "$(OVERLAY)")
Sure, will do.
Quoted 4 lines
<bike-shedding>
... or let kconfig-policy-checker read the 'OVERLAY' environment variable itself.
</bike-shedding>
I'm not a big fan of environment variables, especially in the sensitive domains of auditing and validation.
I've built a lot of Linux systems with Yocto, Debian tooling, etc., and environment variables led to some of the hardest debug sessions.
One checks CI logs, Yocto build logs, etc., and nothing directly leads to the problem at hand. Only to realize some hours later that it was an environment variable some layer on top of you has erroneously set :(
Thanks!
--
Ahmed S. Darwish
Linutronix GmbH
Re: [PATCH v1 10/10] kconfig: Introduce OVERLAY= for make checkconfig
Hi Nicolas,
Quoted 10 lines · Ahmed S. Darwish
Quoted 5 lines · Nicolas Schier
Please add the optional overlay arguments right here:
$(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(addprefix -o , "$(OVERLAY)")Sure, will do.
I've just tried the suggested addprefix function:
$ make V=1 RULES=preempt_rt checkconfig
...
python3 -B ./tools/kconfig-check/check.py check -c ".config" -p "preempt_rt" -o ""Notice the breakage due to -o "".
Unquoting OVERLAY will make it work:
$(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(addprefix -o , $(OVERLAY))
But it breaks the consistent pattern of quoting all passed variables.
So, can we keep it as it was originally done?
Namely:
checkconfig_overlay = $(if $(OVERLAY),-o "$(OVERLAY)")
...
checkconfig:
...
$(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(checkconfig_overlay)Thanks!
--
Ahmed S. Darwish
Linutronix GmbH
Nicolas Schier
maintainerRe: [PATCH v1 10/10] kconfig: Introduce OVERLAY= for make checkconfig
Quoted 30 lines · Ahmed S. Darwish
Hi Nicolas,
Quoted 10 lines · Ahmed S. Darwish
Quoted 5 lines · Nicolas Schier
Please add the optional overlay arguments right here:
$(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(addprefix -o , "$(OVERLAY)")Sure, will do.
I've just tried the suggested addprefix function:
$ make V=1 RULES=preempt_rt checkconfig ... python3 -B ./tools/kconfig-check/check.py check -c ".config" -p "preempt_rt" -o ""Notice the breakage due to -o "".
Unquoting OVERLAY will make it work:
$(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(addprefix -o , $(OVERLAY))But it breaks the consistent pattern of quoting all passed variables.
So, can we keep it as it was originally done?
Quoted 8 lines
Namely:
checkconfig_overlay = $(if $(OVERLAY),-o "$(OVERLAY)") ... checkconfig: ... $(Q)$(checkconfig) check -r "$(RULES)" -c "$(KCONFIG_CONFIG)" $(checkconfig_overlay)
well, ok.
I still do not think that a top-level make target is a good idea. Any important extension to checkconfig's arguments needs to be properly mapped, and as you won't have the 'checkconfig' target in the middle of a series of other targets, I still don't see a good reason for implementing a top-level Makefile integration. Thus, I still recommend to skip the top-level Makefile integration.
Signature · 1 line
Nicolas
Julian Braha
reviewerHi Ahmed,
Cool tool :)
Quoted 67 lines · Ahmed S. Darwish
Hi,
A month ago in Prague I proposed a kernel configuration checker:
PREEMPT_RTconfiguration: Best practices with kconfig-checker
https://youtu.be/hqnOmdpGBdQThis series adds kconfig-checker: a Python tool that checks the kernel .config against a set of YAML rules and reports all issues by severity.
The series also adds:
- a
PREEMPT_RTconfiguration ruleset
- a make checkconfig target
- support for ruleset overlaysExample:
$ make defconfig $ ./tools/kconfig-checker/check.py check -c .config -r preempt_rtConfiguration Issues with severity = FATAL
==========================================*
CONFIG_PREEMPT_RTis not in .configRationale:
https://docs.kernel.org/core-api/real-time/kernel-
configuration.html#config-preempt-rtConfiguration Issues with severity = HIGH
=========================================*
CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCEis unsetRationale:
https://docs.kernel.org/core-api/real-time/kernel-
configuration.html#config-cpu-freq-default-gov-performance* Below options are set:
CONFIG_SLUB_DEBUGRationale:
https://docs.kernel.org/core-api/real-time/kernel-
configuration.html#kernel-debug-optionsConfiguration Issues with severity = MEDIUM
===========================================* Below options are set:
CONFIG_CPU_FREQ_GOV_USERSPACE
CONFIG_CPU_FREQ_GOV_ONDEMANDRationale:
https://docs.kernel.org/core-api/real-time/kernel-
configuration.html#non-performance-cpu-frequency-governors### ... ### More output ### ...The same check can be run through make:
$ make RULES=preempt_rt checkconfig
Quoted 7 lines
If no ruleset is specified, the target prints the available rulesets:
$ make checkconfig Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig Available RULES: preempt_rtThe overlay mechanism allows distributions, CI systems, and Board Support
On the topic of distributions, this seems *a lot* like Canonical's Annotations [1], albeit yours uses YAML and supports matching option names with regex. As you say about PREEMPT_RT configuration not being "one-size-fits-all", similarly there are 100+ Ubuntu kernels that need to adhere to a configuration "policy".
So this seems to be a real problem that others are having.
Quoted 55 lines
Packages to apply additional policy or override existing mainline rules.
For example:
$ ./tools/kconfig-checker/check.py check \ -c path/to/.config \ -r preempt_rt \ -o path/to/overlay.ymlor:
$ make RULES=preempt_rt OVERLAY=path/to/overlay.yml checkconfigPatch 09/10 documents the overlay format and gives an example use case.
My goal is to get this into the kernel and have Debian's
PREEMPT_RTkernel packaging to use it. I'd also like systemd to use it: its README lists 60 kernel CONFIG_* symbols with different requirements severity.Thank you!
Ahmed8<-----
Ahmed S. Darwish (10):
kconfig-checker: Add schema for rule files
kconfig-checker: IntroducePREEMPT_RTconfiguration rules
kconfig-checker: Add the configuration checker code
kconfig: Introduce checkconfig target
Documentation: Describe kconfig-checker usage and design
kconfig-checker: Split schema to support component reuse
kconfig-checker: Introduce overlays schema
kconfig-checker: Add support for rule overlays
Documentation: Describe kconfig-checker overlays
kconfig: Introduce OVERLAY= for make checkconfigDocumentation/admin-guide/README.rst | 29 + .../real-time/kernel-configuration.rst | 3 + Documentation/tools/index.rst | 1 + Documentation/tools/kconfig_checker.rst | 101 +++ scripts/kconfig/Makefile | 25 + tools/kconfig-checker/check.py | 686 ++++++++++++++++++ tools/kconfig-checker/rules/preempt_rt.yml | 169 +++++ tools/kconfig-checker/schemas/base.yml | 114 +++ tools/kconfig-checker/schemas/overlay.yml | 28 + tools/kconfig-checker/schemas/rules.yml | 20 + 10 files changed, 1176 insertions(+)create mode 100644 Documentation/tools/kconfig_checker.rst create mode 100755 tools/kconfig-checker/check.py create mode 100644 tools/kconfig-checker/rules/preempt_rt.yml create mode 100644 tools/kconfig-checker/schemas/base.yml create mode 100644 tools/kconfig-checker/schemas/overlay.yml create mode 100644 tools/kconfig-checker/schemas/rules.yml
Quoted 3 lines
base-commit:
6628e7d4c6b25c8d18f1345e3a20d21829aae7e4-- 2.56.0
I think the name will cause confusion.
We already have some "kconfig checkers" in-tree, like scripts/kconfig-sym-check.pl
But actually, your tool is quite unrelated, because that one checks 'Kconfig' source files, while yours checks the user's '.config' file.
This has already caused some confusion in the past, for example in this thread [2], someone misunderstood which one 'kconfig-sym-check' actually checks.
In addition to .config vs Kconfig, the name is similar to 'kconfig-sym-check', but is not as descriptive about *what kind* of checks it performs.
[1] https://lists.ubuntu.com/archives/kernel-team/2023-June/140230.html
[2] https://lore.kernel.org/all/[email protected]/
- Julian Braha
Nathan Chancellor
maintainerQuoted 8 lines · Julian Braha
I think the name will cause confusion.
We already have some "kconfig checkers" in-tree, like
scripts/kconfig-sym-check.plBut actually, your tool is quite unrelated, because that one checks '
Kconfig' source files, while yours checks the user's '.config' file.
Quoted 7 lines
This has already caused some confusion in the past, for example in this thread [2], someone misunderstood which one 'kconfig-sym-check' actually checks.
In addition to .config vs
Kconfig, the name is similar to 'kconfig-sym-check', but is not as descriptive about *what kind* of checks it performs.
Yeah, I had similar thoughts when this initially appeared in my inbox. As you mentioned in your email, this is basically a policy checker (“we need these configuration options enabled or disabled to meet our requirements”), so maybe config-policy-checker or something like that would be clearer?
Signature · 2 lines
Cheers, Nathan
Quoted 18 lines · Nathan Chancellor
Quoted 8 lines · Julian Braha
I think the name will cause confusion.
We already have some "kconfig checkers" in-tree, like
scripts/kconfig-sym-check.plBut actually, your tool is quite unrelated, because that one checks '
Kconfig' source files, while yours checks the user's '.config' file.Quoted 7 lines
This has already caused some confusion in the past, for example in this thread [2], someone misunderstood which one 'kconfig-sym-check' actually checks.
In addition to .config vs
Kconfig, the name is similar to 'kconfig-sym-check', but is not as descriptive about *what kind* of checks it performs.
Quoted 5 lines
Yeah, I had similar thoughts when this initially appeared in my inbox. As you mentioned in your email, this is basically a policy checker (“we need these configuration options enabled or disabled to meet our requirements”), so maybe config-policy-checker or something like that would be clearer?
I would've loved to keep "kconfig" in the name so that outside the kernel, it's still clear it's about a kernel .config. For example, a Debian package for this tool can be called "kconfig-checker", "kconfig-policy-checker", etc.
What about kconfig-audit? Something like:
./tools/kconfig-audit/audit.py -c .config -p PREEMPT_RT
make POLICY=preempt_rt auditconfig
config-policy-checker does sound good, but it feels verbose.
Feedback appreciated.
Thanks!
--
Ahmed S. Darwish
Linutronix GmbH
Nathan Chancellor
maintainerQuoted 25 lines · Ahmed S. Darwish
Quoted 18 lines · Nathan Chancellor
Quoted 8 lines · Julian Braha
I think the name will cause confusion.
We already have some "kconfig checkers" in-tree, like
scripts/kconfig-sym-check.plBut actually, your tool is quite unrelated, because that one checks '
Kconfig' source files, while yours checks the user's '.config' file.Quoted 7 lines
This has already caused some confusion in the past, for example in this thread [2], someone misunderstood which one 'kconfig-sym-check' actually checks.
In addition to .config vs
Kconfig, the name is similar to 'kconfig-sym-check', but is not as descriptive about *what kind* of checks it performs.Quoted 5 lines
Yeah, I had similar thoughts when this initially appeared in my inbox. As you mentioned in your email, this is basically a policy checker (“we need these configuration options enabled or disabled to meet our requirements”), so maybe config-policy-checker or something like that would be clearer?
Quoted 4 lines
I would've loved to keep "kconfig" in the name so that outside the kernel, it's still clear it's about a kernel .config. For example, a Debian package for this tool can be called "kconfig-checker", "kconfig-policy-checker", etc.
Sure, that makes sense. Like Julian mentioned, kconfig is certainly an overloaded term but there is little we can do about that now :)
Quoted 9 lines
What about kconfig-audit? Something like:
./tools/kconfig-audit/audit.py-c .config -pPREEMPT_RTmake POLICY=preempt_rt auditconfig
config-policy-checker does sound good, but it feels verbose.
Feedback appreciated.
Yeah, config-policy-checker is a little verbose and might not translate into make rules well. kconfig-audit does not sound bad to me, especially with the rename of RULES to POLICY; at the very least, it is on the right track.
Signature · 2 lines
Cheers, Nathan
Quoted 9 lines · Nathan Chancellor
Quoted 7 lines · Ahmed S. Darwish
What about kconfig-audit? Something like:
./tools/kconfig-audit/audit.py-c .config -ppreempt_rtmake POLICY=preempt_rt auditconfig
Quoted 9 lines
Quoted 3 lines
config-policy-checker does sound good, but it feels verbose.
Feedback appreciated.
Yeah, config-policy-checker is a little verbose and might not translate into make rules well. kconfig-audit does not sound bad to me, especially with the rename of RULES to POLICY; at the very least, it is on the right track.
Thanks!
Then, kconfig-audit it is.
--
Ahmed S. Darwish
Linutronix GmbH
Hi Julian,
Quoted 3 lines · Julian Braha
Cool tool :)
Thanks!
Quoted 7 lines
Quoted 7 lines
If no ruleset is specified, the target prints the available rulesets:
$ make checkconfig Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig Available RULES: preempt_rt
Quoted 5 lines
Quoted 1 line
The overlay mechanism allows distributions, CI systems, and Board Support
On the topic of distributions, this seems *a lot* like Canonical's Annotations [1], albeit yours uses YAML and supports matching option names with regex.
The difference is not only in the implementation details. Please see below.
Quoted 6 lines
As you say about
PREEMPT_RTconfiguration not being "one-size-fits-all", similarly there are 100+ Ubuntu kernels that need to adhere to a configuration "policy".So this seems to be a real problem that others are having.
Kernel configuration is definitely getting trickier. That's why I've contributed the PREEMPT_RT kernel configuration guide earlier:
https://docs.kernel.org/core-api/real-time/kernel-configuration.html
Regarding the Canonical tool, it's the first time I see it. From that announce e-mail, it seems that they're using it for generating a .config:
Starting with 22.04 (Jammy Jellyfish), Ubuntu kernels are now using only annotations to /generate/ their corresponding .config.
...
$ ./debian/scripts/misc/annotations --arch amd64 --flavour generic > .config
Yocto also provides a very light concept of .config generation:
https://docs.yoctoproject.org/kernel-dev/common.html#creating-configuration-fragments
But this tool does not conern itself with generation. That is, Canonical can use this tool to validate that they've generated the right thing! ;-)
Quoted 17 lines
Quoted 11 lines
For example:
$ ./tools/kconfig-checker/check.py check \ -c path/to/.config \ -r preempt_rt \ -o path/to/overlay.ymlor:
$ make RULES=preempt_rt OVERLAY=path/to/overlay.yml checkconfigI think the name will cause confusion.
We already have some "kconfig checkers" in-tree, like
scripts/kconfig-sym-check.pl
Quoted 7 lines
But actually, your tool is quite unrelated, because that one checks '
Kconfig' source files, while yours checks the user's '.config' file.This has already caused some confusion in the past, for example in this thread [2], someone misunderstood which one 'kconfig-sym-check' actually checks.
Haha, good point :)
Quoted 3 lines
In addition to .config vs
Kconfig, the name is similar to 'kconfig-sym-check', but is not as descriptive about *what kind* of checks it performs.
Maybe "kconfig-audit" would be a good name?
It makes it clear that it "audits" a .config against a certain policy.
Thanks!
--
Ahmed S. Darwish
Linutronix GmbH
Julian Braha
reviewerQuoted 40 lines · Ahmed S. Darwish
Hi Julian,
Quoted 2 lines · Julian Braha
Cool tool 🙂
Thanks!
Quoted 10 lines
Quoted 7 lines
If no ruleset is specified, the target prints the available rulesets:
$ make checkconfig Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig Available RULES: preempt_rtThe overlay mechanism allows distributions, CI systems, and Board Support
On the topic of distributions, this seems *a lot* like Canonical's Annotations [1], albeit yours uses YAML and supports matching option names with regex.
The difference is not only in the implementation details. Please see below.
Quoted 6 lines
As you say about
PREEMPT_RTconfiguration not being "one-size-fits-all", similarly there are 100+ Ubuntu kernels that need to adhere to a configuration "policy".So this seems to be a real problem that others are having.
Kernel configuration is definitely getting trickier. That's why I've contributed the
PREEMPT_RTkernel configuration guide earlier:https://docs.kernel.org/core-api/real-time/kernel-configuration.html
Regarding the Canonical tool, it's the first time I see it. From that announce e-mail, it seems that they're using it for generating a .config:
Starting with 22.04 (Jammy Jellyfish), Ubuntu kernels are now using only annotations to /generate/ their corresponding .config.
... $ ./debian/scripts/misc/annotations --arch amd64 --flavour generic > .config
Quoted 7 lines
Yocto also provides a very light concept of .config generation:
https://docs.yoctoproject.org/kernel-dev/common.html#creating-
configuration-fragmentsBut this tool does not conern itself with generation. That is, Canonical can use this tool to validate that they've generated the right thing! 😉
Yeah, Annotations also supports generation with --export.
But it does support validating a config with a policy using --check [1]
Anyway, the point was to provide context for the maintainers that this problem is bigger than PREEMPT_RT. I want to see this functionality / your tool in upstream.
[1]
https://git.launchpad.net/~arighi/+git/annotations-tools/tree/kconfig/run.py?h=main#n117
- Julian Braha
Quoted 5 lines · Julian Braha
Yeah, Annotations also supports generation with --export.
But it does support validating a config with a policy using --check [1]
I see.
Quoted 3 lines
Anyway, the point was to provide context for the maintainers that this problem is bigger than
PREEMPT_RT. I want to see this functionality / your tool in upstream.
Thank you, and I apologize for my defensiveness.
--
Ahmed S. Darwish
Linutronix GmbH
Nicolas Schier
maintainerQuoted 106 lines · Ahmed S. Darwish
Hi,
A month ago in Prague I proposed a kernel configuration checker:
PREEMPT_RTconfiguration: Best practices with kconfig-checker
https://youtu.be/hqnOmdpGBdQThis series adds kconfig-checker: a Python tool that checks the kernel .config against a set of YAML rules and reports all issues by severity.
The series also adds:
- a
PREEMPT_RTconfiguration ruleset
- a make checkconfig target
- support for ruleset overlaysExample:
$ make defconfig $ ./tools/kconfig-checker/check.py check -c .config -r preempt_rtConfiguration Issues with severity = FATAL
==========================================*
CONFIG_PREEMPT_RTis not in .configRationale:
https://docs.kernel.org/core-api/real-time/kernel-configuration.html#config-preempt-rtConfiguration Issues with severity = HIGH
=========================================*
CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCEis unset* Below options are set:
CONFIG_SLUB_DEBUGRationale:
https://docs.kernel.org/core-api/real-time/kernel-configuration.html#kernel-debug-optionsConfiguration Issues with severity = MEDIUM
===========================================* Below options are set:
CONFIG_CPU_FREQ_GOV_USERSPACE
CONFIG_CPU_FREQ_GOV_ONDEMAND### ...
### More output
### ...The same check can be run through make:
$ make RULES=preempt_rt checkconfigIf no ruleset is specified, the target prints the available rulesets:
$ make checkconfig Usage: make RULES=<profile> [OVERLAY=<overlay>] checkconfig Available RULES: preempt_rtThe overlay mechanism allows distributions, CI systems, and Board Support Packages to apply additional policy or override existing mainline rules.
For example:
$ ./tools/kconfig-checker/check.py check \ -c path/to/.config \ -r preempt_rt \ -o path/to/overlay.ymlor:
$ make RULES=preempt_rt OVERLAY=path/to/overlay.yml checkconfigPatch 09/10 documents the overlay format and gives an example use case.
My goal is to get this into the kernel and have Debian's
PREEMPT_RTkernel packaging to use it. I'd also like systemd to use it: its README lists 60 kernel CONFIG_* symbols with different requirements severity.Thank you!
Ahmed8<-----
Ahmed S. Darwish (10):
kconfig-checker: Add schema for rule files
kconfig-checker: IntroducePREEMPT_RTconfiguration rules
kconfig-checker: Add the configuration checker code
kconfig: Introduce checkconfig target
Documentation: Describe kconfig-checker usage and design
kconfig-checker: Split schema to support component reuse
kconfig-checker: Introduce overlays schema
kconfig-checker: Add support for rule overlays
Documentation: Describe kconfig-checker overlays
kconfig: Introduce OVERLAY= for make checkconfig
Quoted 11 lines
Documentation/admin-guide/README.rst | 29 + .../real-time/kernel-configuration.rst | 3 + Documentation/tools/index.rst | 1 + Documentation/tools/kconfig_checker.rst | 101 +++ scripts/kconfig/Makefile | 25 + tools/kconfig-checker/check.py | 686 ++++++++++++++++++ tools/kconfig-checker/rules/preempt_rt.yml | 169 +++++ tools/kconfig-checker/schemas/base.yml | 114 +++ tools/kconfig-checker/schemas/overlay.yml | 28 + tools/kconfig-checker/schemas/rules.yml | 20 + 10 files changed, 1176 insertions(+)
Thanks! I know some people who are definitly interested in such a config policy checker.
Please prepare a new MAINTAINERS entry in a respin. Are you planning to maintain it after inclusion?
Signature · 1 line
Nicolas
Hi Nicolas,
Quoted 4 lines · Nicolas Schier
Thanks! I know some people who are definitly interested in such a config policy checker.
Great, thanks!
I hope this leads to more mainline kernel configuration policies as well.
On the user-space side, it's one of the reasons I'm versioning the schema in v2. This way, projects like systemd can ship their own kernel policy file, and that policy will be guaranteed to work with all future versions of this tool.
So it's all mainline-first; both kernel upstream and userspace downstream.
Quoted 1 line
Please prepare a new
MAINTAINERSentry in a respin.
Sure.
Beside a separate entry for the checker itself, I'll also add:
F: tools/kconfig-audit/policies/preempt_rt.yml
to the 'Real-time Linux (PREEMPT_RT)' entry.
Quoted 1 line
Are you planning to maintain it after inclusion?
Yes, I'll be happy to maintain it.
Would it be OK if one or two people from the Kconfig side also step-up as reviewrs? Julian? Nicolas? Nathan?
Thanks,
--
Ahmed S. Darwish
Linutronix GmbH
Nathan Chancellor
maintainerQuoted 7 lines · Ahmed S. Darwish
Quoted 1 line · Nicolas Schier
Are you planning to maintain it after inclusion?
Yes, I'll be happy to maintain it.
Would it be OK if one or two people from the
Kconfigside also step-up as reviewrs? Julian? Nicolas? Nathan?
Sure, I have no objections to being a reviewer for this tool. What tree(s) do you envision this initially landing in and taking subsequent updates through?
Signature · 2 lines
Cheers, Nathan
Quoted 9 lines · Nathan Chancellor
Quoted 4 lines · Ahmed S. Darwish
Would it be OK if one or two people from the
Kconfigside also step-up as reviewrs? Julian? Nicolas? Nathan?Sure, I have no objections to being a reviewer for this tool.
Thanks a lot!
Quoted 4 lines
What tree(s) do you envision this initially landing in and taking subsequent updates through?
Unless you have any objections, I think kbuild would be the right tree ;)
All the best,
Ahmed
Nathan Chancellor
maintainerQuoted 6 lines · Ahmed S. Darwish
Quoted 3 lines · Nathan Chancellor
What tree(s) do you envision this initially landing in and taking subsequent updates through?
Unless you have any objections, I think kbuild would be the right tree ;)
No objections from me, I just wanted to make sure we were all on the same page :)
Signature · 2 lines
Cheers, Nathan
Julian Braha
reviewerQuoted 24 lines · Ahmed S. Darwish
Hi Nicolas,
Quoted 3 lines · Nicolas Schier
Thanks! I know some people who are definitly interested in such a config policy checker.
Great, thanks!
I hope this leads to more mainline kernel configuration policies as well.
On the user-space side, it's one of the reasons I'm versioning the schema in v2. This way, projects like systemd can ship their own kernel policy file, and that policy will be guaranteed to work with all future versions of this tool.
So it's all mainline-first; both kernel upstream and userspace downstream.
Quoted 1 line
Please prepare a new
MAINTAINERSentry in a respin.Sure.
Beside a separate entry for the checker itself, I'll also add:
F:
tools/kconfig-audit/policies/preempt_rt.yml
Quoted 7 lines
to the 'Real-time Linux (
PREEMPT_RT)' entry.Quoted 1 line
Are you planning to maintain it after inclusion?
Yes, I'll be happy to maintain it.
Would it be OK if one or two people from the
Kconfigside also step-up as reviewrs? Julian? Nicolas? Nathan?
I will politely decline the official title, but I will (unofficially) watch and review some patches if merged :)
- Julian Braha
Nicolas Schier
maintainerQuoted 27 lines · Ahmed S. Darwish
Hi Nicolas,
Quoted 4 lines · Nicolas Schier
Thanks! I know some people who are definitly interested in such a config policy checker.
Great, thanks!
I hope this leads to more mainline kernel configuration policies as well.
On the user-space side, it's one of the reasons I'm versioning the schema in v2. This way, projects like systemd can ship their own kernel policy file, and that policy will be guaranteed to work with all future versions of this tool.
So it's all mainline-first; both kernel upstream and userspace downstream.
Quoted 1 line
Please prepare a new
MAINTAINERSentry in a respin.Sure.
Beside a separate entry for the checker itself, I'll also add:
F:
tools/kconfig-audit/policies/preempt_rt.yml
Quoted 8 lines
to the 'Real-time Linux (
PREEMPT_RT)' entry.Quoted 1 line
Are you planning to maintain it after inclusion?
Yes, I'll be happy to maintain it.
Would it be OK if one or two people from the
Kconfigside also step-up as reviewrs? Julian? Nicolas? Nathan?
Sorry, I am out-of-time already.
Signature · 1 line
Nicolas