Kernel API Specification Framework with kerneldoc integration
Subsystems (9)
v3 cover Kernel API Specification Framework with kerneldoc integration
This patch series introduces a framework for formally specifying kernel APIs, addressing the long-standing challenge of maintaining stable interfaces between the kernel and user-space programs. As outlined in previous discussions about kernel ABI stability, the lack of machine-readable API specifications has led to inadvertent breakages and inconsistent validation across system calls and IOCTLs.
The framework represents a fundamental shift from macro-based API specifications to kerneldoc integration. Instead of requiring developers to write specifications using C macros separate from documentation, the framework now leverages the existing kerneldoc infrastructure. This unification means developers write API specifications as part of their regular documentation workflow, with the build system automatically generating machine-readable C macros from these comments.
Changes since RFC v2:
1. Kerneldoc Integration: transition from C macros to kerneldoc comments.
2. Structured Parameter Specifications: Support for complex data structures with field-level constraints, including ranges, enums, and validation groups.
3. Hybrid Documentation Approach: Core API specifications remain inline with the implementation for tight coupling, while extended documentation (examples, detailed notes, complex constraints) can be maintained in separate files under Documentation/.
Sasha Levin (4):
kernel/api: introduce kernel API specification framework kernel/api: enable kerneldoc-based API specifications mm/mlock: add API specification for mlock kernel/sched: add specs for sys_sched_setattr()
Documentation/admin-guide/kernel-api-spec.rst | 507 ++++++ Documentation/userspace-api/syscalls/mlock.rst| 118 ++ MAINTAINERS | 9 + arch/um/kernel/dyn.lds.S | 3 + arch/um/kernel/uml.lds.S | 3 + arch/x86/kernel/vmlinux.lds.S | 3 + include/asm-generic/vmlinux.lds.h | 20 + include/linux/kernel_api_spec.h | 1527 +++++++++++++++++ include/linux/syscall_api_spec.h | 137 ++ include/linux/syscalls.h | 38 + init/Kconfig | 2 + kernel/Makefile | 1 + kernel/api/Kconfig | 35 + kernel/api/Makefile | 26 + kernel/api/kernel_api_spec.c | 1122 ++++++++++++ kernel/sched/syscalls.c | 168 +- mm/mlock.c | 85 + scripts/Makefile.build | 28 + scripts/generate_api_specs.sh | 59 + scripts/kernel-doc.py | 5 + scripts/lib/kdoc/kdoc_apispec.py | 623 +++++++ scripts/lib/kdoc/kdoc_output.py | 5 +- scripts/lib/kdoc/kdoc_parser.py | 54 +- 23 files changed, 4574 insertions(+), 4 deletions(-) create mode 100644 Documentation/admin-guide/kernel-api-spec.rst create mode 100644 Documentation/userspace-api/syscalls/mlock.rst create mode 100644 include/linux/kernel_api_spec.h create mode 100644 include/linux/syscall_api_spec.h create mode 100644 kernel/api/Kconfig create mode 100644 kernel/api/Makefile create mode 100644 kernel/api/kernel_api_spec.c create mode 100755 scripts/generate_api_specs.sh create mode 100644 scripts/lib/kdoc/kdoc_apispec.py
Signature · 1 line
2.39.5
RFC v3 1/4 kernel/api: introduce kernel API specification framework
Add a comprehensive framework for formally documenting kernel APIs with inline specifications. This framework provides:
- Structured API documentation with parameter specifications, return values, error conditions, and execution context requirements
- Runtime validation capabilities for debugging (CONFIG_KAPI_RUNTIME_CHECKS)
- Export of specifications via debugfs for tooling integration
- Support for both internal kernel APIs and system calls
The framework stores specifications in a dedicated ELF section and provides infrastructure for:
- Compile-time validation of specifications
- Runtime querying of API documentation
- Machine-readable export formats
- Integration with existing SYSCALL_DEFINE macros
This commit introduces the core infrastructure without modifying any existing APIs. Subsequent patches will add specifications to individual subsystems.
--- Documentation/admin-guide/kernel-api-spec.rst | 507 ++++++ MAINTAINERS | 9 + arch/um/kernel/dyn.lds.S | 3 + arch/um/kernel/uml.lds.S | 3 + arch/x86/kernel/vmlinux.lds.S | 3 + include/asm-generic/vmlinux.lds.h | 20 + include/linux/kernel_api_spec.h | 1527 +++++++++++++++++ include/linux/syscall_api_spec.h | 137 ++ include/linux/syscalls.h | 38 + init/Kconfig | 2 + kernel/Makefile | 1 + kernel/api/Kconfig | 35 + kernel/api/Makefile | 7 + kernel/api/kernel_api_spec.c | 1122 ++++++++++++ 14 files changed, 3414 insertions(+) create mode 100644 Documentation/admin-guide/kernel-api-spec.rst create mode 100644 include/linux/kernel_api_spec.h create mode 100644 include/linux/syscall_api_spec.h create mode 100644 kernel/api/Kconfig create mode 100644 kernel/api/Makefile create mode 100644 kernel/api/kernel_api_spec.c
Documentation/admin-guide/kernel-api-spec.rst new file +507 -0
@@ -0,0 +1,507 @@ +.. SPDX-License-Identifier: GPL-2.0 + +====================================== +Kernel API Specification Framework +====================================== + +:Author: Sasha Levin <[email protected]> +:Date: June 2025 + +.. contents:: Table of Contents + :depth: 3 + :local: + +Introduction +============ + +The Kernel API Specification Framework (KAPI) provides a comprehensive system for +formally documenting, validating, and introspecting kernel APIs. This framework +addresses the long-standing challenge of maintaining accurate, machine-readable +documentation for the thousands of internal kernel APIs and system calls. + +Purpose and Goals +----------------- + +The framework aims to: + +1. **Improve API Documentation**: Provide structured, inline documentation that + lives alongside the code and is maintained as part of the development process. + +2. **Enable Runtime Validation**: Optionally validate API usage at runtime to catch + common programming errors during development and testing. + +3. **Support Tooling**: Export API specifications in machine-readable formats for + use by static analyzers, documentation generators, and development tools. + +4. **Enhance Debugging**: Provide detailed API information at runtime through debugfs + for debugging and introspection. + +5. **Formalize Contracts**: Explicitly document API contracts including parameter + constraints, execution contexts, locking requirements, and side effects. + +Architecture Overview +===================== + +Components +---------- + +The framework consists of several key components: + +1. **Core Framework** (``kernel/api/kernel_api_spec.c``) + + - API specification registration and storage + - Runtime validation engine + - Specification lookup and querying + +2. **DebugFS Interface** (``kernel/api/kapi_debugfs.c``) + + - Runtime introspection via ``/sys/kernel/debug/kapi/`` + - JSON and XML export formats + - Per-API detailed information + +3. **IOCTL Support** (``kernel/api/ioctl_validation.c``) + + - Extended framework for IOCTL specifications + - Automatic validation wrappers + - Structure field validation + +4. **Specification Macros** (``include/linux/kernel_api_spec.h``) + + - Declarative macros for API documentation + - Type-safe parameter specifications + - Context and constraint definitions + +Data Model +---------- + +The framework uses a hierarchical data model:: + + kernel_api_spec + ├── Basic Information + │ ├── name (API function name) + │ ├── version (specification version) + │ ├── description (human-readable description) + │ └── kernel_version (when API was introduced) + │ + ├── Parameters (up to 16) + │ └── kapi_param_spec + │ ├── name + │ ├── type (int, pointer, string, etc.) + │ ├── direction (in, out, inout) + │ ├── constraints (range, mask, enum values) + │ └── validation rules + │ + ├── Return Value + │ └── kapi_return_spec + │ ├── type + │ ├── success conditions + │ └── validation rules + │ + ├── Error Conditions (up to 32) + │ └── kapi_error_spec + │ ├── error code + │ ├── condition description + │ └── recovery advice + │ + ├── Execution Context + │ ├── allowed contexts (process, interrupt, etc.) + │ ├── locking requirements + │ └── preemption/interrupt state + │ + └── Side Effects + ├── memory allocation + ├── state changes + └── signal handling + +Usage Guide +=========== + +Basic API Specification +----------------------- + +To document a kernel API, use the specification macros in the implementation file: + +.. code-block:: c + + #include <linux/kernel_api_spec.h> + + KAPI_DEFINE_SPEC(kmalloc_spec, kmalloc, "3.0") + KAPI_DESCRIPTION("Allocate kernel memory") + KAPI_PARAM(0, size, KAPI_TYPE_SIZE_T, KAPI_DIR_IN, + "Number of bytes to allocate") + KAPI_PARAM_RANGE(0, 0, KMALLOC_MAX_SIZE) + KAPI_PARAM(1, flags, KAPI_TYPE_FLAGS, KAPI_DIR_IN, + "Allocation flags (GFP_*)") + KAPI_PARAM_MASK(1, __GFP_BITS_MASK) + KAPI_RETURN(KAPI_TYPE_POINTER, "Pointer to allocated memory or NULL") + KAPI_ERROR(ENOMEM, "Out of memory") + KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SOFTIRQ | KAPI_CTX_HARDIRQ) + KAPI_SIDE_EFFECT("Allocates memory from kernel heap") + KAPI_LOCK_NOT_REQUIRED("Any lock") + KAPI_END_SPEC + + void *kmalloc(size_t size, gfp_t flags) + { + /* Implementation */ + } + +System Call Specification +------------------------- + +System calls use specialized macros: + +.. code-block:: c + + KAPI_DEFINE_SYSCALL_SPEC(open_spec, open, "1.0") + KAPI_DESCRIPTION("Open a file") + KAPI_PARAM(0, pathname, KAPI_TYPE_USER_STRING, KAPI_DIR_IN, + "Path to file") + KAPI_PARAM_PATH(0, PATH_MAX) + KAPI_PARAM(1, flags, KAPI_TYPE_FLAGS, KAPI_DIR_IN, + "Open flags (O_*)") + KAPI_PARAM(2, mode, KAPI_TYPE_MODE_T, KAPI_DIR_IN, + "File permissions (if creating)") + KAPI_RETURN(KAPI_TYPE_INT, "File descriptor or -1") + KAPI_ERROR(EACCES, "Permission denied") + KAPI_ERROR(ENOENT, "File does not exist") + KAPI_ERROR(EMFILE, "Too many open files") + KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) + KAPI_SIGNAL(EINTR, "Open can be interrupted by signal") + KAPI_END_SYSCALL_SPEC + +IOCTL Specification +------------------- + +IOCTLs have extended support for structure validation: + +.. code-block:: c + + KAPI_DEFINE_IOCTL_SPEC(vidioc_querycap_spec, VIDIOC_QUERYCAP, + "VIDIOC_QUERYCAP", + sizeof(struct v4l2_capability), + sizeof(struct v4l2_capability), + "video_fops") + KAPI_DESCRIPTION("Query device capabilities") + KAPI_IOCTL_FIELD(driver, KAPI_TYPE_CHAR_ARRAY, KAPI_DIR_OUT, + "Driver name", 16) + KAPI_IOCTL_FIELD(card, KAPI_TYPE_CHAR_ARRAY, KAPI_DIR_OUT, + "Device name", 32) + KAPI_IOCTL_FIELD(version, KAPI_TYPE_U32, KAPI_DIR_OUT, + "Driver version") + KAPI_IOCTL_FIELD(capabilities, KAPI_TYPE_FLAGS, KAPI_DIR_OUT, + "Device capabilities") + KAPI_END_IOCTL_SPEC + +Runtime Validation +================== + +Enabling Validation +------------------- + +Runtime validation is controlled by kernel configuration: + +1. Enable ``CONFIG_KAPI_SPEC`` to build the framework +2. Enable ``CONFIG_KAPI_RUNTIME_CHECKS`` for runtime validation +3. Optionally enable ``CONFIG_KAPI_SPEC_DEBUGFS`` for debugfs interface + +Validation Modes +---------------- + +The framework supports several validation modes: + +.. code-block:: c + + /* Enable validation for specific API */ + kapi_enable_validation("kmalloc"); + + /* Enable validation for all APIs */ + kapi_enable_all_validation(); + + /* Set validation level */ + kapi_set_validation_level(KAPI_VALIDATE_FULL); + +Validation Levels: + +- ``KAPI_VALIDATE_NONE``: No validation +- ``KAPI_VALIDATE_BASIC``: Type and NULL checks only +- ``KAPI_VALIDATE_NORMAL``: Basic + range and constraint checks +- ``KAPI_VALIDATE_FULL``: All checks including custom validators + +Custom Validators +----------------- + +APIs can register custom validation functions: + +.. code-block:: c + + static bool validate_buffer_size(const struct kapi_param_spec *spec, + const void *value, void *context) + { + size_t size = *(size_t *)value; + struct my_context *ctx = context; + + return size > 0 && size <= ctx->max_buffer_size; + } + + KAPI_PARAM_CUSTOM_VALIDATOR(0, validate_buffer_size) + +DebugFS Interface +================= + +The debugfs interface provides runtime access to API specifications: + +Directory Structure +------------------- + +:: + + /sys/kernel/debug/kapi/ + ├── apis/ # All registered APIs + │ ├── kmalloc/ + │ │ ├── specification # Human-readable spec + │ │ ├── json # JSON format + │ │ └── xml # XML format + │ └── open/ + │ └── ... + ├── summary # Overview of all APIs + ├── validation/ # Validation controls + │ ├── enabled # Global enable/disable + │ ├── level # Validation level + │ └── stats # Validation statistics + └── export/ # Bulk export options + ├── all.json # All specs in JSON + └── all.xml # All specs in XML + +Usage Examples +-------------- + +Query specific API:: + + $ cat /sys/kernel/debug/kapi/apis/kmalloc/specification + API: kmalloc + Version: 3.0 + Description: Allocate kernel memory + + Parameters: + [0] size (size_t, in): Number of bytes to allocate + Range: 0 - 4194304 + [1] flags (flags, in): Allocation flags (GFP_*) + Mask: 0x1ffffff + + Returns: pointer - Pointer to allocated memory or NULL + + Errors: + ENOMEM: Out of memory + + Context: process, softirq, hardirq + + Side Effects: + - Allocates memory from kernel heap + +Export all specifications:: + + $ cat /sys/kernel/debug/kapi/export/all.json > kernel-apis.json + +Enable validation for specific API:: + + $ echo 1 > /sys/kernel/debug/kapi/apis/kmalloc/validate + +Performance Considerations +========================== + +Memory Overhead +--------------- + +Each API specification consumes approximately 2-4KB of memory. With thousands +of kernel APIs, this can add up to several megabytes. Consider: + +1. Building with ``CONFIG_KAPI_SPEC=n`` for production kernels +2. Using ``__init`` annotations for APIs only used during boot +3. Implementing lazy loading for rarely used specifications + +Runtime Overhead +---------------- + +When ``CONFIG_KAPI_RUNTIME_CHECKS`` is enabled: + +- Each validated API call adds 50-200ns overhead +- Complex validations (custom validators) may add more +- Use validation only in development/testing kernels + +Optimization Strategies +----------------------- + +1. **Compile-time optimization**: When validation is disabled, all + validation code is optimized away by the compiler. + +2. **Selective validation**: Enable validation only for specific APIs + or subsystems under test. + +3. **Caching**: The framework caches validation results for repeated + calls with identical parameters. + +Documentation Generation +------------------------ + +The framework exports specifications via debugfs that can be used +to generate documentation. Tools for automatic documentation generation +from specifications are planned for future development. + +IDE Integration +--------------- + +Modern IDEs can use the JSON export for: + +- Parameter hints +- Type checking +- Context validation +- Error code documentation + +Testing Framework +----------------- + +The framework includes test helpers:: + + #ifdef CONFIG_KAPI_TESTING + /* Verify API behaves according to specification */ + kapi_test_api("kmalloc", test_cases); + #endif + +Best Practices +============== + +Writing Specifications +---------------------- + +1. **Be Comprehensive**: Document all parameters, errors, and side effects +2. **Keep Updated**: Update specs when API behavior changes +3. **Use Examples**: Include usage examples in descriptions +4. **Validate Constraints**: Define realistic constraints for parameters +5. **Document Context**: Clearly specify allowed execution contexts + +Maintenance +----------- + +1. **Version Specifications**: Increment version when API changes +2. **Deprecation**: Mark deprecated APIs and suggest replacements +3. **Cross-reference**: Link related APIs in descriptions +4. **Test Specifications**: Verify specs match implementation + +Common Patterns +--------------- + +**Optional Parameters**:: + + KAPI_PARAM(2, optional_arg, KAPI_TYPE_POINTER, KAPI_DIR_IN, + "Optional argument (may be NULL)") + KAPI_PARAM_OPTIONAL(2) + +**Variable Arguments**:: + + KAPI_PARAM(1, fmt, KAPI_TYPE_FORMAT_STRING, KAPI_DIR_IN, + "Printf-style format string") + KAPI_PARAM_VARIADIC(2, "Format arguments") + +**Callback Functions**:: + + KAPI_PARAM(1, callback, KAPI_TYPE_FUNCTION_PTR, KAPI_DIR_IN, + "Callback function") + KAPI_PARAM_CALLBACK(1, "int (*)(void *data)", "data") + +Troubleshooting +=============== + +Common Issues +------------- + +**Specification Not Found**:: + + kernel: KAPI: Specification for 'my_api' not found + + Solution: Ensure KAPI_DEFINE_SPEC is in the same translation unit + as the function implementation. + +**Validation Failures**:: + + kernel: KAPI: Validation failed for kmalloc parameter 'size': + value 5242880 exceeds maximum 4194304 + + Solution: Check parameter constraints or adjust specification if + the constraint is incorrect. + +**Build Errors**:: + + error: 'KAPI_TYPE_UNKNOWN' undeclared + + Solution: Include <linux/kernel_api_spec.h> and ensure + CONFIG_KAPI_SPEC is enabled. + +Debug Options +------------- + +Enable verbose debugging:: + + echo 8 > /proc/sys/kernel/printk + echo 1 > /sys/kernel/debug/kapi/debug/verbose + +Future Directions +================= + +Planned Features +---------------- + +1. **Automatic Extraction**: Tool to extract specifications from existing + kernel-doc comments + +2. **Contract Verification**: Static analysis to verify implementation + matches specification + +3. **Performance Profiling**: Measure actual API performance against + documented expectations + +4. **Fuzzing Integration**: Use specifications to guide intelligent + fuzzing of kernel APIs + +5. **Version Compatibility**: Track API changes across kernel versions + +Research Areas +-------------- + +1. **Formal Verification**: Use specifications for mathematical proofs + of correctness + +2. **Runtime Monitoring**: Detect specification violations in production + with minimal overhead + +3. **API Evolution**: Analyze how kernel APIs change over time + +4. **Security Applications**: Use specifications for security policy + enforcement + +Contributing +============ + +Submitting Specifications +------------------------- + +1. Add specifications to the same file as the API implementation +2. Follow existing patterns and naming conventions +3. Test with CONFIG_KAPI_RUNTIME_CHECKS enabled +4. Verify debugfs output is correct +5. Run scripts/checkpatch.pl on your changes + +Review Criteria +--------------- + +Specifications will be reviewed for: + +1. **Completeness**: All parameters and errors documented +2. **Accuracy**: Specification matches implementation +3. **Clarity**: Descriptions are clear and helpful +4. **Consistency**: Follows framework conventions +5. **Performance**: No unnecessary runtime overhead + +Contact +------- + +- Maintainer: Sasha Levin <[email protected]>
MAINTAINERS +9 -0
@@ -13049,6 +13049,15 @@ W: https://linuxtv.org T: git git://linuxtv.org/media.git F: drivers/media/radio/radio-keene* +KERNEL API SPECIFICATION FRAMEWORK (KAPI) +M: Sasha Levin <[email protected]> +L: [email protected] +S: Maintained +F: Documentation/admin-guide/kernel-api-spec.rst +F: include/linux/kernel_api_spec.h +F: kernel/api/ +F: scripts/extract-kapi-spec.sh + KERNEL AUTOMOUNTER M: Ian Kent <[email protected]> L: [email protected]
arch/um/kernel/dyn.lds.S +3 -0
@@ -102,6 +102,9 @@ SECTIONS init.data : { INIT_DATA } __init_end = .; + /* Kernel API specifications in dedicated section */ + KAPI_SPECS_SECTION() + /* Ensure the __preinit_array_start label is properly aligned. We could instead move the label definition inside the section, but the linker would then create the section even if it turns out to
arch/um/kernel/uml.lds.S +3 -0
@@ -74,6 +74,9 @@ SECTIONS init.data : { INIT_DATA } __init_end = .; + /* Kernel API specifications in dedicated section */ + KAPI_SPECS_SECTION() + .data : { INIT_TASK_DATA(KERNEL_STACK_SIZE)
arch/x86/kernel/vmlinux.lds.S +3 -0
@@ -173,6 +173,9 @@ SECTIONS RO_DATA(PAGE_SIZE) X86_ALIGN_RODATA_END + /* Kernel API specifications in dedicated section */ + KAPI_SPECS_SECTION() + /* Data */ .data : AT(ADDR(.data) - LOAD_OFFSET) { /* Start of data section */
include/asm-generic/vmlinux.lds.h +20 -0
@@ -279,6 +279,26 @@ defined(CONFIG_AUTOFDO_CLANG) || defined(CONFIG_PROPELLER_CLANG)#define TRACE_SYSCALLS ()#endif +#ifdef CONFIG_KAPI_SPEC +#define KAPI_SPECS () \ + . = ALIGN(8); \ + __start_kapi_specs = .; \ + KEEP(*(.kapi_specs)) \ + __stop_kapi_specs = .; + +/* For placing KAPI specs in a dedicated section */ +#define KAPI_SPECS_SECTION () \ + .kapi_specs : AT(ADDR(.kapi_specs) - LOAD_OFFSET) { \ + . = ALIGN(8); \ + __start_kapi_specs = .; \ + KEEP(*(.kapi_specs)) \ + __stop_kapi_specs = .; \ + } +#else +#define KAPI_SPECS () +#define KAPI_SPECS_SECTION () +#endif +#ifdef CONFIG_BPF_EVENTS #define BPF_RAW_TP () STRUCT_ALIGN(); \ BOUNDED_SECTION_BY(__bpf_raw_tp_map, __bpf_raw_tp)
include/linux/kernel_api_spec.h new file +1527 -0
1,527 lines not on this page · raw message
include/linux/syscall_api_spec.h new file +137 -0
138 lines not on this page · raw message
include/linux/syscalls.h +38 -0
@@ -87,6 +87,7 @@ struct xattr_args;#include <linux/bug.h> #include <linux/sem.h> #include <asm/siginfo.h> +#include <linux/syscall_api_spec.h> #include <linux/unistd.h> #include <linux/quota.h> #include <linux/key.h>
@@ -132,6 +133,7 @@ struct xattr_args;#define __SC_TYPE (t, a) t#define __SC_ARGS (t, a) a#define __SC_TEST (t, a) (void)BUILD_BUG_ON_ZERO(!__TYPE_IS_LL(t) && sizeof(t) > sizeof(long)) +#define __SC_CAST_TO_S64 (t, a) (s64)(a)#ifdef CONFIG_FTRACE_SYSCALLS #define __SC_STR_ADECL (t, a) #a
@@ -242,6 +244,41 @@ static inline int is_syscall_trace_event(struct trace_event_call *tp_event)* done within __do_sys_*(). */ #ifndef __SYSCALL_DEFINEx +#ifdef CONFIG_KAPI_RUNTIME_CHECKS +#define __SYSCALL_DEFINEx (x, name, ...) \ + __diag_push(); \ + __diag_ignore(GCC, 8, "-Wattribute-alias", \ + "Type aliasing is used to sanitize syscall arguments");\ + asmlinkage long sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)) \ + __attribute__((alias(__stringify(__se_sys##name)))); \ + ALLOW_ERROR_INJECTION(sys##name, ERRNO); \ + static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__));\ + static inline long __do_kapi_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)); \ + asmlinkage long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__)); \ + asmlinkage long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__)) \ + { \ + long ret = __do_kapi_sys##name(__MAP(x,__SC_CAST,__VA_ARGS__));\ + __MAP(x,__SC_TEST,__VA_ARGS__); \ + __PROTECT(x, ret,__MAP(x,__SC_ARGS,__VA_ARGS__)); \ + return ret; \ + } \ + __diag_pop(); \ + static inline long __do_kapi_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__))\ + { \ + const struct kernel_api_spec *__spec = kapi_get_spec("sys_" #name); \ + if (__spec) { \ + s64 __params[x] = { __MAP(x,__SC_CAST_TO_S64,__VA_ARGS__) }; \ + int __ret = kapi_validate_syscall_params(__spec, __params, x); \ + if (__ret) return __ret; \ + } \ + long ret = __do_sys##name(__MAP(x,__SC_ARGS,__VA_ARGS__)); \ + if (__spec) { \ + kapi_validate_syscall_return(__spec, (s64)ret); \ + } \ + return ret; \ + } \ + static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)) +#else /* !CONFIG_KAPI_RUNTIME_CHECKS */ #define __SYSCALL_DEFINEx (x, name, ...) \ __diag_push(); \ __diag_ignore(GCC, 8, "-Wattribute-alias", \
@@ -260,6 +297,7 @@ static inline int is_syscall_trace_event(struct trace_event_call *tp_event) } \__diag_pop (); \ static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)) +#endif /* CONFIG_KAPI_RUNTIME_CHECKS */ #endif /* __SYSCALL_DEFINEx */ /* For split 64-bit arguments on 32-bit architectures */
init/Kconfig +2 -0
@@ -2079,6 +2079,8 @@ config TRACEPOINTS source "kernel/Kconfig.kexec" +source "kernel/api/Kconfig" + endmenu # General setup source "arch/Kconfig"
kernel/Makefile +1 -0
@@ -56,6 +56,7 @@ obj-y += livepatch/ obj-y += dma/ obj-y += entry/ obj-$(CONFIG_MODULES) += module/ +obj-$(CONFIG_KAPI_SPEC) += api/ obj-$(CONFIG_KCMP) += kcmp.o obj-$(CONFIG_FREEZER) += freezer.o
kernel/api/Kconfig new file +35 -0
@@ -0,0 +1,35 @@ +# SPDX-License-Identifier: GPL-2.0-only +# +# Kernel API Specification Framework Configuration +# + +config KAPI_SPEC + bool "Kernel API Specification Framework" + help + This option enables the kernel API specification framework, + which provides formal documentation of kernel APIs in both + human and machine-readable formats. + + The framework allows developers to document APIs inline with + their implementation, including parameter specifications, + return values, error conditions, locking requirements, and + execution context constraints. + + When enabled, API specifications can be queried at runtime + and exported in various formats (JSON, XML) through debugfs. + + If unsure, say N. + +config KAPI_RUNTIME_CHECKS + bool "Runtime API specification checks" + depends on KAPI_SPEC + depends on DEBUG_KERNEL + help + Enable runtime validation of API usage against specifications. + This includes checking execution context requirements, parameter + validation, and lock state verification. + + This adds overhead and should only be used for debugging and + development. The checks use WARN_ONCE to report violations. + + If unsure, say N.
kernel/api/Makefile new file +7 -0
@@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Makefile for the Kernel API Specification Framework +# + +# Core API specification framework +obj-$(CONFIG_KAPI_SPEC) += kernel_api_spec.o
kernel/api/kernel_api_spec.c new file +1122 -0
640 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.39.5
Part of the diff is not shown here. View the raw message.
kernel test robot
build botRe: [RFC v3 1/4] kernel/api: introduce kernel API specification framework
kernel test robot noticed the following build warnings:
Hi Sasha,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build warnings:
[auto build test WARNING on uml/next]
[also build test WARNING on uml/fixes tip/x86/core akpm-mm/mm-everything tip/sched/core linus/master v6.16-rc5 next-20250711] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Sasha-Levin/kernel-api-introduce-kernel-API-specification-framework/20250711-194622 base: https://git.kernel.org/pub/scm/linux/kernel/git/uml/linux next patch link: https://lore.kernel.org/r/20250711114248.2288591-2-sashal%40kernel.org patch subject: [RFC v3 1/4] kernel/api: introduce kernel API specification framework config: m68k-allmodconfig (https://download.01.org/0day-ci/archive/20250713/[email protected]/config) compiler: m68k-linux-gcc (GCC) 15.1.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250713/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
In file included from io_uring/io_uring.c:45:
io_uring/io_uring.c: In function '__do_kapi_sys_io_uring_enter':
>> include/linux/syscalls.h:136:33: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
136 | #define __SC_CAST_TO_S64(t, a) (s64)(a)
| ^
include/linux/syscalls.h:119:27: note: in expansion of macro '__SC_CAST_TO_S64'
119 | #define __MAP2(m,t,a,...) m(t,a), __MAP1(m,__VA_ARGS__)
| ^
include/linux/syscalls.h:120:35: note: in expansion of macro '__MAP2'
120 | #define __MAP3(m,t,a,...) m(t,a), __MAP2(m,__VA_ARGS__)
| ^~~~~~
include/linux/syscalls.h:121:35: note: in expansion of macro '__MAP3'
121 | #define __MAP4(m,t,a,...) m(t,a), __MAP3(m,__VA_ARGS__)
| ^~~~~~
include/linux/syscalls.h:122:35: note: in expansion of macro '__MAP4'
122 | #define __MAP5(m,t,a,...) m(t,a), __MAP4(m,__VA_ARGS__)
| ^~~~~~
include/linux/syscalls.h:123:35: note: in expansion of macro '__MAP5'
123 | #define __MAP6(m,t,a,...) m(t,a), __MAP5(m,__VA_ARGS__)
| ^~~~~~
include/linux/syscalls.h:124:22: note: in expansion of macro '__MAP6'
124 | #define __MAP(n,...) __MAP##n(__VA_ARGS__)
| ^~~~~
include/linux/syscalls.h:270:45: note: in expansion of macro '__MAP'
270 | s64 __params[x] = { __MAP(x,__SC_CAST_TO_S64,__VA_ARGS__) }; \
| ^~~~~
include/linux/syscalls.h:237:9: note: in expansion of macro '__SYSCALL_DEFINEx'
237 | __SYSCALL_DEFINEx(x, sname, __VA_ARGS__)
| ^~~~~~~~~~~~~~~~~
include/linux/syscalls.h:231:36: note: in expansion of macro 'SYSCALL_DEFINEx'
231 | #define SYSCALL_DEFINE6(name, ...) SYSCALL_DEFINEx(6, _##name, __VA_ARGS__)
| ^~~~~~~~~~~~~~~
io_uring/io_uring.c:3338:1: note: in expansion of macro 'SYSCALL_DEFINE6'
3338 | SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
| ^~~~~~~~~~~~~~~
io_uring/io_uring.c: In function '__do_kapi_sys_io_uring_setup':
>> include/linux/syscalls.h:136:33: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
136 | #define __SC_CAST_TO_S64(t, a) (s64)(a)
| ^
include/linux/syscalls.h:118:27: note: in expansion of macro '__SC_CAST_TO_S64'
118 | #define __MAP1(m,t,a,...) m(t,a)
| ^
include/linux/syscalls.h:119:35: note: in expansion of macro '__MAP1'
119 | #define __MAP2(m,t,a,...) m(t,a), __MAP1(m,__VA_ARGS__)
| ^~~~~~
include/linux/syscalls.h:124:22: note: in expansion of macro '__MAP2'
124 | #define __MAP(n,...) __MAP##n(__VA_ARGS__)
| ^~~~~
include/linux/syscalls.h:270:45: note: in expansion of macro '__MAP'
270 | s64 __params[x] = { __MAP(x,__SC_CAST_TO_S64,__VA_ARGS__) }; \
| ^~~~~
include/linux/syscalls.h:237:9: note: in expansion of macro '__SYSCALL_DEFINEx'
237 | __SYSCALL_DEFINEx(x, sname, __VA_ARGS__)
| ^~~~~~~~~~~~~~~~~
include/linux/syscalls.h:227:36: note: in expansion of macro 'SYSCALL_DEFINEx'
227 | #define SYSCALL_DEFINE2(name, ...) SYSCALL_DEFINEx(2, _##name, __VA_ARGS__)
| ^~~~~~~~~~~~~~~
io_uring/io_uring.c:3855:1: note: in expansion of macro 'SYSCALL_DEFINE2'
3855 | SYSCALL_DEFINE2(io_uring_setup, u32, entries,
| ^~~~~~~~~~~~~~~
--
In file included from io_uring/register.c:9:
io_uring/register.c: In function '__do_kapi_sys_io_uring_register':
>> include/linux/syscalls.h:136:33: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
136 | #define __SC_CAST_TO_S64(t, a) (s64)(a)
| ^
include/linux/syscalls.h:119:27: note: in expansion of macro '__SC_CAST_TO_S64'
119 | #define __MAP2(m,t,a,...) m(t,a), __MAP1(m,__VA_ARGS__)
| ^
include/linux/syscalls.h:120:35: note: in expansion of macro '__MAP2'
120 | #define __MAP3(m,t,a,...) m(t,a), __MAP2(m,__VA_ARGS__)
| ^~~~~~
include/linux/syscalls.h:121:35: note: in expansion of macro '__MAP3'
121 | #define __MAP4(m,t,a,...) m(t,a), __MAP3(m,__VA_ARGS__)
| ^~~~~~
include/linux/syscalls.h:124:22: note: in expansion of macro '__MAP4'
124 | #define __MAP(n,...) __MAP##n(__VA_ARGS__)
| ^~~~~
include/linux/syscalls.h:270:45: note: in expansion of macro '__MAP'
270 | s64 __params[x] = { __MAP(x,__SC_CAST_TO_S64,__VA_ARGS__) }; \
| ^~~~~
include/linux/syscalls.h:237:9: note: in expansion of macro '__SYSCALL_DEFINEx'
237 | __SYSCALL_DEFINEx(x, sname, __VA_ARGS__)
| ^~~~~~~~~~~~~~~~~
include/linux/syscalls.h:229:36: note: in expansion of macro 'SYSCALL_DEFINEx'
229 | #define SYSCALL_DEFINE4(name, ...) SYSCALL_DEFINEx(4, _##name, __VA_ARGS__)
| ^~~~~~~~~~~~~~~ io_uring/register.c:906:1: note: in expansion of macro 'SYSCALL_DEFINE4'
906 | SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
| ^~~~~~~~~~~~~~~
--
kernel/api/kernel_api_spec.c: In function 'kapi_validate_param':
>> kernel/api/kernel_api_spec.c:668:42: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
668 | const void __user *ptr = (const void __user *)value;
| ^
kernel/api/kernel_api_spec.c:687:43: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
687 | const char __user *path = (const char __user *)value;
| ^
kernel/api/kernel_api_spec.c: In function 'kapi_validate_param_with_context':
kernel/api/kernel_api_spec.c:753:42: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
753 | const void __user *ptr = (const void __user *)value;
| ^vim +136 include/linux/syscalls.h
125
126 #define __SC_DECL(t, a) t a
127 #define __TYPE_AS(t, v) __same_type((__force t)0, v)
128 #define __TYPE_IS_L(t) (__TYPE_AS(t, 0L))
129 #define __TYPE_IS_UL(t) (__TYPE_AS(t, 0UL))
130 #define __TYPE_IS_LL(t) (__TYPE_AS(t, 0LL) || __TYPE_AS(t, 0ULL))
131 #define __SC_LONG(t, a) __typeof(__builtin_choose_expr(__TYPE_IS_LL(t), 0LL, 0L)) a
132 #define __SC_CAST(t, a) (__force t) a
133 #define __SC_TYPE(t, a) t
134 #define __SC_ARGS(t, a) a
135 #define __SC_TEST(t, a) (void)BUILD_BUG_ON_ZERO(!__TYPE_IS_LL(t) && sizeof(t) > sizeof(long))
> 136 #define __SC_CAST_TO_S64(t, a) (s64)(a)
137
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
kernel test robot
build botRe: [RFC v3 1/4] kernel/api: introduce kernel API specification framework
In reply to Sasha Levinkernel test robot noticed the following build errors:
Hi Sasha,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build errors:
[auto build test ERROR on uml/next]
[also build test ERROR on uml/fixes tip/x86/core arnd-asm-generic/master masahiroy-kbuild/for-next masahiroy-kbuild/fixes akpm-mm/mm-everything tip/sched/core linus/master v6.16-rc5 next-20250711] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Sasha-Levin/kernel-api-introduce-kernel-API-specification-framework/20250711-194622 base: https://git.kernel.org/pub/scm/linux/kernel/git/uml/linux next patch link: https://lore.kernel.org/r/20250711114248.2288591-2-sashal%40kernel.org patch subject: [RFC v3 1/4] kernel/api: introduce kernel API specification framework config: loongarch-allmodconfig (https://download.01.org/0day-ci/archive/20250713/[email protected]/config) compiler: clang version 19.1.7 (https://github.com/llvm/llvm-project cd708029e0b2869e80abe31ddb175f7c35361f90) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250713/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
>> ld.lld: error: undefined symbol: __stop_kapi_specs >>> referenced by kernel_api_spec.c >>> kernel/api/kernel_api_spec.o:(kapi_get_spec) in archive vmlinux.a >>> referenced by kernel_api_spec.c >>> kernel/api/kernel_api_spec.o:(kapi_get_spec) in archive vmlinux.a >>> referenced by kernel_api_spec.c >>> kernel/api/kernel_api_spec.o:(kapi_register_spec) in archive vmlinux.a >>> referenced 5 more times -- >> ld.lld: error: undefined symbol: __start_kapi_specs >>> referenced by kernel_api_spec.c >>> kernel/api/kernel_api_spec.o:(kapi_get_spec) in archive vmlinux.a >>> referenced by kernel_api_spec.c >>> kernel/api/kernel_api_spec.o:(kapi_get_spec) in archive vmlinux.a >>> referenced by kernel_api_spec.c >>> kernel/api/kernel_api_spec.o:(kapi_register_spec) in archive vmlinux.a >>> referenced 5 more times
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Re: [RFC v3 1/4] kernel/api: introduce kernel API specification framework
In reply to Sasha Levininclude/linux/kernel_api_spec.h line 79
Quoted 3 lines
include/linux/kernel_api_spec.h new file +3
-0+KAPI_PARAM_IN = (1 <<0 ), +KAPI_PARAM_OUT = (1 <<1 ), + KAPI_PARAM_INOUT = (1 << 2),
There is no need for KAPI_PARAM_INOUT. It could be replaced by KAPI_PARAM_IN | KAPI_PARAM_OUT
--
Askar Safin
Re: [RFC v3 1/4] kernel/api: introduce kernel API specification framework
Quoted 5 lines · Askar Safin
include/linux/kernel_api_spec.h line 79
Quoted 3 lines
include/linux/kernel_api_spec.h new file +3
-0+KAPI_PARAM_IN = (1 <<0 ), +KAPI_PARAM_OUT = (1 <<1 ), + KAPI_PARAM_INOUT = (1 << 2),There is no need for
KAPI_PARAM_INOUT. It could be replaced byKAPI_PARAM_IN|KAPI_PARAM_OUT
It could, but it's easier to write _INOUT :)
Signature · 2 lines
Thanks, Sasha
RFC v3 2/4 kernel/api: enable kerneldoc-based API specifications
In reply to Sasha LevinAllow kernel developers to write API specifications directly in kerneldoc comments, which are automatically converted to machine-readable C macros during build.
--- kernel/api/Makefile | 21 +- scripts/Makefile.build | 28 ++ scripts/generate_api_specs.sh | 59 +++ scripts/kernel-doc.py | 5 + scripts/lib/kdoc/kdoc_apispec.py | 623 +++++++++++++++++++++++++++++++ scripts/lib/kdoc/kdoc_output.py | 5 +- scripts/lib/kdoc/kdoc_parser.py | 54 ++- 7 files changed, 791 insertions(+), 4 deletions(-) create mode 100755 scripts/generate_api_specs.sh create mode 100644 scripts/lib/kdoc/kdoc_apispec.py
kernel/api/Makefile +20 -1
@@ -4,4 +4,23 @@ # # Core API specification framework -obj-$(CONFIG_KAPI_SPEC) += kernel_api_spec.o +obj-$(CONFIG_KAPI_SPEC) += kernel_api_spec.o + +# Auto-generated API specifications collector +ifeq ($(CONFIG_KAPI_SPEC),y) +obj-$(CONFIG_KAPI_SPEC) += generated_api_specs.o + +# Find all potential apispec files (this is evaluated at make time) +apispec-files := $(shell find $(objtree) -name "*.apispec.h" -type f 2>/dev/null) + +# Generate the collector file +# Note: FORCE ensures this is always regenerated to pick up new apispec files +$(obj)/generated_api_specs.c: $(srctree)/scripts/generate_api_specs.sh FORCE + $(Q)$(CONFIG_SHELL) $< $(srctree) $(objtree) > $@ + +targets += generated_api_specs.c +clean-files += generated_api_specs.c + +# Add explicit dependency on the generator script +$(obj)/generated_api_specs.o: $(obj)/generated_api_specs.c +endif
scripts/Makefile.build +28 -0
@@ -172,6 +172,34 @@ ifneq ($(KBUILD_EXTRA_WARN),) $< endif +# Generate API spec headers from kernel-doc comments +ifeq ($(CONFIG_KAPI_SPEC),y) +# Function to check if a file has API specifications +has-apispec = $(shell grep -qE '^\s*\*\s*(api-type|long-desc|context-flags|param-type|error-code|capability|signal|lock|side-effect|state-trans):' $(src)/$(1) 2>/dev/null && echo $(1)) + +# Get base names without directory prefix +c-objs-base := $(notdir $(real-obj-y) $(real-obj-m)) +# Filter to only .o files with corresponding .c source files +c-files := $(foreach o,$(c-objs-base),$(if $(wildcard $(src)/$(o:.o=.c)),$(o:.o=.c))) +# Also check for any additional .c files that contain API specs but are included +extra-c-files := $(shell find $(src) -maxdepth 1 -name "*.c" -exec grep -l '^\s*\*\s*\(api-type\|long-desc\|context-flags\|param-type\|error-code\|capability\|signal\|lock\|side-effect\|state-trans\):' {} \; 2>/dev/null | xargs -r basename -a) +# Combine both lists and remove duplicates +all-c-files := $(sort $(c-files) $(extra-c-files)) +# Only include files that actually have API specifications +apispec-files := $(foreach f,$(all-c-files),$(call has-apispec,$(f))) +# Generate apispec targets with proper directory prefix +apispec-y := $(addprefix $(obj)/,$(apispec-files:.c=.apispec.h)) +always-y += $(apispec-y) +targets += $(apispec-y) + +quiet_cmd_apispec = APISPEC $@ + cmd_apispec = PYTHONDONTWRITEBYTECODE=1 $(KERNELDOC) -apispec \ + $(KDOCFLAGS) $< > $@ 2>/dev/null || rm -f $@ + +$(obj)/%.apispec.h: $(src)/%.c FORCE + $(call if_changed,apispec) +endif + # Compile C sources (.c) # ---------------------------------------------------------------------------
scripts/generate_api_specs.sh new file +59 -0
60 lines not on this page · raw message
scripts/kernel-doc.py +5 -0
@@ -109,6 +109,7 @@ sys.path.insert(0, os.path.join(SRC_DIR, LIB_DIR)) from kdoc_files import KernelFiles # pylint: disable=C0413 from kdoc_output import RestFormat, ManFormat # pylint: disable=C0413 +from kdoc_apispec import ApiSpecFormat # pylint: disable=C0413 DESC = """ Read C language source or header FILEs, extract embedded documentation comments,
@@ -225,6 +226,8 @@ def main(): help="Output reStructuredText format (default).") out_fmt.add_argument("-N", "-none", "--none", action="store_true", help="Do not output documentation, only warnings.") + out_fmt.add_argument("-apispec", "--apispec", action="store_true", + help="Output C macro invocations for kernel API specifications.") # Output selection mutually-exclusive group
@@ -275,6 +278,8 @@ def main(): out_style = ManFormat(modulename=args.modulename) elif args.none: out_style = None + elif args.apispec: + out_style = ApiSpecFormat() else: out_style = RestFormat()
scripts/lib/kdoc/kdoc_apispec.py new file +623 -0
624 lines not on this page · raw message
scripts/lib/kdoc/kdoc_output.py +4 -1
@@ -127,7 +127,10 @@ class OutputFormat: warnings = args.get('warnings', []) for log_msg in warnings: - self.config.warning(log_msg) + # Skip numeric warnings (line numbers) which are false positives + # from parameter-specific sections like "param-constraint: name, value" + if not isinstance(log_msg, int): + self.config.warning(log_msg) def check_doc(self, name, args): """Check if DOC should be output"""
scripts/lib/kdoc/kdoc_parser.py +52 -2
66 lines not on this page · raw message
Signature · 1 line
2.39.5
kernel test robot
build botRe: [RFC v3 2/4] kernel/api: enable kerneldoc-based API specifications
kernel test robot noticed the following build warnings:
Hi Sasha,
[This is a private test report for your RFC patch.] kernel test robot noticed the following build warnings:
[auto build test WARNING on uml/next]
[also build test WARNING on uml/fixes tip/x86/core masahiroy-kbuild/for-next masahiroy-kbuild/fixes akpm-mm/mm-everything tip/sched/core linus/master v6.16-rc5 next-20250711] [cannot apply to arnd-asm-generic/master]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Sasha-Levin/kernel-api-introduce-kernel-API-specification-framework/20250711-194622 base: https://git.kernel.org/pub/scm/linux/kernel/git/uml/linux next patch link: https://lore.kernel.org/r/20250711114248.2288591-3-sashal%40kernel.org patch subject: [RFC v3 2/4] kernel/api: enable kerneldoc-based API specifications config: i386-buildonly-randconfig-002-20250712 (https://download.01.org/0day-ci/archive/20250712/[email protected]/config) compiler: gcc-11 (Debian 11.3.0-12) 11.3.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250712/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
>> Warning: sound/soc/samsung/pcm.c:131 struct member 'lock' not described in 's3c_pcm_info' -- >> Warning: sound/soc/fsl/fsl_esai.c:83 struct member 'lock' not described in 'fsl_esai' -- >> Warning: sound/soc/stm/stm32_spdifrx.c:248 struct member 'lock' not described in 'stm32_spdifrx_data' -- >> Warning: drivers/iio/temperature/mlx90632.c:162 struct member 'lock' not described in 'mlx90632_data' -- >> Warning: drivers/iio/temperature/mlx90635.c:133 struct member 'lock' not described in 'mlx90635_data' -- >> Warning: drivers/virtio/virtio_rtc_driver.c:37 struct member 'lock' not described in 'viortc_vq' >> Warning: drivers/virtio/virtio_rtc_driver.c:1137 function parameter 'lock' not described in 'viortc_populate_vq' -- >> Warning: drivers/iio/magnetometer/ak8974.c:201 struct member 'lock' not described in 'ak8974' -- >> Warning: kernel/locking/qrwlock.c:21 function parameter 'lock' not described in 'queued_read_lock_slowpath' >> Warning: kernel/locking/qrwlock.c:66 function parameter 'lock' not described in 'queued_write_lock_slowpath' -- >> Warning: kernel/locking/qspinlock.c:130 function parameter 'lock' not described in 'queued_spin_lock_slowpath' -- >> Warning: drivers/gpio/gpio-graniterapids.c:66 struct member 'lock' not described in 'gnr_gpio' -- >> Warning: drivers/iio/dac/ad5758.c:121 struct member 'lock' not described in 'ad5758_state'
..
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Randy Dunlap
reviewerRe: [RFC v3 2/4] kernel/api: enable kerneldoc-based API specifications
In reply to Sasha LevinHi Sasha,
I would like to ask a few questions to try to clarify/understand, please.
Quoted 17 lines · Sasha Levin
Allow kernel developers to write API specifications directly in kerneldoc comments, which are automatically converted to machine-readable C macros during build.
Signed-off-by Sasha Levin <[email protected]>--- kernel/api/Makefile | 21 +- scripts/Makefile.build | 28 ++ scripts/generate_api_specs.sh | 59 +++ scripts/kernel-doc.py | 5 + scripts/lib/kdoc/kdoc_apispec.py | 623 +++++++++++++++++++++++++++++++ scripts/lib/kdoc/kdoc_output.py | 5 +- scripts/lib/kdoc/kdoc_parser.py | 54 ++- 7 files changed, 791 insertions(+), 4 deletions(-) create mode 100755 scripts/generate_api_specs.sh create mode 100644 scripts/lib/kdoc/kdoc_apispec.py
[snip]
Quoted 7 lines
scripts/Makefile.build +0
-0@@ -172,6 +172,34 @@ ifneq ($(KBUILD_EXTRA_WARN),) $< endif
scripts/Makefile.build ifneq ($(KBUILD_EXTRA_WARN),) · line 183
Quoted 10 lines
scripts/Makefile.build +9
-0+# Generate API spec headers from kernel-doc comments +ifeq ($(CONFIG_KAPI_SPEC),y) +# Function to check if a file has API specifications +has-apispec = $(shell grep -qE '^\s*\*\s*(api-type|long-desc|context-flags|param-type|error-code|capability|signal|lock|side-effect|state-trans):' $(src)/$(1) 2>/dev/null && echo $(1)) + +# Get base names without directory prefix +c-objs-base := $(notdir $(real-obj-y) $(real-obj-m)) +# Filter to only .o files with corresponding .c source files +c-files := $(foreach o,$(c-objs-base),$(if $(wildcard $(src)/$(o:.o=.c)),$(o:.o=.c)))
1. One must build a kernel (with some desired .config file) to use/test this, correct?
2. It looks like it only checks .c files, omitting header files. (?) Some APIs are only present in header files (e.g., all of <linux/list.h> is either macros or inline functions).
scripts/Makefile.build ifneq ($(KBUILD_EXTRA_WARN),) · line 185
Quoted 2 lines
scripts/Makefile.build +2
-0+# Also check for any additional .c files that contain API specs but are included +extra-c-files := $(shell find $(src) -maxdepth 1 -name "*.c" -exec grep -l '^\s*\*\s*\(api-type\|long-desc\|context-flags\|param-type\|error-code\|capability\|signal\|lock\|side-effect\|state-trans\):' {} \; 2>/dev/null | xargs -r basename -a)
3a. included files: does this catch the (rare) use of a C file doing #include <path to some other C file> ?
3b. Quite a few makefiles generate final .o files with a different name from the source files. It looks like that is handled above by looking for the first (or intermediate) .o file for each .c file, so the final .o file with a different name is ignored (or at least doesn't come into play here). Yes?
Quoted 10 lines
scripts/Makefile.build +10
-0+# Combine both lists and remove duplicates +all-c-files := $(sort $(c-files) $(extra-c-files)) +# Only include files that actually have API specifications +apispec-files := $(foreach f,$(all-c-files),$(call has-apispec,$(f))) +# Generate apispec targets with proper directory prefix +apispec-y := $(addprefix $(obj)/,$(apispec-files:.c=.apispec.h)) +always-y += $(apispec-y) +targets += $(apispec-y) + +quiet_cmd_apispec = APISPEC $@
scripts/Makefile.build ifneq ($(KBUILD_EXTRA_WARN),) · line 205
Quoted 10 lines
scripts/Makefile.build +7
-0+ cmd_apispec = PYTHONDONTWRITEBYTECODE=1 $(KERNELDOC) -apispec \ + $(KDOCFLAGS) $< > $@ 2>/dev/null || rm -f $@ + +$(obj)/%.apispec.h: $(src)/%.c FORCE + $(call if_changed,apispec) +endif + # Compile C sources (.c) # ---------------------------------------------------------------------------
[snip]
Thanks.
Signature · 1 line
~Randy
Re: [RFC v3 2/4] kernel/api: enable kerneldoc-based API specifications
Quoted 33 lines · Randy Dunlap
Hi Sasha,
I would like to ask a few questions to try to clarify/understand, please.
Quoted 17 lines · Sasha Levin
Allow kernel developers to write API specifications directly in kerneldoc comments, which are automatically converted to machine-readable C macros during build.
Signed-off-by Sasha Levin <[email protected]>--- kernel/api/Makefile | 21 +- scripts/Makefile.build | 28 ++ scripts/generate_api_specs.sh | 59 +++ scripts/kernel-doc.py | 5 + scripts/lib/kdoc/kdoc_apispec.py | 623 +++++++++++++++++++++++++++++++ scripts/lib/kdoc/kdoc_output.py | 5 +- scripts/lib/kdoc/kdoc_parser.py | 54 ++- 7 files changed, 791 insertions(+), 4 deletions(-) create mode 100755 scripts/generate_api_specs.sh create mode 100644 scripts/lib/kdoc/kdoc_apispec.py[snip]
Quoted 8 lines
scripts/Makefile.build +0
-0@@ -172,6 +172,34 @@ ifneq ($(KBUILD_EXTRA_WARN),) $< endif
Quoted 12 lines
scripts/Makefile.build ifneq ($(KBUILD_EXTRA_WARN),) · line 183
Quoted 9 lines
scripts/Makefile.build +9
-0+# Generate API spec headers from kernel-doc comments +ifeq ($(CONFIG_KAPI_SPEC),y) +# Function to check if a file has API specifications +has-apispec = $(shell grep -qE '^\s*\*\s*(api-type|long-desc|context-flags|param-type|error-code|capability|signal|lock|side-effect|state-trans):' $(src)/$(1) 2>/dev/null && echo $(1)) + +# Get base names without directory prefix +c-objs-base := $(notdir $(real-obj-y) $(real-obj-m)) +# Filter to only .o files with corresponding .c source files +c-files := $(foreach o,$(c-objs-base),$(if $(wildcard $(src)/$(o:.o=.c)),$(o:.o=.c)))1. One must build a kernel (with some desired .config file) to use/test this, correct?
Mostly yes, but another option is to use the kapi tool (which I haven't updated and sent out as part of v3, but you can see it in v2:
https://lore.kernel.org/tools/[email protected]/T/#u).
With the kapi tool, you can also run it on a source tree to extract the same information that you'd have in a built vmlinux.
Quoted 3 lines
2. It looks like it only checks .c files, omitting header files. (?) Some APIs are only present in header files (e.g., all of <
linux/list.h> is either macros or inline functions).
I was trying to focus on the userspace side of things, so I didn't think we'll have anything in header files, but I also don't have an objection to extending it to scan headers too.
Quoted 5 lines
scripts/Makefile.build ifneq ($(KBUILD_EXTRA_WARN),) · line 185
Quoted 2 lines
scripts/Makefile.build +2
-0+# Also check for any additional .c files that contain API specs but are included +extra-c-files := $(shell find $(src) -maxdepth 1 -name "*.c" -exec grep -l '^\s*\*\s*\(api-type\|long-desc\|context-flags\|param-type\|error-code\|capability\|signal\|lock\|side-effect\|state-trans\):' {} \; 2>/dev/null | xargs -r basename -a)3a. included files: does this catch the (rare) use of a C file doing #include <path to some other C file> ?
Yes!
Jon suggested I apply this to a kernel/sched/ syscall to see how it handles complex syscalls, but it also added another complexity because sched does exactly what you described (kernel/sched/build_policy.c includes a bunch of other .c files including syscalls.c). See the 4th patch in the series.
Quoted 5 lines
3b. Quite a few makefiles generate final .o files with a different name from the source files. It looks like that is handled above by looking for the first (or intermediate) .o file for each .c file, so the final .o file with a different name is ignored (or at least doesn't come into play here). Yes?
Yes, exactly. The code looks for .o files that have directly corresponding .c files with the same base name. When makefiles generate final .o files with different names (like when multiple .c files are combined into a single .o, or when the output name is changed), those renamed .o files won't have a matching .c file and will be filtered out by the $(if $(wildcard $(src)/$(o:.o=.c)),$(o:.o=.c)) check.
Quoted 1 line
Thanks.
Thanks for looking into it!
Signature · 2 lines
Thanks, Sasha
Randy Dunlap
reviewerRe: [RFC v3 2/4] kernel/api: enable kerneldoc-based API specifications
Quoted 7 lines · Sasha Levin
Quoted 3 lines
2. It looks like it only checks .c files, omitting header files. (?) Some APIs are only present in header files (e.g., all of <
linux/list.h> is either macros or inline functions).I was trying to focus on the userspace side of things, so I didn't think we'll have anything in header files, but I also don't have an objection to extending it to scan headers too.
That's probably sufficient, at least for now.
Thanks.
Signature · 1 line
~Randy
RFC v3 3/4 mm/mlock: add API specification for mlock
In reply to Sasha LevinAdd kernel API specification for the mlock() system call.
--- mm/mlock.c | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+)
mm/mlock.c +85 -0
@@ -658,6 +658,91 @@ static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t flareturn 0 ; } +/** +* sys_mlock - Lock pages in memory +* @start: Starting address of memory range to lock +* @len: Length of memory range to lock in bytes +* +* long-desc: Locks pages in the specified address range into RAM, preventing +* them from being paged to swap. Requires CAP_IPC_LOCK capability +* or RLIMIT_MEMLOCK resource limit. +* context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE +* param-type: start, KAPI_TYPE_UINT +* param-flags: start, KAPI_PARAM_IN +* param-constraint-type: start, KAPI_CONSTRAINT_NONE +* param-constraint: start, Rounded down to page boundary +* param-type: len, KAPI_TYPE_UINT +* param-flags: len, KAPI_PARAM_IN +* param-constraint-type: len, KAPI_CONSTRAINT_RANGE +* param-range: len, 0, LONG_MAX +* param-constraint: len, Rounded up to page boundary +* return-type: KAPI_TYPE_INT +* return-check-type: KAPI_RETURN_ERROR_CHECK +* return-success: 0 +* error-code: -ENOMEM, ENOMEM, Address range issue, +* Some of the specified range is not mapped, has unmapped gaps, +* or the lock would cause the number of mapped regions to exceed the limit. +* error-code: -EPERM, EPERM, Insufficient privileges, +* The caller is not privileged (no CAP_IPC_LOCK) and RLIMIT_MEMLOCK is 0. +* error-code: -EINVAL, EINVAL, Address overflow, +* The result of the addition start+len was less than start (arithmetic overflow). +* error-code: -EAGAIN, EAGAIN, Some or all memory could not be locked, +* Some or all of the specified address range could not be locked. +* error-code: -EINTR, EINTR, Interrupted by signal, +* The operation was interrupted by a fatal signal before completion. +* error-code: -EFAULT, EFAULT, Bad address, +* The specified address range contains invalid addresses that cannot be accessed. +* since-version: 2.0 +* lock: mmap_lock, KAPI_LOCK_RWLOCK +* lock-acquired: true +* lock-released: true +* lock-desc: Process memory map write lock +* signal: FATAL +* signal-direction: KAPI_SIGNAL_RECEIVE +* signal-action: KAPI_SIGNAL_ACTION_RETURN +* signal-condition: Fatal signal pending +* signal-desc: Fatal signals (SIGKILL) can interrupt the operation at two points: +* when acquiring mmap_write_lock_killable() and during page population +* in __mm_populate(). Returns -EINTR. Non-fatal signals do NOT interrupt +* mlock - the operation continues even if SIGINT/SIGTERM are received. +* signal-error: -EINTR +* signal-timing: KAPI_SIGNAL_TIME_DURING +* signal-priority: 0 +* signal-interruptible: yes +* signal-state-req: KAPI_SIGNAL_STATE_RUNNING +* examples: mlock(addr, 4096); // Lock one page +* mlock(addr, len); // Lock range of pages +* notes: Memory locks do not stack - multiple calls on the same range can be +* undone by a single munlock. Locks are not inherited by child processes. +* Pages are locked on whole page boundaries. Commonly used by real-time +* applications to prevent page faults during time-critical operations. +* Also used for security to prevent sensitive data (e.g., cryptographic keys) +* from being written to swap. Note: locked pages may still be saved to +* swap during system suspend/hibernate. +* +* Tagged addresses are automatically handled via untagged_addr(). The operation +* occurs in two phases: first VMAs are marked with VM_LOCKED, then pages are +* populated into memory. When checking RLIMIT_MEMLOCK, the kernel optimizes +* by recounting locked memory to avoid double-counting overlapping regions. +* side-effect: KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_ALLOC_MEMORY, process memory, Locks pages into physical memory, preventing swapping, reversible=yes +* side-effect: KAPI_EFFECT_MODIFY_STATE, mm->locked_vm, Increases process locked memory counter, reversible=yes +* side-effect: KAPI_EFFECT_ALLOC_MEMORY, physical pages, May allocate and populate page table entries, condition=Pages not already present, reversible=yes +* side-effect: KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_ALLOC_MEMORY, page faults, Triggers page faults to bring pages into memory, condition=Pages not already resident +* side-effect: KAPI_EFFECT_MODIFY_STATE, VMA splitting, May split existing VMAs at lock boundaries, condition=Lock range partially overlaps existing VMA +* state-trans: memory pages, swappable, locked in RAM, Pages become non-swappable and pinned in physical memory +* state-trans: VMA flags, unlocked, VM_LOCKED set, Virtual memory area marked as locked +* capability: CAP_IPC_LOCK, KAPI_CAP_BYPASS_CHECK, CAP_IPC_LOCK capability +* capability-allows: Lock unlimited amount of memory (no RLIMIT_MEMLOCK enforcement) +* capability-without: Must respect RLIMIT_MEMLOCK resource limit +* capability-condition: Checked when RLIMIT_MEMLOCK is 0 or locking would exceed limit +* capability-priority: 0 +* constraint: RLIMIT_MEMLOCK Resource Limit, The RLIMIT_MEMLOCK soft resource limit specifies the maximum bytes of memory that may be locked into RAM. Unprivileged processes are restricted to this limit. CAP_IPC_LOCK capability allows bypassing this limit entirely. The limit is enforced per-process, not per-user. +* constraint-expr: RLIMIT_MEMLOCK Resource Limit, locked_memory + request_size <= RLIMIT_MEMLOCK || CAP_IPC_LOCK +* constraint: Memory Pressure and OOM, Locking large amounts of memory can cause system-wide memory pressure and potentially trigger the OOM killer. The kernel does not prevent locking memory that would destabilize the system. +* constraint: Special Memory Areas, Some memory types cannot be locked or are silently skipped: VM_IO/VM_PFNMAP areas (device mappings) are skipped; Hugetlb pages are inherently pinned and skipped; DAX mappings are always present in memory and skipped; Secret memory (memfd_secret) mappings are skipped; VM_DROPPABLE memory cannot be locked and is skipped; Gate VMA (kernel entry point) is skipped; VM_LOCKED areas are already locked. These special areas are silently excluded without error. +* +* Context: Process context. May sleep. Takes mmap_lock for write. +*/ SYSCALL_DEFINE2(mlock, unsigned long, start, size_t, len) {return do_mlock (start, len,VM_LOCKED );
Signature · 1 line
2.39.5
RFC v3 4/4 kernel/sched: add specs for sys_sched_setattr()
In reply to Sasha Levin--- kernel/sched/syscalls.c | 168 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 167 insertions(+), 1 deletion(-)
kernel/sched/syscalls.c +167 -1
@@ -974,10 +974,176 @@ SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param) }/** -* sys_sched_setattr - same as above, but with extended sched_attr +* sys_sched_setattr - set/change scheduling policy and attributes * @pid: the pid in question. * @uattr: structure containing the extended parameters. * @flags: for future extension. +* +* long-desc: Sets the scheduling policy and attributes for a process, +* supporting multiple scheduling classes including real-time, +* deadline, and normal policies. Performs capability checks, +* validates parameters, enforces resource limits, and ensures +* bandwidth constraints for deadline tasks. +* context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE +* param-count: 3 +* param-type: pid, KAPI_TYPE_INT +* param-flags: pid, KAPI_PARAM_IN +* param-constraint-type: pid, KAPI_CONSTRAINT_RANGE +* param-range: pid, 0, INT_MAX +* param-constraint: pid, Must be >= 0, where 0 means current process +* param-type: uattr, KAPI_TYPE_USER_PTR +* param-flags: uattr, KAPI_PARAM_IN | KAPI_PARAM_USER +* param-constraint-type: uattr, KAPI_CONSTRAINT_CUSTOM +* param-constraint: uattr, Valid user pointer to struct sched_attr +* struct-type: uattr, struct sched_attr +* struct-field: size, __u32, Structure size for version compatibility +* struct-field-range: size, 48, 512 +* struct-field-validate: size, uattr->size >= SCHED_ATTR_SIZE_VER0 +* struct-field: sched_policy, __u32, Scheduling policy selector +* struct-field-enum: sched_policy, SCHED_NORMAL(0), SCHED_FIFO(1), SCHED_RR(2), SCHED_BATCH(3), SCHED_IDLE(5), SCHED_DEADLINE(6), SCHED_EXT(7) +* struct-field: sched_flags, __u64, Policy modifier flags +* struct-field-mask: sched_flags, SCHED_FLAG_ALL +* struct-field: sched_nice, __s32, Nice value for CFS policies +* struct-field-range: sched_nice, -20, 19 +* struct-field-policy: sched_nice, SCHED_NORMAL, SCHED_BATCH, SCHED_IDLE +* struct-field: sched_priority, __u32, Priority for RT policies +* struct-field-range: sched_priority, 1, 99 +* struct-field-policy: sched_priority, SCHED_FIFO, SCHED_RR +* struct-field: sched_runtime, __u64, Runtime budget in nanoseconds +* struct-field-policy: sched_runtime, SCHED_DEADLINE +* struct-field: sched_deadline, __u64, Deadline in nanoseconds +* struct-field-policy: sched_deadline, SCHED_DEADLINE +* struct-field: sched_period, __u64, Period in nanoseconds (0 = use deadline) +* struct-field-policy: sched_period, SCHED_DEADLINE +* struct-field: sched_util_min, __u32, Minimum utilization hint (v1+) +* struct-field-range: sched_util_min, 0, 1024 +* struct-field-version: sched_util_min, 1 +* struct-field-flag: sched_util_min, SCHED_FLAG_UTIL_CLAMP_MIN +* struct-field: sched_util_max, __u32, Maximum utilization hint (v1+) +* struct-field-range: sched_util_max, 0, 1024 +* struct-field-version: sched_util_max, 1 +* struct-field-flag: sched_util_max, SCHED_FLAG_UTIL_CLAMP_MAX +* param-type: flags, KAPI_TYPE_UINT +* param-flags: flags, KAPI_PARAM_IN +* param-range: flags, 0, 0 +* param-constraint: flags, Must be 0 (reserved for future use) +* validation-group: RT Policies +* validation-policy: SCHED_FIFO, SCHED_RR +* validation-rule: sched_priority must be in [1,99] +* validation-rule: sched_nice must be 0 +* validation-rule: No deadline parameters +* validation-group: CFS Policies +* validation-policy: SCHED_NORMAL, SCHED_BATCH, SCHED_IDLE +* validation-rule: sched_priority must be 0 +* validation-rule: sched_nice must be in [-20,19] +* validation-rule: No deadline parameters +* validation-group: Deadline Policy +* validation-policy: SCHED_DEADLINE +* validation-rule: sched_runtime > 0 +* validation-rule: sched_deadline >= sched_runtime +* validation-rule: sched_period == 0 || sched_period >= sched_deadline +* validation-rule: sched_priority must be 0 +* validation-rule: sched_nice must be 0 +* validation-group: Utilization Clamping +* validation-flag: SCHED_FLAG_UTIL_CLAMP_MIN, SCHED_FLAG_UTIL_CLAMP_MAX +* validation-rule: Requires struct version >= 1 (size >= 56) +* validation-rule: util values must be in [0,1024] +* validation-rule: util_min <= util_max +* return-type: KAPI_TYPE_INT +* return-check-type: KAPI_RETURN_ERROR_CHECK +* return-success: 0 +* error-code: -EINVAL, EINVAL, Invalid parameters, +* Returned when uattr is NULL, pid < 0, flags != 0, +* attr.size < SCHED_ATTR_SIZE_VER0, invalid scheduling policy, +* invalid priority for policy, invalid sched_flags, or malformed +* sched_attr structure (e.g., DL runtime > deadline) +* error-code: -ESRCH, ESRCH, Process not found, +* Returned when the specified pid does not exist +* error-code: -EPERM, EPERM, Insufficient privileges, +* Returned when lacking CAP_SYS_NICE for privileged operations, +* trying to change another user's process without CAP_SYS_NICE, +* or resetting SCHED_RESET_ON_FORK flag without privileges +* error-code: -E2BIG, E2BIG, Structure size mismatch, +* Returned when sched_attr size is larger than kernel expects +* error-code: -EFAULT, EFAULT, Bad user pointer, +* Returned when copying from user space fails or uattr is not +* a valid readable user pointer +* error-code: -EBUSY, EBUSY, Bandwidth exceeded, +* Returned when SCHED_DEADLINE bandwidth would be exceeded or +* deadline admission test fails +* error-code: -EAGAIN, EAGAIN, Transient failure, +* Returned when unable to change cpus_allowed due to transient +* cpuset or CPU hotplug conditions +* error-code: -ENOMEM, ENOMEM, Memory allocation failed, +* Returned when unable to allocate memory for CPU masks +* error-code: -EOPNOTSUPP, EOPNOTSUPP, Feature not supported, +* Returned when utilization clamping is requested but +* CONFIG_UCLAMP_TASK is not enabled +* since-version: 3.14 +* lock: rq->lock, KAPI_LOCK_SPINLOCK +* lock-acquired: true +* lock-released: true +* lock-desc: Process runqueue lock for scheduler state changes +* lock: p->pi_lock, KAPI_LOCK_SPINLOCK +* lock-acquired: true +* lock-released: true +* lock-desc: Priority inheritance lock for PI chain adjustments +* lock: cpuset_mutex, KAPI_LOCK_MUTEX +* lock-acquired: true +* lock-released: true +* lock-desc: Cpuset mutex for SCHED_DEADLINE bandwidth checks +* signal: SIGXCPU +* signal-direction: KAPI_SIGNAL_SEND +* signal-action: KAPI_SIGNAL_ACTION_DEFAULT +* signal-condition: SCHED_FLAG_DL_OVERRUN is set and deadline is missed +* signal-desc: Sent to task when it exceeds its SCHED_DEADLINE runtime. +* The signal is sent asynchronously from the scheduler tick or +* deadline timer. Unlike other scheduling policies, SCHED_DEADLINE +* can generate SIGXCPU for runtime overruns rather than just +* CPU time limit violations. +* signal-timing: KAPI_SIGNAL_TIME_DURING +* signal-priority: 0 +* signal-interruptible: no +* signal-state-req: KAPI_SIGNAL_STATE_RUNNING +* examples: sched_setattr(0, &attr, 0); // Set attributes for current task +* sched_setattr(pid, &attr, 0); // Set attributes for specific task +* notes: The sched_attr structure supports forward/backward compatibility +* through its size field. Older kernels ignore newer fields. The syscall +* validates all parameters based on the scheduling policy. For SCHED_DEADLINE, +* it performs CBS (Constant Bandwidth Server) admission control. Priority +* changes may trigger immediate reschedule. RT policies require sched_priority +* in range [1,99]. Normal policies use nice values [-20,19] mapped to +* static_prio. Changes are atomic - either all succeed or none are applied. +* side-effect: KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_PROCESS_STATE, task scheduling attributes, Updates policy/priority/deadline parameters atomically, reversible=yes +* side-effect: KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_SCHEDULE, runqueue, May requeue task with new priority and trigger reschedule, condition=Task is runnable +* side-effect: KAPI_EFFECT_MODIFY_STATE, deadline bandwidth, Allocates CBS bandwidth for SCHED_DEADLINE tasks, condition=Policy is SCHED_DEADLINE, reversible=yes +* side-effect: KAPI_EFFECT_MODIFY_STATE, timer slack, Sets timer slack to 0 for RT/DL policies, condition=RT or DEADLINE policy +* side-effect: KAPI_EFFECT_MODIFY_STATE, PI chain, Updates priority inheritance chain if task has PI waiters, condition=Task has PI waiters +* side-effect: KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_SCHEDULE, CPU, May migrate task to different CPU based on affinity/bandwidth, condition=SCHED_DEADLINE or cpuset changes +* state-trans: task->policy, any policy, new policy, Task scheduling policy changes per sched_attr +* state-trans: task->rt_priority, any, 0-99 or 0, RT priority updated for RT policies, 0 for others +* state-trans: task->normal_prio, any, recalculated, Normal priority recalculated based on policy/nice +* state-trans: task->sched_reset_on_fork, 0/1, 0/1, Reset-on-fork flag updated per SCHED_FLAG_RESET_ON_FORK +* state-trans: task->dl, inactive/active, active/inactive, Deadline entity activated for SCHED_DEADLINE +* capability: CAP_SYS_NICE, KAPI_CAP_BYPASS_CHECK, CAP_SYS_NICE capability +* capability-allows: Set RT/DL policies, increase priority, nice < 0, change other users' tasks, remove SCHED_FLAG_RESET_ON_FORK +* capability-without: Can only set SCHED_NORMAL/BATCH/IDLE, decrease priority, nice >= 0, modify own tasks +* capability-condition: Checked when setting RT/DL policy, decreasing nice, or modifying other user's tasks +* capability-priority: 0 +* constraint: Valid Scheduling Policy, The sched_policy field must be one of: SCHED_NORMAL (0), SCHED_FIFO (1), SCHED_RR (2), SCHED_BATCH (3), SCHED_IDLE (5), SCHED_DEADLINE (6), or SCHED_EXT (7) if configured. Invalid policies result in -EINVAL. +* constraint-expr: Valid Scheduling Policy, uattr->sched_policy >= 0 && (uattr->sched_policy <= SCHED_DEADLINE || (uattr->sched_policy == SCHED_EXT && IS_ENABLED(CONFIG_SCHED_CLASS_EXT))) +* constraint: RT Priority Range, For SCHED_FIFO and SCHED_RR policies, sched_priority must be in range [1, 99] where 1 is lowest and 99 is highest RT priority. For other policies, sched_priority must be 0. +* constraint-expr: RT Priority Range, rt_policy(uattr->sched_policy) ? (uattr->sched_priority >= 1 && uattr->sched_priority <= 99) : (uattr->sched_priority == 0) +* constraint: Nice Value Range, For SCHED_NORMAL, SCHED_BATCH, and SCHED_IDLE policies, the nice value must be in range [-20, 19] where -20 is highest priority (least nice) and 19 is lowest priority (most nice). +* constraint-expr: Nice Value Range, fair_policy(uattr->sched_policy) ? (uattr->sched_nice >= MIN_NICE && uattr->sched_nice <= MAX_NICE) : 1 +* constraint: SCHED_DEADLINE CBS Rules, For SCHED_DEADLINE, must satisfy: sched_runtime > 0, sched_deadline >= sched_runtime, sched_period >= sched_deadline. If period is 0, it defaults to deadline. +* constraint-expr: SCHED_DEADLINE CBS Rules, dl_policy(uattr->sched_policy) ? (uattr->sched_runtime > 0 && uattr->sched_runtime <= uattr->sched_deadline && (uattr->sched_period == 0 || uattr->sched_period >= uattr->sched_deadline)) : 1 +* constraint: Utilization Clamping Range, If sched_flags includes SCHED_FLAG_UTIL_CLAMP_MIN/MAX, the util_min and util_max values must be in range [0, 1024] where 1024 represents 100% utilization. +* constraint-expr: Utilization Clamping Range, (uattr->sched_flags & SCHED_FLAG_UTIL_CLAMP) ? (uattr->sched_util_min >= 0 && uattr->sched_util_min <= SCHED_CAPACITY_SCALE && uattr->sched_util_max >= 0 && uattr->sched_util_max <= SCHED_CAPACITY_SCALE && uattr->sched_util_min <= uattr->sched_util_max) : 1 +* constraint: SCHED_DEADLINE Bandwidth, The sum of runtime/period ratios for all SCHED_DEADLINE tasks on the system must not exceed the available CPU capacity. This global bandwidth check prevents system overload. +* constraint: Structure Size Compatibility, The attr.size field must be at least SCHED_ATTR_SIZE_VER0 (48 bytes) and no larger than the kernel's known structure size to ensure forward/backward compatibility. +* +* Context: Process context. May sleep. Takes various scheduler locks. */ SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr, unsigned int, flags)
Signature · 1 line
2.39.5