Skip to contentSkip to conversation

Kernel API Specification Framework

RFC Superseded Sasha Levin 6 participants 44 messages Jun 14, 2025 – Jul 1, 2025

Subsystems (12)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

cover Kernel API Specification Framework

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 provides three key components: declarative macros for specifying system call and IOCTL interfaces directly in the kernel source, automated extraction tools for generating machine-readable specifications, and a runtime validation infrastructure accessible through debugfs. By embedding specifications alongside implementation code, we ensure they remain synchronized and enable automated detection of API/ABI changes that could break user-space applications.

This implementation demonstrates the approach with specifications for core system calls (epoll, exec, mlock families) and complex IOCTL interfaces (binder, fwctl). The specifications capture parameter types, validation rules, return values, and error conditions in a structured format that enables both documentation generation and runtime verification. Future work will expand coverage to additional subsystems and integrate with existing testing infrastructure to provide API compatibility guarantees.

To complement the framework, we introduce the 'kapi' tool - a utility for extracting and analyzing kernel API specifications from multiple sources. The tool can extract specifications from kernel source code (parsing KAPI macros), compiled vmlinux binaries (reading the .kapi_specs ELF section), or from a running kernel via debugfs. It supports multiple output formats (plain text, JSON, RST) to facilitate integration with documentation systems and automated testing workflows. This tool enables developers to easily inspect API specifications, verify changes across kernel versions, and generate documentation without requiring kernel rebuilds.

Sasha Levin (19):
kernel/api: introduce kernel API specification framework
eventpoll: add API specification for epoll_create1
eventpoll: add API specification for epoll_create
eventpoll: add API specification for epoll_ctl
eventpoll: add API specification for epoll_wait
eventpoll: add API specification for epoll_pwait
eventpoll: add API specification for epoll_pwait2
exec: add API specification for execve
exec: add API specification for execveat
mm/mlock: add API specification for mlock
mm/mlock: add API specification for mlock2
mm/mlock: add API specification for mlockall mm/mlock: add API specification for munlock
mm/mlock: add API specification for munlockall kernel/api: add debugfs interface for kernel API specifications kernel/api: add IOCTL specification infrastructure
fwctl: add detailed IOCTL API specifications
binder: add detailed IOCTL API specifications tools/kapi: Add kernel API specification extraction tool

 Documentation/admin-guide/kernel-api-spec.rst |  699 +++++++++
 MAINTAINERS                                   |    9 +
 arch/um/kernel/dyn.lds.S                      |    3 +
 arch/um/kernel/uml.lds.S                      |    3 +
 arch/x86/kernel/vmlinux.lds.S                 |    3 +
 drivers/android/binder.c                      |  758 ++++++++++
 drivers/fwctl/main.c                          |  295 +++-
 fs/eventpoll.c                                | 1056 ++++++++++++++
 fs/exec.c                                     |  463 ++++++
 include/asm-generic/vmlinux.lds.h             |   20 +
 include/linux/ioctl_api_spec.h                |  540 +++++++
 include/linux/kernel_api_spec.h               |  942 ++++++++++++
 include/linux/syscall_api_spec.h              |  341 +++++
 include/linux/syscalls.h                      |    1 +
 init/Kconfig                                  |    2 +
 kernel/Makefile                               |    1 +
 kernel/api/Kconfig                            |   55 +
 kernel/api/Makefile                           |   13 +
 kernel/api/ioctl_validation.c                 |  360 +++++
 kernel/api/kapi_debugfs.c                     |  340 +++++
 kernel/api/kernel_api_spec.c                  | 1257 +++++++++++++++++
 mm/mlock.c                                    |  646 +++++++++
 tools/kapi/.gitignore                         |    4 +
 tools/kapi/Cargo.toml                         |   19 +
 tools/kapi/src/extractor/debugfs.rs           |  204 +++
 tools/kapi/src/extractor/mod.rs               |   95 ++
 tools/kapi/src/extractor/source_parser.rs     |  488 +++++++
 .../src/extractor/vmlinux/binary_utils.rs     |  130 ++
 tools/kapi/src/extractor/vmlinux/mod.rs       |  372 +++++
 tools/kapi/src/formatter/json.rs              |  170 +++
 tools/kapi/src/formatter/mod.rs               |   68 +
 tools/kapi/src/formatter/plain.rs             |   99 ++
 tools/kapi/src/formatter/rst.rs               |  144 ++
 tools/kapi/src/main.rs                        |  121 ++
 34 files changed, 9719 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/admin-guide/kernel-api-spec.rst
 create mode 100644 include/linux/ioctl_api_spec.h
 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/ioctl_validation.c
 create mode 100644 kernel/api/kapi_debugfs.c
 create mode 100644 kernel/api/kernel_api_spec.c
 create mode 100644 tools/kapi/.gitignore
 create mode 100644 tools/kapi/Cargo.toml
 create mode 100644 tools/kapi/src/extractor/debugfs.rs
 create mode 100644 tools/kapi/src/extractor/mod.rs
 create mode 100644 tools/kapi/src/extractor/source_parser.rs
 create mode 100644 tools/kapi/src/extractor/vmlinux/binary_utils.rs
 create mode 100644 tools/kapi/src/extractor/vmlinux/mod.rs
 create mode 100644 tools/kapi/src/formatter/json.rs
 create mode 100644 tools/kapi/src/formatter/mod.rs
 create mode 100644 tools/kapi/src/formatter/plain.rs
 create mode 100644 tools/kapi/src/formatter/rst.rs
 create mode 100644 tools/kapi/src/main.rs
Signature · 1 line
2.39.5
#1 lore raw

RFC 1/19 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               |  942 +++++++++++++
 include/linux/syscall_api_spec.h              |  341 +++++
 include/linux/syscalls.h                      |    1 +
 init/Kconfig                                  |    2 +
 kernel/Makefile                               |    1 +
 kernel/api/Kconfig                            |   35 +
 kernel/api/Makefile                           |    7 +
 kernel/api/kernel_api_spec.c                  | 1169 +++++++++++++++++
 14 files changed, 3043 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
new file mode 100644
index 0000000000000..3a63f6711e27b
@@ -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
index a92290fffa163..7a2cb663131bd 100644
@@ -13047,6 +13047,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
index a36b7918a011a..283ab11788d8c 100644
@@ -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
index a409d4b66114f..e3850d8293436 100644
@@ -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
index 4fa0be732af10..8cc508adc9d51 100644
@@ -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
index fa5f19b8d53a0..7b47736057e01 100644
@@ -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 +942 -0

943 lines not on this page · raw message

include/linux/syscall_api_spec.h new file +341 -0

342 lines not on this page · raw message

include/linux/syscalls.h +1 -0
index e5603cc91963d..f2951ece2068b 100644
@@ -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>
init/Kconfig +2 -0
index af4c2f0854554..7a15248933895 100644
@@ -2079,6 +2079,8 @@ config TRACEPOINTS
 
 source "kernel/Kconfig.kexec"
 
+source "kernel/api/Kconfig"
+
 endmenu		# General setup
 
 source "arch/Kconfig"
kernel/Makefile +1 -0
index 32e80dd626af0..ba94ee4bb2292 100644
@@ -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
new file mode 100644
index 0000000000000..fde25ec70e134
@@ -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
new file mode 100644
index 0000000000000..4120ded7e5cf1
@@ -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
\ No newline at end of file
kernel/api/kernel_api_spec.c new file +1169 -0

1,075 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.

#2 lore raw

RFC 2/19 eventpoll: add API specification for epoll_create1

In reply to Sasha Levin

Add kernel API specification for the epoll_create1() system call.

---
 fs/eventpoll.c | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 86 insertions(+)
fs/eventpoll.c +86 -0
index d4dbffdedd08e..8f8a64ebbaef6 100644
@@ -21,6 +21,7 @@
 #include <linux/hash.h>
 #include <linux/spinlock.h>
 #include <linux/syscalls.h>
+#include <linux/syscall_api_spec.h>
 #include <linux/rbtree.h>
 #include <linux/wait.h>
 #include <linux/eventpoll.h>
@@ -2265,6 +2266,91 @@ static int do_epoll_create(int flags)
 	return error;
 }
 
+
+/* Valid values for epoll_create1 flags parameter */
+static const s64 epoll_create1_valid_values[] = { 0, EPOLL_CLOEXEC };
+
+DEFINE_KERNEL_API_SPEC(sys_epoll_create1)
+	KAPI_DESCRIPTION("Create an epoll instance")
+	KAPI_LONG_DESC("Creates a new epoll instance and returns a file descriptor "
+		       "referring to that instance. The file descriptor is used for all "
+		       "subsequent calls to the epoll interface.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	KAPI_PARAM(0, "flags", "int", "Creation flags for the epoll instance")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.constraint_type = KAPI_CONSTRAINT_ENUM,
+		.enum_values = epoll_create1_valid_values,
+		.enum_count = ARRAY_SIZE(epoll_create1_valid_values),
+		.constraints = "Must be 0 or EPOLL_CLOEXEC",
+	KAPI_PARAM_END
+
+	KAPI_RETURN("long", "File descriptor on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_FD,
+	KAPI_RETURN_END
+
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "Invalid flags specified",
+		   "The flags parameter contains invalid values. Only EPOLL_CLOEXEC is allowed.")
+	KAPI_ERROR(1, -EMFILE, "EMFILE", "Per-process file descriptor limit reached",
+		   "The per-process limit on the number of open file descriptors has been reached.")
+	KAPI_ERROR(2, -ENFILE, "ENFILE", "System file table overflow",
+		   "The system-wide limit on the total number of open files has been reached.")
+	KAPI_ERROR(3, -ENOMEM, "ENOMEM", "Insufficient kernel memory",
+		   "There was insufficient kernel memory to create the epoll instance.")
+	KAPI_ERROR(4, -EINTR, "EINTR", "Interrupted by signal",
+		   "The system call was interrupted by a signal before the epoll instance could be created.")
+
+	.error_count = 5,
+	.param_count = 1,
+	.since_version = "2.6.27",
+	.examples = "int epfd = epoll_create1(EPOLL_CLOEXEC);",
+	.notes = "EPOLL_CLOEXEC sets the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. "
+		 "When all file descriptors referring to an epoll instance are closed, the kernel "
+		 "destroys the instance and releases associated resources.",
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_RESOURCE_CREATE | KAPI_EFFECT_ALLOC_MEMORY,
+			 "epoll instance",
+			 "Creates a new epoll instance and allocates kernel memory for it")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_RESOURCE_CREATE,
+			 "file descriptor",
+			 "Allocates a new file descriptor in the process's file descriptor table")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(2)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "epoll instance", "non-existent", "created and empty",
+			 "A new epoll instance is created with no monitored file descriptors")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(1)
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, SIGINT, "SIGINT", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("During creation if process receives SIGINT")
+		KAPI_SIGNAL_DESC("If interrupted during kernel memory allocation, returns -EINTR")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(1, SIGTERM, "SIGTERM", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("During creation if process receives SIGTERM")
+		KAPI_SIGNAL_DESC("If interrupted during kernel memory allocation, returns -EINTR")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(2, SIGKILL, "SIGKILL", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_CONDITION("At any point during the syscall")
+		KAPI_SIGNAL_DESC("Process is terminated immediately, epoll instance creation may be incomplete")
+	KAPI_SIGNAL_END
+
+	.signal_count = 3,
+KAPI_END_SPEC;
 SYSCALL_DEFINE1(epoll_create1, int, flags)
 {
 	return do_epoll_create(flags);
Signature · 1 line
2.39.5
#3 lore raw

RFC 3/19 eventpoll: add API specification for epoll_create

In reply to Sasha Levin

Add kernel API specification for the epoll_create() system call.

---
 fs/eventpoll.c | 111 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 111 insertions(+)
fs/eventpoll.c +111 -0
index 8f8a64ebbaef6..50adea7ba43d1 100644
@@ -2356,6 +2356,117 @@ SYSCALL_DEFINE1(epoll_create1, int, flags)
 	return do_epoll_create(flags);
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_epoll_create)
+	KAPI_DESCRIPTION("Create an epoll instance (obsolete)")
+	KAPI_LONG_DESC("Creates a new epoll instance and returns a file descriptor "
+		       "referring to that instance. This is the obsolete interface; "
+		       "new applications should use epoll_create1() instead.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	KAPI_PARAM(0, "size", "int", "Ignored hint about expected number of file descriptors")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		KAPI_PARAM_RANGE(1, INT_MAX)
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.constraints = "Must be greater than zero (ignored since Linux 2.6.8)",
+	KAPI_PARAM_END
+
+	KAPI_RETURN("long", "File descriptor on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_FD,
+	KAPI_RETURN_END
+
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "size <= 0",
+		   "The size parameter must be greater than zero.")
+	KAPI_ERROR(1, -EMFILE, "EMFILE", "Per-process file descriptor limit reached",
+		   "The per-process limit on the number of open file descriptors has been reached.")
+	KAPI_ERROR(2, -ENFILE, "ENFILE", "System file table overflow",
+		   "The system-wide limit on the total number of open files has been reached.")
+	KAPI_ERROR(3, -ENOMEM, "ENOMEM", "Insufficient kernel memory",
+		   "There was insufficient kernel memory to create the epoll instance.")
+	KAPI_ERROR(4, -EINTR, "EINTR", "Interrupted by signal",
+		   "The system call was interrupted by a signal before the epoll instance could be created.")
+
+	.error_count = 5,
+	.param_count = 1,
+	.since_version = "2.6",
+	.deprecated = true,
+	.replacement = "epoll_create1",
+	.examples = "int epfd = epoll_create(1024); // size is ignored since Linux 2.6.8",
+	.notes = "Since Linux 2.6.8, the size argument is ignored but must be greater than zero. "
+		 "The kernel dynamically sizes the data structures as needed. "
+		 "For new applications, epoll_create1() should be preferred as it allows "
+		 "setting close-on-exec flag atomically.",
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_RESOURCE_CREATE | KAPI_EFFECT_ALLOC_MEMORY,
+			 "epoll instance",
+			 "Creates a new epoll instance and allocates kernel memory for it")
+		KAPI_EFFECT_CONDITION("Always when successful")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_RESOURCE_CREATE,
+			 "file descriptor",
+			 "Allocates a new file descriptor in the process's file descriptor table")
+		KAPI_EFFECT_CONDITION("Always when successful")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_MODIFY_STATE,
+			 "kernel file table",
+			 "Adds new file structure to system-wide file table")
+		KAPI_EFFECT_CONDITION("Always when successful")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(3)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "epoll instance", "non-existent", "created and empty",
+			 "A new epoll instance is created with no monitored file descriptors")
+		KAPI_STATE_TRANS_COND("On successful creation")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "file descriptor", "unallocated", "allocated and open",
+			 "A new file descriptor is allocated in the process's fd table")
+		KAPI_STATE_TRANS_COND("On successful creation")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(2)
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, SIGINT, "SIGINT", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("During kernel memory allocation")
+		KAPI_SIGNAL_DESC("If interrupted during memory allocation or fd allocation, returns -EINTR")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(1, SIGTERM, "SIGTERM", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("During kernel memory allocation")
+		KAPI_SIGNAL_DESC("If interrupted during memory allocation or fd allocation, returns -EINTR")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(2, SIGKILL, "SIGKILL", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_CONDITION("At any point during the syscall")
+		KAPI_SIGNAL_DESC("Process is terminated immediately, epoll instance creation may be incomplete")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(3, SIGHUP, "SIGHUP", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("During kernel operations")
+		KAPI_SIGNAL_DESC("If process is being terminated due to terminal hangup, may return -EINTR")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(4, SIGPIPE, "SIGPIPE", KAPI_SIGNAL_IGNORE, KAPI_SIGNAL_ACTION_DEFAULT)
+		KAPI_SIGNAL_CONDITION("Never generated by epoll_create")
+		KAPI_SIGNAL_DESC("This signal is not relevant to epoll_create as it doesn't involve pipes")
+	KAPI_SIGNAL_END
+
+	.signal_count = 5,
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE1(epoll_create, int, size)
 {
 	if (size <= 0)
Signature · 1 line
2.39.5
#4 lore raw

RFC 4/19 eventpoll: add API specification for epoll_ctl

In reply to Sasha Levin

Add kernel API specification for the epoll_ctl() system call.

---
 fs/eventpoll.c | 203 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 203 insertions(+)
fs/eventpoll.c +203 -0
index 50adea7ba43d1..409a0c440f112 100644
@@ -2647,6 +2647,209 @@ int do_epoll_ctl(int epfd, int op, int fd, struct epoll_event *epds,
  * the eventpoll file that enables the insertion/removal/change of
  * file descriptors inside the interest set.
  */
+
+/* Valid values for epoll_ctl op parameter */
+static const s64 epoll_ctl_valid_ops[] = {
+	EPOLL_CTL_ADD,
+	EPOLL_CTL_DEL,
+	EPOLL_CTL_MOD,
+};
+
+DEFINE_KERNEL_API_SPEC(sys_epoll_ctl)
+	KAPI_DESCRIPTION("Control interface for an epoll file descriptor")
+	KAPI_LONG_DESC("Performs control operations on the epoll instance referred to by epfd. "
+		       "It requests that the operation op be performed for the target file "
+		       "descriptor fd. Valid operations are adding, modifying, or deleting "
+		       "file descriptors from the interest set.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	KAPI_PARAM(0, "epfd", "int", "File descriptor referring to the epoll instance")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_FD,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "op", "int", "Operation to be performed")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_INT,
+		.constraint_type = KAPI_CONSTRAINT_ENUM,
+		.enum_values = epoll_ctl_valid_ops,
+		.enum_count = ARRAY_SIZE(epoll_ctl_valid_ops),
+		.constraints = "Must be EPOLL_CTL_ADD, EPOLL_CTL_DEL, or EPOLL_CTL_MOD",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "fd", "int", "File descriptor to be monitored")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_FD,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Must refer to a file that supports poll operations",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(3, "event", "struct epoll_event __user *", "Settings for the file descriptor")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER | KAPI_PARAM_OPTIONAL)
+		.type = KAPI_TYPE_USER_PTR,
+		KAPI_PARAM_SIZE(sizeof(struct epoll_event))
+		.constraints = "Required for ADD and MOD operations, ignored for DEL",
+	KAPI_PARAM_END
+
+	KAPI_RETURN("long", "0 on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_EXACT,
+		KAPI_RETURN_SUCCESS(0)
+	KAPI_RETURN_END
+
+	KAPI_ERROR(0, -EBADF, "EBADF", "epfd or fd is not a valid file descriptor",
+		   "One of the file descriptors is invalid or has been closed.")
+	KAPI_ERROR(1, -EEXIST, "EEXIST", "op is EPOLL_CTL_ADD and fd is already registered",
+		   "The file descriptor is already present in the epoll instance.")
+	KAPI_ERROR(2, -EINVAL, "EINVAL", "Invalid operation or parameters",
+		   "epfd is not an epoll file descriptor, epfd == fd, op is not valid, "
+		   "or EPOLLEXCLUSIVE was specified with invalid events.")
+	KAPI_ERROR(3, -ENOENT, "ENOENT", "op is EPOLL_CTL_MOD or EPOLL_CTL_DEL and fd is not registered",
+		   "The file descriptor is not registered with this epoll instance.")
+	KAPI_ERROR(4, -ENOMEM, "ENOMEM", "Insufficient kernel memory",
+		   "There was insufficient memory to handle the requested operation.")
+	KAPI_ERROR(5, -EPERM, "EPERM", "Target file does not support epoll",
+		   "The target file fd does not support poll operations.")
+	KAPI_ERROR(6, -ELOOP, "ELOOP", "Circular monitoring detected",
+		   "fd refers to an epoll instance and this operation would result "
+		   "in a circular loop of epoll instances monitoring one another.")
+	KAPI_ERROR(7, -EFAULT, "EFAULT", "event points outside accessible address space",
+		   "The memory area pointed to by event is not accessible with write permissions.")
+	KAPI_ERROR(8, -EAGAIN, "EAGAIN", "Nonblocking mode and lock not available",
+		   "The operation was called in nonblocking mode and could not acquire necessary locks.")
+	KAPI_ERROR(9, -ENOSPC, "ENOSPC", "User epoll watch limit exceeded",
+		   "The limit on the total number of epoll watches was exceeded. "
+		   "See /proc/sys/fs/epoll/max_user_watches.")
+	KAPI_ERROR(10, -EINTR, "EINTR", "Interrupted by signal",
+		   "The system call was interrupted by a signal before completion.")
+
+	.error_count = 11,
+	.param_count = 4,
+	.since_version = "2.6",
+
+	/* Locking specifications */
+	KAPI_LOCK(0, "ep->mtx", KAPI_LOCK_MUTEX)
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects the epoll instance during control operations")
+	KAPI_LOCK_END
+
+	KAPI_LOCK(1, "epnested_mutex", KAPI_LOCK_MUTEX)
+		KAPI_LOCK_DESC("Global mutex to prevent circular epoll structures (acquired for nested epoll)")
+	KAPI_LOCK_END
+
+	.lock_count = 2,
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_ALLOC_MEMORY,
+			 "epoll interest list",
+			 "Adds new epitem structure to the epoll interest list")
+		KAPI_EFFECT_CONDITION("When op is EPOLL_CTL_ADD")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_FREE_MEMORY,
+			 "epoll interest list",
+			 "Removes epitem structure from the epoll interest list")
+		KAPI_EFFECT_CONDITION("When op is EPOLL_CTL_DEL")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_MODIFY_STATE,
+			 "epoll event mask",
+			 "Modifies the event mask for an existing epitem")
+		KAPI_EFFECT_CONDITION("When op is EPOLL_CTL_MOD")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_MODIFY_STATE,
+			 "file reference count",
+			 "Increases reference count on the monitored file")
+		KAPI_EFFECT_CONDITION("When op is EPOLL_CTL_ADD")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(4, KAPI_EFFECT_MODIFY_STATE,
+			 "file reference count",
+			 "Decreases reference count on the monitored file")
+		KAPI_EFFECT_CONDITION("When op is EPOLL_CTL_DEL")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(5, KAPI_EFFECT_SCHEDULE,
+			 "process state",
+			 "May wake up processes waiting on the epoll instance if events become available")
+		KAPI_EFFECT_CONDITION("When adding or modifying entries that match current events")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(6)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "epoll entry", "non-existent", "monitored",
+			 "File descriptor is added to epoll interest list")
+		KAPI_STATE_TRANS_COND("When op is EPOLL_CTL_ADD")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "epoll entry", "monitored", "non-existent",
+			 "File descriptor is removed from epoll interest list")
+		KAPI_STATE_TRANS_COND("When op is EPOLL_CTL_DEL")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "epoll entry", "monitored with events A", "monitored with events B",
+			 "Event mask for file descriptor is modified")
+		KAPI_STATE_TRANS_COND("When op is EPOLL_CTL_MOD")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "epoll ready list", "empty or partial", "contains new events",
+			 "Ready list may be updated if new/modified entry has pending events")
+		KAPI_STATE_TRANS_COND("When monitored fd has events matching the mask")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(4)
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, SIGINT, "SIGINT", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("During mutex acquisition or memory allocation")
+		KAPI_SIGNAL_DESC("Returns -EINTR if interrupted before completing the operation")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(1, SIGTERM, "SIGTERM", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("During mutex acquisition or memory allocation")
+		KAPI_SIGNAL_DESC("Returns -EINTR if interrupted before completing the operation")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(2, SIGKILL, "SIGKILL", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_CONDITION("At any point during the syscall")
+		KAPI_SIGNAL_DESC("Process is terminated immediately, operation may be partially completed")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(3, SIGHUP, "SIGHUP", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("During blocking operations")
+		KAPI_SIGNAL_DESC("Returns -EINTR if terminal hangup occurs")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(4, SIGURG, "SIGURG", KAPI_SIGNAL_IGNORE, KAPI_SIGNAL_ACTION_DEFAULT)
+		KAPI_SIGNAL_CONDITION("May be generated by monitored sockets")
+		KAPI_SIGNAL_DESC("Urgent data signals from monitored sockets do not affect epoll_ctl")
+	KAPI_SIGNAL_END
+
+	.signal_count = 5,
+
+	.examples = "struct epoll_event ev;\n"
+		    "ev.events = EPOLLIN | EPOLLOUT;\n"
+		    "ev.data.fd = fd;\n"
+		    "if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev) == -1)\n"
+		    "    handle_error();\n",
+	.notes = "EPOLL_CTL_DEL ignores the event parameter (can be NULL). "
+		 "EPOLLEXCLUSIVE flag has restrictions and cannot be used with EPOLL_CTL_MOD. "
+		 "The epoll instance maintains a reference to registered files until they are "
+		 "explicitly removed with EPOLL_CTL_DEL or the epoll instance is closed.",
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,
 		struct epoll_event __user *, event)
 {
Signature · 1 line
2.39.5
#5 lore raw

RFC 5/19 eventpoll: add API specification for epoll_wait

In reply to Sasha Levin

Add kernel API specification for the epoll_wait() system call.

---
 fs/eventpoll.c | 182 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 182 insertions(+)
fs/eventpoll.c +182 -0
index 409a0c440f112..254b50d687d37 100644
@@ -2932,6 +2932,188 @@ static int do_epoll_wait(int epfd, struct epoll_event __user *events,
 	return ep_poll(ep, events, maxevents, to);
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_epoll_wait)
+	KAPI_DESCRIPTION("Wait for events on an epoll instance")
+	KAPI_LONG_DESC("Waits for events on the epoll instance referred to by epfd. "
+		       "The function blocks the calling thread until either at least one of the "
+		       "file descriptors referred to by epfd becomes ready for some I/O operation, "
+		       "the call is interrupted by a signal handler, or the timeout expires.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	KAPI_PARAM(0, "epfd", "int", "File descriptor referring to the epoll instance")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_FD,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "events", "struct epoll_event __user *", "Buffer where ready events will be stored")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_USER_PTR,
+		KAPI_PARAM_SIZE(sizeof(struct epoll_event))  /* Base size of single element */
+		.size_param_idx = 2,  /* Size determined by maxevents parameter */
+		.size_multiplier = sizeof(struct epoll_event),
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Must point to an array of at least maxevents epoll_event structures",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "maxevents", "int", "Maximum number of events to return")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_INT,
+		KAPI_PARAM_RANGE(1, INT_MAX / sizeof(struct epoll_event))  /* EP_MAX_EVENTS */
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.constraints = "Must be greater than zero and not exceed system limits",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(3, "timeout", "int", "Timeout in milliseconds")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_INT,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "-1 blocks indefinitely, 0 returns immediately, >0 specifies milliseconds to wait",
+	KAPI_PARAM_END
+
+	KAPI_RETURN("long", "Number of ready file descriptors on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_RANGE,
+		.success_min = 0,
+		.success_max = INT_MAX,
+	KAPI_RETURN_END
+
+	KAPI_ERROR(0, -EBADF, "EBADF", "epfd is not a valid file descriptor",
+		   "The epoll file descriptor is invalid or has been closed.")
+	KAPI_ERROR(1, -EFAULT, "EFAULT", "events points outside accessible address space",
+		   "The memory area pointed to by events is not accessible with write permissions.")
+	KAPI_ERROR(2, -EINTR, "EINTR", "Call interrupted by signal handler",
+		   "The call was interrupted by a signal handler before any events "
+		   "became ready or the timeout expired.")
+	KAPI_ERROR(3, -EINVAL, "EINVAL", "Invalid parameters",
+		   "epfd is not an epoll file descriptor, or maxevents is less than or equal to zero.")
+
+	.error_count = 4,
+	.param_count = 4,
+	.since_version = "2.6",
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE,
+			 "ready list",
+			 "Removes events from the epoll ready list as they are reported")
+		KAPI_EFFECT_CONDITION("When events are available and level-triggered")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_SCHEDULE,
+			 "process state",
+			 "Blocks the calling thread until events are available or timeout")
+		KAPI_EFFECT_CONDITION("When timeout != 0 and no events are immediately available")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_MODIFY_STATE,
+			 "user memory",
+			 "Writes event data to user-provided buffer")
+		KAPI_EFFECT_CONDITION("When events are available")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_PROCESS_STATE,
+			 "signal state",
+			 "Clears TIF_SIGPENDING if a signal was pending")
+		KAPI_EFFECT_CONDITION("When returning due to signal interruption")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(4)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "process", "running", "blocked",
+			 "Process blocks waiting for events")
+		KAPI_STATE_TRANS_COND("When no events available and timeout != 0")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "process", "blocked", "running",
+			 "Process wakes up due to events, timeout, or signal")
+		KAPI_STATE_TRANS_COND("When wait condition is satisfied")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "epoll ready list", "has events", "events consumed",
+			 "Ready events are consumed from the epoll instance")
+		KAPI_STATE_TRANS_COND("When returning events to userspace")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "events buffer", "uninitialized", "contains event data",
+			 "User buffer is populated with ready events")
+		KAPI_STATE_TRANS_COND("When events are available")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(4)
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, 0, "ANY", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Any pending signal")
+		KAPI_SIGNAL_DESC("Any signal delivered to the thread will interrupt epoll_wait() "
+				 "and cause it to return -EINTR. This is checked via signal_pending() "
+				 "after checking for available events.")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(1, SIGKILL, "SIGKILL", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_CONDITION("Always delivered, cannot be blocked")
+		KAPI_SIGNAL_DESC("SIGKILL will terminate the process. The epoll_wait call will "
+				 "not return as the process is terminated immediately.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(2, SIGSTOP, "SIGSTOP", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_STOP)
+		KAPI_SIGNAL_CONDITION("Always delivered, cannot be blocked")
+		KAPI_SIGNAL_DESC("SIGSTOP will stop the process. When continued with SIGCONT, "
+				 "epoll_wait may return -EINTR if the timeout has not expired.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(3, SIGCONT, "SIGCONT", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_CONTINUE)
+		KAPI_SIGNAL_CONDITION("When process is stopped")
+		KAPI_SIGNAL_DESC("SIGCONT resumes a stopped process. If epoll_wait was interrupted "
+				 "by SIGSTOP, it may return -EINTR when continued.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(4, SIGALRM, "SIGALRM", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Timer expiration")
+		KAPI_SIGNAL_DESC("SIGALRM from timer expiration will interrupt epoll_wait with -EINTR")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	.signal_count = 5,
+	.signal_mask_count = 0, /* No signal mask manipulation in epoll_wait */
+
+	/* Locking specifications */
+	KAPI_LOCK(0, "ep->lock", KAPI_LOCK_SPINLOCK)
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects the ready list while checking for and consuming events")
+	KAPI_LOCK_END
+
+	KAPI_LOCK(1, "ep->mtx", KAPI_LOCK_MUTEX)
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects against concurrent epoll_ctl operations during wait")
+	KAPI_LOCK_END
+
+	.lock_count = 2,
+
+	.examples = "struct epoll_event events[10];\n"
+		    "int nfds = epoll_wait(epfd, events, 10, 1000);\n"
+		    "if (nfds == -1) {\n"
+		    "    perror(\"epoll_wait\");\n"
+		    "    exit(EXIT_FAILURE);\n"
+		    "}\n"
+		    "for (int n = 0; n < nfds; ++n) {\n"
+		    "    if (events[n].data.fd == listen_sock) {\n"
+		    "        accept_new_connection();\n"
+		    "    } else {\n"
+		    "        handle_io(events[n].data.fd);\n"
+		    "    }\n"
+		    "}",
+	.notes = "The timeout uses CLOCK_MONOTONIC and may be rounded up to system clock granularity. "
+		 "A timeout of -1 causes epoll_wait to block indefinitely, while a timeout of 0 "
+		 "causes it to return immediately even if no events are available. "
+		 "The struct epoll_event is defined as containing events (uint32_t) and data (epoll_data_t union).",
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events,
 		int, maxevents, int, timeout)
 {
Signature · 1 line
2.39.5
#6 lore raw

RFC 6/19 eventpoll: add API specification for epoll_pwait

In reply to Sasha Levin

Add kernel API specification for the epoll_pwait() system call.

---
 fs/eventpoll.c | 230 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 230 insertions(+)
fs/eventpoll.c +230 -0
index 254b50d687d37..8bd25f9230fc8 100644
@@ -3148,6 +3148,236 @@ static int do_epoll_pwait(int epfd, struct epoll_event __user *events,
 	return error;
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_epoll_pwait)
+	KAPI_DESCRIPTION("Wait for events on an epoll instance with signal handling")
+	KAPI_LONG_DESC("Similar to epoll_wait(), but allows the caller to safely wait for "
+		       "either events on the epoll instance or the delivery of a signal. "
+		       "The sigmask argument specifies a signal mask which is atomically "
+		       "set during the wait, allowing signals to be blocked while not waiting "
+		       "and ensuring no signal is lost between checking for events and blocking.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	KAPI_PARAM(0, "epfd", "int", "File descriptor referring to the epoll instance")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_FD,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "events", "struct epoll_event __user *", "Buffer where ready events will be stored")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_USER_PTR,
+		KAPI_PARAM_SIZE(sizeof(struct epoll_event))
+		.size_param_idx = 2,  /* Size determined by maxevents parameter */
+		.size_multiplier = sizeof(struct epoll_event),
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Must point to an array of at least maxevents epoll_event structures",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "maxevents", "int", "Maximum number of events to return")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_INT,
+		KAPI_PARAM_RANGE(1, INT_MAX / sizeof(struct epoll_event))  /* EP_MAX_EVENTS */
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.constraints = "Must be greater than zero and not exceed system limits",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(3, "timeout", "int", "Timeout in milliseconds")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_INT,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "-1 blocks indefinitely, 0 returns immediately, >0 specifies milliseconds to wait",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(4, "sigmask", "const sigset_t __user *", "Signal mask to atomically set during wait")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER | KAPI_PARAM_OPTIONAL)
+		.type = KAPI_TYPE_USER_PTR,
+		KAPI_PARAM_SIZE(sizeof(sigset_t))
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Can be NULL if no signal mask change is desired",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(5, "sigsetsize", "size_t", "Size of the signal set in bytes")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		KAPI_PARAM_RANGE(sizeof(sigset_t), sizeof(sigset_t))
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.constraints = "Must be sizeof(sigset_t)",
+	KAPI_PARAM_END
+
+	KAPI_RETURN("long", "Number of ready file descriptors on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_RANGE,
+		.success_min = 0,
+		.success_max = INT_MAX,
+	KAPI_RETURN_END
+
+	KAPI_ERROR(0, -EBADF, "EBADF", "epfd is not a valid file descriptor",
+		   "The epoll file descriptor is invalid or has been closed.")
+	KAPI_ERROR(1, -EFAULT, "EFAULT", "Memory area not accessible",
+		   "The memory area pointed to by events or sigmask is not accessible.")
+	KAPI_ERROR(2, -EINTR, "EINTR", "Call interrupted by signal handler",
+		   "The call was interrupted by a signal handler before any events "
+		   "became ready or the timeout expired; see signal(7).")
+	KAPI_ERROR(3, -EINVAL, "EINVAL", "Invalid parameters",
+		   "epfd is not an epoll file descriptor, maxevents is less than or equal to zero, "
+		   "or sigsetsize is not equal to sizeof(sigset_t).")
+
+	.error_count = 4,
+	.param_count = 6,
+	.since_version = "2.6.19",
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE,
+			 "signal mask",
+			 "Atomically sets the signal mask for the calling thread")
+		KAPI_EFFECT_CONDITION("When sigmask is not NULL")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE,
+			 "ready list",
+			 "Removes events from the epoll ready list as they are reported")
+		KAPI_EFFECT_CONDITION("When events are available and level-triggered")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_SCHEDULE,
+			 "process state",
+			 "Blocks the calling thread until events are available, timeout, or signal")
+		KAPI_EFFECT_CONDITION("When timeout != 0 and no events are immediately available")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_MODIFY_STATE,
+			 "user memory",
+			 "Writes event data to user-provided buffer")
+		KAPI_EFFECT_CONDITION("When events are available")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(4, KAPI_EFFECT_PROCESS_STATE,
+			 "saved signal mask",
+			 "Saves and restores the original signal mask")
+		KAPI_EFFECT_CONDITION("When sigmask is not NULL")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(5)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "signal mask", "original mask", "user-specified mask",
+			 "Thread's signal mask is atomically changed to the provided mask")
+		KAPI_STATE_TRANS_COND("When sigmask is not NULL")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "process", "running", "blocked",
+			 "Process blocks waiting for events with specified signal mask")
+		KAPI_STATE_TRANS_COND("When no events available and timeout != 0")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "process", "blocked", "running",
+			 "Process wakes up due to events, timeout, or unblocked signal")
+		KAPI_STATE_TRANS_COND("When wait condition is satisfied")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "signal mask", "user-specified mask", "original mask",
+			 "Thread's signal mask is restored to its original value")
+		KAPI_STATE_TRANS_COND("When returning from epoll_pwait")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(4, "pending signals", "blocked", "deliverable",
+			 "Signals that were blocked by the temporary mask become deliverable")
+		KAPI_STATE_TRANS_COND("When signal mask is restored and signals were pending")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(5)
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, 0, "ANY_UNBLOCKED", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Signal not blocked by provided sigmask")
+		KAPI_SIGNAL_DESC("Any signal not blocked by the sigmask parameter will interrupt "
+				 "epoll_pwait() and cause it to return -EINTR. The signal mask is "
+				 "atomically set via set_user_sigmask() and restored via "
+				 "restore_saved_sigmask_unless() before returning.")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(1, SIGKILL, "SIGKILL", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_CONDITION("Cannot be blocked by sigmask")
+		KAPI_SIGNAL_DESC("SIGKILL cannot be blocked and will terminate the process immediately. "
+				 "The epoll_pwait call will not return.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(2, SIGSTOP, "SIGSTOP", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_STOP)
+		KAPI_SIGNAL_CONDITION("Cannot be blocked by sigmask")
+		KAPI_SIGNAL_DESC("SIGSTOP cannot be blocked and will stop the process. When continued "
+				 "with SIGCONT, epoll_pwait may return -EINTR.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(3, 0, "BLOCKED_SIGNALS", KAPI_SIGNAL_BLOCK, KAPI_SIGNAL_ACTION_DEFAULT)
+		KAPI_SIGNAL_CONDITION("Signals in provided sigmask")
+		KAPI_SIGNAL_DESC("Signals specified in the sigmask parameter are blocked for the "
+				 "duration of the epoll_pwait call. They remain pending and will be "
+				 "delivered after the signal mask is restored.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(4, SIGCONT, "SIGCONT", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_CONTINUE)
+		KAPI_SIGNAL_CONDITION("When process is stopped")
+		KAPI_SIGNAL_DESC("SIGCONT resumes a stopped process. If epoll_pwait was interrupted "
+				 "by SIGSTOP, it may return -EINTR when continued.")
+	KAPI_SIGNAL_END
+
+	.signal_count = 5,
+
+	/* Signal mask specifications */
+	KAPI_SIGNAL_MASK(0, "user_sigmask", "User-provided signal mask atomically applied")
+		.description = "The signal mask provided in the sigmask parameter is atomically "
+			       "set for the duration of the wait operation. This prevents race "
+			       "conditions between checking for events and blocking. The original "
+			       "signal mask is restored before epoll_pwait returns, unless the "
+			       "return value is -EINTR (in which case the mask is restored by "
+			       "the signal delivery mechanism)."
+	KAPI_SIGNAL_MASK_END
+
+	.signal_mask_count = 1,
+
+	/* Locking specifications */
+	KAPI_LOCK(0, "ep->lock", KAPI_LOCK_SPINLOCK)
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects the ready list while checking for and consuming events")
+	KAPI_LOCK_END
+
+	KAPI_LOCK(1, "ep->mtx", KAPI_LOCK_MUTEX)
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects against concurrent epoll_ctl operations during wait")
+	KAPI_LOCK_END
+
+	.lock_count = 2,
+
+	.examples = "sigset_t sigmask;\n"
+		    "struct epoll_event events[10];\n\n"
+		    "/* Block SIGINT during epoll_pwait */\n"
+		    "sigemptyset(&sigmask);\n"
+		    "sigaddset(&sigmask, SIGINT);\n\n"
+		    "int nfds = epoll_pwait(epfd, events, 10, 1000, &sigmask, sizeof(sigmask));\n"
+		    "if (nfds == -1) {\n"
+		    "    if (errno == EINTR) {\n"
+		    "        /* Handle signal */\n"
+		    "    }\n"
+		    "    perror(\"epoll_pwait\");\n"
+		    "    exit(EXIT_FAILURE);\n"
+		    "}",
+	.notes = "epoll_pwait() is equivalent to atomically executing:\n"
+		 "    sigset_t origmask;\n"
+		 "    pthread_sigmask(SIG_SETMASK, &sigmask, &origmask);\n"
+		 "    ready = epoll_wait(epfd, events, maxevents, timeout);\n"
+		 "    pthread_sigmask(SIG_SETMASK, &origmask, NULL);\n"
+		 "This atomicity prevents race conditions where a signal could be delivered "
+		 "after checking for events but before blocking in epoll_wait(). "
+		 "The signal mask is always restored before epoll_pwait() returns.",
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events,
 		int, maxevents, int, timeout, const sigset_t __user *, sigmask,
 		size_t, sigsetsize)
Signature · 1 line
2.39.5
#7 lore raw

RFC 7/19 eventpoll: add API specification for epoll_pwait2

In reply to Sasha Levin

Add kernel API specification for the epoll_pwait2() system call.

---
 fs/eventpoll.c | 244 +++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 244 insertions(+)
fs/eventpoll.c +244 -0
index 8bd25f9230fc8..0e90d66467010 100644
@@ -3389,6 +3389,250 @@ SYSCALL_DEFINE6(epoll_pwait, int, epfd, struct epoll_event __user *, events,
 			      sigmask, sigsetsize);
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_epoll_pwait2)
+	KAPI_DESCRIPTION("Wait for events on an epoll instance with nanosecond precision timeout")
+	KAPI_LONG_DESC("Similar to epoll_pwait(), but takes a timespec structure that allows "
+		       "nanosecond precision for the timeout value. This provides more accurate "
+		       "timeout control compared to the millisecond precision of epoll_pwait(). "
+		       "Like epoll_pwait(), it atomically sets a signal mask during the wait.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	KAPI_PARAM(0, "epfd", "int", "File descriptor referring to the epoll instance")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_FD,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "events", "struct epoll_event __user *", "Buffer where ready events will be stored")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_USER_PTR,
+		KAPI_PARAM_SIZE(sizeof(struct epoll_event))
+		.size_param_idx = 2,  /* Size determined by maxevents parameter */
+		.size_multiplier = sizeof(struct epoll_event),
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Must point to an array of at least maxevents epoll_event structures",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "maxevents", "int", "Maximum number of events to return")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_INT,
+		KAPI_PARAM_RANGE(1, INT_MAX / sizeof(struct epoll_event))  /* EP_MAX_EVENTS */
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.constraints = "Must be greater than zero and not exceed system limits",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(3, "timeout", "const struct __kernel_timespec __user *", "Timeout with nanosecond precision")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER | KAPI_PARAM_OPTIONAL)
+		.type = KAPI_TYPE_USER_PTR,
+		KAPI_PARAM_SIZE(sizeof(struct __kernel_timespec))
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "NULL means block indefinitely, {0, 0} returns immediately, "
+			       "negative values are invalid",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(4, "sigmask", "const sigset_t __user *", "Signal mask to atomically set during wait")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER | KAPI_PARAM_OPTIONAL)
+		.type = KAPI_TYPE_USER_PTR,
+		KAPI_PARAM_SIZE(sizeof(sigset_t))
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Can be NULL if no signal mask change is desired",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(5, "sigsetsize", "size_t", "Size of the signal set in bytes")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		KAPI_PARAM_RANGE(sizeof(sigset_t), sizeof(sigset_t))
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.constraints = "Must be sizeof(sigset_t)",
+	KAPI_PARAM_END
+
+	KAPI_RETURN("long", "Number of ready file descriptors on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_RANGE,
+		.success_min = 0,
+		.success_max = INT_MAX,
+	KAPI_RETURN_END
+
+	KAPI_ERROR(0, -EBADF, "EBADF", "epfd is not a valid file descriptor",
+		   "The epoll file descriptor is invalid or has been closed.")
+	KAPI_ERROR(1, -EFAULT, "EFAULT", "Memory area not accessible",
+		   "The memory area pointed to by events, timeout, or sigmask is not accessible.")
+	KAPI_ERROR(2, -EINTR, "EINTR", "Call interrupted by signal handler",
+		   "The call was interrupted by a signal handler before any events "
+		   "became ready or the timeout expired.")
+	KAPI_ERROR(3, -EINVAL, "EINVAL", "Invalid parameters",
+		   "epfd is not an epoll file descriptor, maxevents is less than or equal to zero, "
+		   "sigsetsize is not equal to sizeof(sigset_t), or timeout values are invalid.")
+
+	.error_count = 4,
+	.param_count = 6,
+	.since_version = "5.11",
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE,
+			 "signal mask",
+			 "Atomically sets the signal mask for the calling thread")
+		KAPI_EFFECT_CONDITION("When sigmask is not NULL")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE,
+			 "ready list",
+			 "Removes events from the epoll ready list as they are reported")
+		KAPI_EFFECT_CONDITION("When events are available and level-triggered")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_SCHEDULE,
+			 "process state",
+			 "Blocks the calling thread until events, timeout, or signal")
+		KAPI_EFFECT_CONDITION("When timeout != NULL or timeout->tv_sec/tv_nsec != 0")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_MODIFY_STATE,
+			 "user memory",
+			 "Writes event data to user-provided buffer")
+		KAPI_EFFECT_CONDITION("When events are available")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(4, KAPI_EFFECT_PROCESS_STATE,
+			 "saved signal mask",
+			 "Saves and restores the original signal mask")
+		KAPI_EFFECT_CONDITION("When sigmask is not NULL")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(5, KAPI_EFFECT_MODIFY_STATE,
+			 "timer precision",
+			 "Timeout may be rounded up to system timer granularity")
+		KAPI_EFFECT_CONDITION("When timeout is specified")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(6)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "signal mask", "original mask", "user-specified mask",
+			 "Thread's signal mask is atomically changed to the provided mask")
+		KAPI_STATE_TRANS_COND("When sigmask is not NULL")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "process", "running", "blocked",
+			 "Process blocks waiting for events with specified signal mask")
+		KAPI_STATE_TRANS_COND("When no events available and not immediate return")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "process", "blocked", "running",
+			 "Process wakes up due to events, timeout expiry, or unblocked signal")
+		KAPI_STATE_TRANS_COND("When wait condition is satisfied")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "signal mask", "user-specified mask", "original mask",
+			 "Thread's signal mask is restored to its original value")
+		KAPI_STATE_TRANS_COND("When returning from epoll_pwait2")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(4, "pending signals", "blocked", "deliverable",
+			 "Signals that were blocked by the temporary mask become deliverable")
+		KAPI_STATE_TRANS_COND("When signal mask is restored and signals were pending")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(5, "timeout timer", "not started", "armed with nanosecond precision",
+			 "High resolution timer is armed with the specified timeout")
+		KAPI_STATE_TRANS_COND("When timeout is specified and > 0")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(6)
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, 0, "ANY_UNBLOCKED", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Signal not blocked by provided sigmask")
+		KAPI_SIGNAL_DESC("Any signal not blocked by the sigmask parameter will interrupt "
+				 "epoll_pwait2() and cause it to return -EINTR. Signal handling is "
+				 "identical to epoll_pwait().")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(1, SIGKILL, "SIGKILL", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_CONDITION("Cannot be blocked by sigmask")
+		KAPI_SIGNAL_DESC("SIGKILL cannot be blocked and will terminate the process immediately.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(2, SIGSTOP, "SIGSTOP", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_STOP)
+		KAPI_SIGNAL_CONDITION("Cannot be blocked by sigmask")
+		KAPI_SIGNAL_DESC("SIGSTOP cannot be blocked and will stop the process.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(3, 0, "BLOCKED_SIGNALS", KAPI_SIGNAL_BLOCK, KAPI_SIGNAL_ACTION_DEFAULT)
+		KAPI_SIGNAL_CONDITION("Signals in provided sigmask")
+		KAPI_SIGNAL_DESC("Signals specified in the sigmask parameter are blocked during "
+				 "the epoll_pwait2 call.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(4, SIGCONT, "SIGCONT", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_CONTINUE)
+		KAPI_SIGNAL_CONDITION("When process is stopped")
+		KAPI_SIGNAL_DESC("SIGCONT resumes a stopped process. If epoll_pwait2 was interrupted "
+				 "by SIGSTOP, it may return -EINTR when continued.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(5, SIGALRM, "SIGALRM", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Timer expiration")
+		KAPI_SIGNAL_DESC("SIGALRM or other timer signals will interrupt epoll_pwait2 with -EINTR "
+				 "if not blocked by sigmask")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	.signal_count = 6,
+
+	/* Signal mask specifications */
+	KAPI_SIGNAL_MASK(0, "user_sigmask", "User-provided signal mask atomically applied")
+		.description = "The signal mask is atomically set and restored exactly as in "
+			       "epoll_pwait(), providing the same race-condition prevention."
+	KAPI_SIGNAL_MASK_END
+
+	.signal_mask_count = 1,
+
+	/* Locking specifications */
+	KAPI_LOCK(0, "ep->lock", KAPI_LOCK_SPINLOCK)
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects the ready list while checking for and consuming events")
+	KAPI_LOCK_END
+
+	KAPI_LOCK(1, "ep->mtx", KAPI_LOCK_MUTEX)
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects against concurrent epoll_ctl operations during wait")
+	KAPI_LOCK_END
+
+	.lock_count = 2,
+
+	.examples = "sigset_t sigmask;\n"
+		    "struct epoll_event events[10];\n"
+		    "struct __kernel_timespec ts;\n\n"
+		    "/* Block SIGINT during epoll_pwait2 */\n"
+		    "sigemptyset(&sigmask);\n"
+		    "sigaddset(&sigmask, SIGINT);\n\n"
+		    "/* Wait for 1.5 seconds */\n"
+		    "ts.tv_sec = 1;\n"
+		    "ts.tv_nsec = 500000000; /* 500 milliseconds */\n\n"
+		    "int nfds = epoll_pwait2(epfd, events, 10, &ts, &sigmask, sizeof(sigmask));\n"
+		    "if (nfds == -1) {\n"
+		    "    if (errno == EINTR) {\n"
+		    "        /* Handle signal */\n"
+		    "    }\n"
+		    "    perror(\"epoll_pwait2\");\n"
+		    "    exit(EXIT_FAILURE);\n"
+		    "}\n\n"
+		    "/* Example with infinite timeout */\n"
+		    "nfds = epoll_pwait2(epfd, events, 10, NULL, &sigmask, sizeof(sigmask));",
+	.notes = "epoll_pwait2() provides nanosecond precision timeouts, addressing the limitation "
+		 "of epoll_pwait() which only supports millisecond precision. The timeout parameter "
+		 "uses struct __kernel_timespec which is compatible with 64-bit time values, making "
+		 "it Y2038-safe. Like epoll_pwait(), the signal mask operation is atomic. "
+		 "The timeout is still subject to system timer granularity and may be rounded up.",
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE6(epoll_pwait2, int, epfd, struct epoll_event __user *, events,
 		int, maxevents, const struct __kernel_timespec __user *, timeout,
 		const sigset_t __user *, sigmask, size_t, sigsetsize)
Signature · 1 line
2.39.5
#8 lore raw

RFC 8/19 exec: add API specification for execve

In reply to Sasha Levin

Add comprehensive kernel API specification for the execve() system call.

---
 fs/exec.c | 218 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 218 insertions(+)
fs/exec.c +218 -0
index 1f5fdd2e096e3..3d006105ab23d 100644
@@ -52,6 +52,7 @@
 #include <linux/mount.h>
 #include <linux/security.h>
 #include <linux/syscalls.h>
+#include <linux/syscall_api_spec.h>
 #include <linux/tsacct_kern.h>
 #include <linux/cn_proc.h>
 #include <linux/audit.h>
@@ -1997,7 +1998,224 @@ void set_dumpable(struct mm_struct *mm, int value)
 	set_mask_bits(&mm->flags, MMF_DUMPABLE_MASK, value);
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_execve)
+	KAPI_DESCRIPTION("Execute a new program")
+	KAPI_LONG_DESC("Executes the program referred to by filename. This causes the program "
+		       "that is currently being run by the calling process to be replaced with "
+		       "a new program, with newly initialized stack, heap, and (initialized and "
+		       "uninitialized) data segments. The process ID remains the same.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	KAPI_PARAM(0, "filename", "const char __user *", "Pathname of the program to execute")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_PATH,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Must be a valid pathname to an executable file or script",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "argv", "const char __user *const __user *", "Array of argument strings passed to the new program")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_USER_PTR,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "NULL-terminated array of pointers to null-terminated strings",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "envp", "const char __user *const __user *", "Array of environment strings for the new program")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_USER_PTR,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "NULL-terminated array of pointers to null-terminated strings in form key=value",
+	KAPI_PARAM_END
+
+	KAPI_RETURN("long", "Does not return on success; returns -1 on error")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+	KAPI_RETURN_END
+
+	KAPI_ERROR(0, -E2BIG, "E2BIG", "Argument list too long",
+		   "The total size of argv and envp exceeds the system limit.")
+	KAPI_ERROR(1, -EACCES, "EACCES", "Permission denied",
+		   "Search permission denied on a component of the path, file is not regular, "
+		   "or execute permission denied for file or interpreter.")
+	KAPI_ERROR(2, -EFAULT, "EFAULT", "Bad address",
+		   "filename, argv, or envp points outside accessible address space.")
+	KAPI_ERROR(3, -EINVAL, "EINVAL", "Invalid executable format",
+		   "An ELF executable has more than one PT_INTERP segment.")
+	KAPI_ERROR(4, -EIO, "EIO", "I/O error",
+		   "An I/O error occurred while reading from the file system.")
+	KAPI_ERROR(5, -EISDIR, "EISDIR", "Is a directory",
+		   "An ELF interpreter was a directory.")
+	KAPI_ERROR(6, -ELIBBAD, "ELIBBAD", "Invalid ELF interpreter",
+		   "An ELF interpreter was not in a recognized format.")
+	KAPI_ERROR(7, -ELOOP, "ELOOP", "Too many symbolic links",
+		   "Too many symbolic links encountered while resolving filename or interpreter.")
+	KAPI_ERROR(8, -EMFILE, "EMFILE", "Too many open files",
+		   "The per-process limit on open file descriptors has been reached.")
+	KAPI_ERROR(9, -ENAMETOOLONG, "ENAMETOOLONG", "Filename too long",
+		   "filename or one of the strings in argv or envp is too long.")
+	KAPI_ERROR(10, -ENFILE, "ENFILE", "System file table overflow",
+		   "The system-wide limit on open files has been reached.")
+	KAPI_ERROR(11, -ENOENT, "ENOENT", "File not found",
+		   "The file filename or an interpreter does not exist.")
+	KAPI_ERROR(12, -ENOEXEC, "ENOEXEC", "Exec format error",
+		   "An executable is not in a recognized format, is for wrong architecture, "
+		   "or has other format errors preventing execution.")
+	KAPI_ERROR(13, -ENOMEM, "ENOMEM", "Out of memory",
+		   "Insufficient kernel memory available.")
+	KAPI_ERROR(14, -ENOTDIR, "ENOTDIR", "Not a directory",
+		   "A component of the path prefix is not a directory.")
+	KAPI_ERROR(15, -EPERM, "EPERM", "Operation not permitted",
+		   "The filesystem is mounted nosuid, the user is not root, and the file has "
+		   "set-user-ID or set-group-ID bit set.")
+	KAPI_ERROR(16, -ETXTBSY, "ETXTBSY", "Text file busy",
+		   "The executable was open for writing by one or more processes.")
+	KAPI_ERROR(17, -EAGAIN, "EAGAIN", "Resource temporarily unavailable",
+		   "RLIMIT_NPROC limit exceeded - too many processes for this user.")
+
+	.error_count = 18,
+	.param_count = 3,
+	.since_version = "1.0",
+	.examples = "char *argv[] = { \"echo\", \"hello\", \"world\", NULL };\n"
+		    "char *envp[] = { \"PATH=/bin\", NULL };\n"
+		    "execve(\"/bin/echo\", argv, envp);\n"
+		    "/* This point is only reached on error */\n"
+		    "perror(\"execve failed\");\n"
+		    "exit(EXIT_FAILURE);",
+	.notes = "On success, execve() does not return; the new program is executed. "
+		 "File descriptors remain open unless marked close-on-exec. "
+		 "Signal dispositions are reset to default except for ignored signals. "
+		 "Any alternate signal stack is not preserved. "
+		 "The process's set of pending signals is cleared. "
+		 "All threads except the calling thread are destroyed.",
+
+	/* Fatal signals can interrupt exec */
+	KAPI_SIGNAL(0, 0, "FATAL_SIGNALS", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_CONDITION("Fatal signal pending during exec setup")
+		KAPI_SIGNAL_DESC("Fatal signals (checked via fatal_signal_pending()) can interrupt "
+				 "exec during setup phases like de_thread(). This causes exec to fail "
+				 "and the process to exit.")
+	KAPI_SIGNAL_END
+
+	/* SIGKILL sent to other threads */
+	KAPI_SIGNAL(1, SIGKILL, "SIGKILL", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_TARGET("All other threads in the thread group")
+		KAPI_SIGNAL_CONDITION("Multi-threaded process doing exec")
+		KAPI_SIGNAL_DESC("During de_thread(), zap_other_threads() sends SIGKILL to all "
+				 "other threads in the thread group to ensure only the execing "
+				 "thread survives.")
+	KAPI_SIGNAL_END
+
+	/* Signal handlers reset */
+	KAPI_SIGNAL(2, 0, "ALL_HANDLERS", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Signal has a handler installed")
+		KAPI_SIGNAL_DESC("flush_signal_handlers() resets all signal handlers to SIG_DFL "
+				 "except for signals that are ignored (SIG_IGN). This happens "
+				 "after de_thread() completes.")
+	KAPI_SIGNAL_END
+
+	/* Ignored signals preserved */
+	KAPI_SIGNAL(3, 0, "IGNORED_SIGNALS", KAPI_SIGNAL_IGNORE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Signal disposition is SIG_IGN")
+		KAPI_SIGNAL_DESC("Signals set to SIG_IGN are preserved across exec. This is "
+				 "POSIX-compliant behavior allowing parent processes to ignore "
+				 "signals in children.")
+	KAPI_SIGNAL_END
+
+	/* Pending signals cleared */
+	KAPI_SIGNAL(4, 0, "PENDING_SIGNALS", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Any pending signals")
+		KAPI_SIGNAL_DESC("All pending signals are cleared during exec. This includes "
+				 "both thread-specific and process-wide pending signals.")
+	KAPI_SIGNAL_END
+
+	/* Timer signals cleared */
+	KAPI_SIGNAL(5, 0, "TIMER_SIGNALS", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Timer-generated signals pending")
+		KAPI_SIGNAL_DESC("flush_itimer_signals() clears any pending timer signals "
+				 "(SIGALRM, SIGVTALRM, SIGPROF) to prevent confusion in the "
+				 "new program.")
+	KAPI_SIGNAL_END
+
+	/* Exit signal set to SIGCHLD */
+	KAPI_SIGNAL(6, SIGCHLD, "SIGCHLD", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_DEFAULT)
+		KAPI_SIGNAL_TARGET("Parent process when this process exits")
+		KAPI_SIGNAL_CONDITION("Process exit after exec")
+		KAPI_SIGNAL_DESC("The exit_signal is set to SIGCHLD during exec, ensuring the "
+				 "parent will receive SIGCHLD when this process terminates.")
+	KAPI_SIGNAL_END
+
+	/* Alternate signal stack cleared */
+	KAPI_SIGNAL(7, 0, "SIGALTSTACK", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Process had alternate signal stack")
+		KAPI_SIGNAL_DESC("Any alternate signal stack (sigaltstack) is not preserved "
+				 "across exec. The new program starts with no alternate stack.")
+	KAPI_SIGNAL_END
+
+	.signal_count = 8,
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_PROCESS_STATE | KAPI_EFFECT_FREE_MEMORY | KAPI_EFFECT_ALLOC_MEMORY,
+			 "process image",
+			 "Replaces entire process image including code, data, heap, and stack")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_RESOURCE_DESTROY,
+			 "file descriptors",
+			 "Closes all file descriptors with close-on-exec flag set")
+		KAPI_EFFECT_CONDITION("FD_CLOEXEC flag set")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_MODIFY_STATE,
+			 "signal handlers",
+			 "Resets all signal handlers to default, preserves ignored signals")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_PROCESS_STATE | KAPI_EFFECT_SIGNAL_SEND,
+			 "thread group",
+			 "Kills all other threads in the thread group with SIGKILL")
+		KAPI_EFFECT_CONDITION("Multi-threaded process")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(4, KAPI_EFFECT_MODIFY_STATE,
+			 "process attributes",
+			 "Clears pending signals, timers, alternate signal stack, and various process attributes")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(5, KAPI_EFFECT_FILESYSTEM,
+			 "executable file",
+			 "Opens and reads the executable file, may trigger filesystem operations")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(6)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "process memory",
+			 "old program image", "new program image",
+			 "Complete replacement of process address space with new program")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "process credentials",
+			 "current credentials", "potentially modified credentials",
+			 "May change effective UID/GID based on file permissions")
+		KAPI_STATE_TRANS_COND("setuid/setgid binary")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "thread state",
+			 "multi-threaded", "single-threaded",
+			 "Process becomes single-threaded after killing other threads")
+		KAPI_STATE_TRANS_COND("Multi-threaded process")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "signal state",
+			 "custom handlers and pending signals", "default handlers, no pending signals",
+			 "Signal handling reset to clean state for new program")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(4)
+KAPI_END_SPEC;
 SYSCALL_DEFINE3(execve,
+
 		const char __user *, filename,
 		const char __user *const __user *, argv,
 		const char __user *const __user *, envp)
Signature · 1 line
2.39.5
#13 lore raw

RFC 9/19 exec: add API specification for execveat

In reply to Sasha Levin

Add comprehensive kernel API specification for the execveat() system call.

---
 fs/exec.c | 245 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 245 insertions(+)
fs/exec.c +245 -0
index 3d006105ab23d..49d8647c053ef 100644
@@ -2223,6 +2223,251 @@ SYSCALL_DEFINE3(execve,
 	return do_execve(getname(filename), argv, envp);
 }
 
+
+/* Valid flag combinations for execveat */
+static const s64 execveat_valid_flags[] = {
+	0,
+	AT_EMPTY_PATH,
+	AT_SYMLINK_NOFOLLOW,
+	AT_EXECVE_CHECK,
+	AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW,
+	AT_EMPTY_PATH | AT_EXECVE_CHECK,
+	AT_SYMLINK_NOFOLLOW | AT_EXECVE_CHECK,
+	AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW | AT_EXECVE_CHECK,
+};
+
+DEFINE_KERNEL_API_SPEC(sys_execveat)
+	KAPI_DESCRIPTION("Execute a new program relative to a directory file descriptor")
+	KAPI_LONG_DESC("Executes the program referred to by the combination of fd and filename. "
+		       "This system call is useful when implementing a secure execution environment "
+		       "or when the calling process has an open file descriptor but no access to "
+		       "the corresponding pathname. Like execve(), it replaces the current process "
+		       "image with a new process image.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	KAPI_PARAM(0, "fd", "int", "Directory file descriptor")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_FD,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "AT_FDCWD for current directory, or valid directory file descriptor",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "filename", "const char __user *", "Pathname of the program to execute")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER | KAPI_PARAM_OPTIONAL)
+		.type = KAPI_TYPE_PATH,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Relative or absolute path; empty string with AT_EMPTY_PATH to use fd directly",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "argv", "const char __user *const __user *", "Array of argument strings passed to the new program")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_USER_PTR,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "NULL-terminated array of pointers to null-terminated strings",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(3, "envp", "const char __user *const __user *", "Array of environment strings for the new program")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_USER_PTR,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "NULL-terminated array of pointers to null-terminated strings in form key=value",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(4, "flags", "int", "Execution flags")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_INT,
+		.constraint_type = KAPI_CONSTRAINT_MASK,
+		.valid_mask = AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW | AT_EXECVE_CHECK,
+		.constraints = "0 or combination of AT_EMPTY_PATH, AT_SYMLINK_NOFOLLOW, and AT_EXECVE_CHECK",
+	KAPI_PARAM_END
+
+	/* Return specification */
+	KAPI_RETURN("long", "Does not return on success (except with AT_EXECVE_CHECK which returns 0); returns -1 on error")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+	KAPI_RETURN_END
+
+	/* Error codes */
+	KAPI_ERROR(0, -E2BIG, "E2BIG", "Argument list too long", "The total size of argv and envp exceeds the system limit.")
+	KAPI_ERROR(1, -EACCES, "EACCES", "Permission denied", "Search permission denied on a component of the path, file is not regular, or execute permission denied for file or interpreter.")
+	KAPI_ERROR(2, -EBADF, "EBADF", "Bad file descriptor", "fd is not a valid file descriptor.")
+	KAPI_ERROR(3, -EFAULT, "EFAULT", "Bad address", "filename, argv, or envp points outside accessible address space.")
+	KAPI_ERROR(4, -EINVAL, "EINVAL", "Invalid flags or executable format", "Invalid flags specified, or ELF executable has more than one PT_INTERP segment.")
+	KAPI_ERROR(5, -EIO, "EIO", "I/O error", "An I/O error occurred while reading from the file system.")
+	KAPI_ERROR(6, -EISDIR, "EISDIR", "Is a directory", "An ELF interpreter was a directory.")
+	KAPI_ERROR(7, -ELIBBAD, "ELIBBAD", "Invalid ELF interpreter", "An ELF interpreter was not in a recognized format.")
+	KAPI_ERROR(8, -ELOOP, "ELOOP", "Too many symbolic links", "Too many symbolic links encountered, or AT_SYMLINK_NOFOLLOW was specified but filename refers to a symbolic link.")
+	KAPI_ERROR(9, -EMFILE, "EMFILE", "Too many open files", "The per-process limit on open file descriptors has been reached.")
+	KAPI_ERROR(10, -ENAMETOOLONG, "ENAMETOOLONG", "Filename too long", "filename or one of the strings in argv or envp is too long.")
+	KAPI_ERROR(11, -ENFILE, "ENFILE", "System file table overflow", "The system-wide limit on open files has been reached.")
+	KAPI_ERROR(12, -ENOENT, "ENOENT", "File not found", "The file filename or an interpreter does not exist, or filename is empty and AT_EMPTY_PATH was not specified in flags.")
+	KAPI_ERROR(13, -ENOEXEC, "ENOEXEC", "Exec format error", "An executable is not in a recognized format, is for wrong architecture, or has other format errors preventing execution.")
+	KAPI_ERROR(14, -ENOMEM, "ENOMEM", "Out of memory", "Insufficient kernel memory available.")
+	KAPI_ERROR(15, -ENOTDIR, "ENOTDIR", "Not a directory", "A component of the path prefix is not a directory, or fd is not a directory when a relative path is given.")
+	KAPI_ERROR(16, -EPERM, "EPERM", "Operation not permitted", "The filesystem is mounted nosuid, the user is not root, and the file has set-user-ID or set-group-ID bit set.")
+	KAPI_ERROR(17, -ETXTBSY, "ETXTBSY", "Text file busy", "The executable was open for writing by one or more processes.")
+	KAPI_ERROR(18, -EAGAIN, "EAGAIN", "Resource temporarily unavailable", "RLIMIT_NPROC limit exceeded - too many processes for this user.")
+	KAPI_ERROR(19, -EINTR, "EINTR", "Interrupted by signal", "The exec was interrupted by a signal during setup phase.")
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, 0, "FATAL_SIGNALS", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_CONDITION("Fatal signal pending during exec setup")
+		KAPI_SIGNAL_DESC("Fatal signals (checked via fatal_signal_pending()) can interrupt exec during setup phases like de_thread(). This causes exec to fail and the process to exit.")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(1, SIGKILL, "SIGKILL", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_TERMINATE)
+		KAPI_SIGNAL_TARGET("All other threads in the thread group")
+		KAPI_SIGNAL_CONDITION("Multi-threaded process doing exec")
+		KAPI_SIGNAL_DESC("During de_thread(), zap_other_threads() sends SIGKILL to all other threads in the thread group to ensure only the execing thread survives.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(2, 0, "ALL_HANDLERS", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Signal has a handler installed")
+		KAPI_SIGNAL_DESC("flush_signal_handlers() resets all signal handlers to SIG_DFL except for signals that are ignored (SIG_IGN). This happens after de_thread() completes.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(3, 0, "IGNORED_SIGNALS", KAPI_SIGNAL_IGNORE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Signal disposition is SIG_IGN")
+		KAPI_SIGNAL_DESC("Signals set to SIG_IGN are preserved across exec. This is POSIX-compliant behavior allowing parent processes to ignore signals in children.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(4, 0, "PENDING_SIGNALS", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Any pending signals")
+		KAPI_SIGNAL_DESC("All pending signals are cleared during exec. This includes both thread-specific and process-wide pending signals.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(5, 0, "TIMER_SIGNALS", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Timer-generated signals pending")
+		KAPI_SIGNAL_DESC("flush_itimer_signals() clears any pending timer signals (SIGALRM, SIGVTALRM, SIGPROF) to prevent confusion in the new program.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(6, SIGCHLD, "SIGCHLD", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_DEFAULT)
+		KAPI_SIGNAL_TARGET("Parent process when this process exits")
+		KAPI_SIGNAL_CONDITION("Process exit after exec")
+		KAPI_SIGNAL_DESC("The exit_signal is set to SIGCHLD during exec, ensuring the parent will receive SIGCHLD when this process terminates.")
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(7, 0, "SIGALTSTACK", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM)
+		KAPI_SIGNAL_CONDITION("Process had alternate signal stack")
+		KAPI_SIGNAL_DESC("Any alternate signal stack (sigaltstack) is not preserved across exec. The new program starts with no alternate stack.")
+	KAPI_SIGNAL_END
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_PROCESS_STATE | KAPI_EFFECT_FREE_MEMORY | KAPI_EFFECT_ALLOC_MEMORY,
+			 "process image",
+			 "Replaces entire process image including code, data, heap, and stack")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_RESOURCE_DESTROY,
+			 "file descriptors",
+			 "Closes all file descriptors with close-on-exec flag set")
+		KAPI_EFFECT_CONDITION("FD_CLOEXEC flag set")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_MODIFY_STATE,
+			 "signal handlers",
+			 "Resets all signal handlers to default, preserves ignored signals")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_PROCESS_STATE | KAPI_EFFECT_SIGNAL_SEND,
+			 "thread group",
+			 "Kills all other threads in the thread group with SIGKILL")
+		KAPI_EFFECT_CONDITION("Multi-threaded process")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(4, KAPI_EFFECT_MODIFY_STATE,
+			 "process attributes",
+			 "Clears pending signals, timers, alternate signal stack, and various process attributes")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(5, KAPI_EFFECT_FILESYSTEM,
+			 "executable file",
+			 "Opens and reads the executable file, may trigger filesystem operations")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(6, KAPI_EFFECT_MODIFY_STATE,
+			 "security context",
+			 "May change SELinux/AppArmor context based on file labels and transitions")
+		KAPI_EFFECT_CONDITION("LSM enabled")
+	KAPI_SIDE_EFFECT_END
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "process memory",
+			 "old program image", "new program image",
+			 "Complete replacement of process address space with new program")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "process credentials",
+			 "current credentials", "potentially modified credentials",
+			 "May change effective UID/GID based on file permissions")
+		KAPI_STATE_TRANS_COND("setuid/setgid binary")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "thread state",
+			 "multi-threaded", "single-threaded",
+			 "Process becomes single-threaded after killing other threads")
+		KAPI_STATE_TRANS_COND("Multi-threaded process")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "signal state",
+			 "custom handlers and pending signals", "default handlers, no pending signals",
+			 "Signal handling reset to clean state for new program")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(4, "file descriptor table",
+			 "contains close-on-exec FDs", "close-on-exec FDs closed",
+			 "All file descriptors marked FD_CLOEXEC are closed during exec")
+		KAPI_STATE_TRANS_COND("FDs with FD_CLOEXEC")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(5, "working directory",
+			 "fd-relative operations", "resolved to absolute paths",
+			 "Directory fd operations resolved before exec completes")
+		KAPI_STATE_TRANS_COND("Using dirfd != AT_FDCWD")
+	KAPI_STATE_TRANS_END
+
+	/* Locking information */
+	KAPI_LOCK(0, "cred_guard_mutex", KAPI_LOCK_MUTEX)
+		KAPI_LOCK_DESC("Protects against concurrent credential changes during exec")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_DESC("Ensures atomic credential transition during exec process")
+	KAPI_LOCK_END
+
+	KAPI_LOCK(1, "sighand->siglock", KAPI_LOCK_SPINLOCK)
+		KAPI_LOCK_DESC("Protects signal handler modifications")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Taken during signal handler reset and pending signal clearing")
+	KAPI_LOCK_END
+
+	KAPI_SIDE_EFFECT_COUNT(7)
+	KAPI_STATE_TRANS_COUNT(6)
+
+	.error_count = 20,
+	.param_count = 5,
+	.since_version = "3.19",
+	.examples = "/* Execute /bin/echo using AT_FDCWD */\n"
+		    "char *argv[] = { \"echo\", \"hello\", NULL };\n"
+		    "char *envp[] = { \"PATH=/bin\", NULL };\n"
+		    "execveat(AT_FDCWD, \"/bin/echo\", argv, envp, 0);\n\n"
+		    "/* Execute via file descriptor */\n"
+		    "int fd = open(\"/bin/echo\", O_PATH);\n"
+		    "execveat(fd, \"\", argv, envp, AT_EMPTY_PATH);\n\n"
+		    "/* Execute relative to directory fd */\n"
+		    "int dirfd = open(\"/bin\", O_RDONLY | O_DIRECTORY);\n"
+		    "execveat(dirfd, \"echo\", argv, envp, 0);",
+	.notes = "execveat() was added to allow fexecve() to be implemented on systems that "
+		 "do not have /proc mounted. When filename is an empty string and AT_EMPTY_PATH "
+		 "is specified, the file descriptor fd specifies the file to be executed. "
+		 "AT_SYMLINK_NOFOLLOW prevents following symbolic links. "
+		 "AT_EXECVE_CHECK (since Linux 6.12) only checks if execution would be allowed "
+		 "without actually executing. Like execve(), on success execveat() does not return "
+		 "(except with AT_EXECVE_CHECK which returns 0).",
+	.signal_count = 8,
+	.lock_count = 2,
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE5(execveat,
 		int, fd, const char __user *, filename,
 		const char __user *const __user *, argv,
Signature · 1 line
2.39.5
#14 lore raw

RFC 10/19 mm/mlock: add API specification for mlock

In reply to Sasha Levin

Add kernel API specification for the mlock() system call.

---
 mm/mlock.c | 105 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 105 insertions(+)
mm/mlock.c +105 -0
index 3cb72b579ffd3..a37102df54b01 100644
@@ -25,6 +25,7 @@
 #include <linux/memcontrol.h>
 #include <linux/mm_inline.h>
 #include <linux/secretmem.h>
+#include <linux/syscall_api_spec.h>
 
 #include "internal.h"
 
@@ -658,6 +659,110 @@ static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t fla
 	return 0;
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_mlock)
+	KAPI_DESCRIPTION("Lock pages in memory")
+	KAPI_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.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	KAPI_PARAM(0, "start", "unsigned long", "Starting address of memory range to lock")
+		.type = KAPI_TYPE_UINT,
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Rounded down to page boundary",
+	KAPI_PARAM_END
+	KAPI_PARAM(1, "len", "size_t", "Length of memory range to lock in bytes")
+		.type = KAPI_TYPE_UINT,
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		KAPI_PARAM_RANGE(0, LONG_MAX)
+		.constraints = "Rounded up to page boundary",
+	KAPI_PARAM_END
+
+	.return_spec = {
+		.type_name = "long",
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.success_value = 0,
+		.description = "0 on success, negative error code on failure",
+	},
+
+	KAPI_ERROR(0, -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.")
+	KAPI_ERROR(1, -EPERM, "EPERM", "Insufficient privileges",
+		   "The caller is not privileged (no CAP_IPC_LOCK) and RLIMIT_MEMLOCK is 0.")
+	KAPI_ERROR(2, -EINVAL, "EINVAL", "Address overflow",
+		   "The result of the addition start+len was less than start (arithmetic overflow).")
+	KAPI_ERROR(3, -EAGAIN, "EAGAIN", "Some or all memory could not be locked",
+		   "Some or all of the specified address range could not be locked.")
+	KAPI_ERROR(4, -EINTR, "EINTR", "Interrupted by signal",
+		   "The operation was interrupted by a fatal signal before completion.")
+
+	.error_count = 5,
+	.param_count = 2,
+	.since_version = "2.0",
+
+	.locks[0] = {
+		.lock_name = "mmap_lock",
+		.lock_type = KAPI_LOCK_RWLOCK,
+		.acquired = true,
+		.released = true,
+		.description = "Process memory map write lock",
+	},
+	.lock_count = 1,
+
+	/* Signal specifications */
+	.signal_count = 1,
+
+	/* Fatal signals can interrupt mmap_write_lock_killable */
+	KAPI_SIGNAL(0, 0, "FATAL", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Fatal signal pending")
+		KAPI_SIGNAL_DESC("Fatal signals (SIGKILL, etc.) can interrupt the operation "
+				 "when acquiring mmap_write_lock_killable(), causing -EINTR return")
+	KAPI_SIGNAL_END
+
+	.examples = "mlock(addr, 4096);  // Lock one page\n"
+		    "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.",
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_ALLOC_MEMORY,
+			 "process memory",
+			 "Locks pages into physical memory, preventing swapping")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE,
+			 "mm->locked_vm",
+			 "Increases process locked memory counter")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_ALLOC_MEMORY,
+			 "physical pages",
+			 "May allocate and populate page table entries")
+		KAPI_EFFECT_CONDITION("Pages not already present")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(3)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "memory pages", "swappable", "locked in RAM",
+			 "Pages become non-swappable and pinned in physical memory")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "VMA flags", "unlocked", "VM_LOCKED set",
+			 "Virtual memory area marked as locked")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(2)
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE2(mlock, unsigned long, start, size_t, len)
 {
 	return do_mlock(start, len, VM_LOCKED);
Signature · 1 line
2.39.5
#15 lore raw

RFC 11/19 mm/mlock: add API specification for mlock2

In reply to Sasha Levin

Add kernel API specification for the mlock2() system call.

---
 mm/mlock.c | 148 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 148 insertions(+)
mm/mlock.c +148 -0
index a37102df54b01..af2ab78acc226 100644
@@ -768,6 +768,154 @@ SYSCALL_DEFINE2(mlock, unsigned long, start, size_t, len)
 	return do_mlock(start, len, VM_LOCKED);
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_mlock2)
+	KAPI_DESCRIPTION("Lock pages in memory with flags")
+	KAPI_LONG_DESC("Enhanced version of mlock() that supports flags. "
+		       "MLOCK_ONFAULT flag allows locking pages on fault rather than immediately.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "start", "unsigned long", "Starting address of memory range to lock")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Rounded down to page boundary",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "len", "size_t", "Length of memory range to lock in bytes")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		KAPI_PARAM_RANGE(0, LONG_MAX)
+		.constraints = "Rounded up to page boundary",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "flags", "int", "Flags controlling lock behavior")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_INT,
+		.constraint_type = KAPI_CONSTRAINT_MASK,
+		.valid_mask = MLOCK_ONFAULT,
+		.constraints = "Only MLOCK_ONFAULT flag is currently supported",
+	KAPI_PARAM_END
+
+	/* Return specification */
+	KAPI_RETURN("long", "0 on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.success_value = 0,
+	KAPI_RETURN_END
+
+	/* Error codes */
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "Invalid flags", "Unknown flags were specified (flags & ~MLOCK_ONFAULT).")
+	KAPI_ERROR(1, -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.")
+	KAPI_ERROR(2, -EPERM, "EPERM", "Insufficient privileges", "The caller is not privileged (no CAP_IPC_LOCK) and RLIMIT_MEMLOCK is 0.")
+	KAPI_ERROR(3, -EAGAIN, "EAGAIN", "Some or all memory could not be locked", "Some or all of the specified address range could not be locked.")
+	KAPI_ERROR(4, -EINTR, "EINTR", "Interrupted by signal", "The operation was interrupted by a fatal signal before completion.")
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, 0, "FATAL_SIGNALS", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Fatal signal pending during mmap_write_lock_killable")
+		KAPI_SIGNAL_DESC("Fatal signals (SIGKILL, SIGTERM, etc.) can interrupt the operation when acquiring mmap_write_lock_killable(), causing -EINTR return")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(1, SIGBUS, "SIGBUS", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_DEFAULT)
+		KAPI_SIGNAL_TARGET("Current process")
+		KAPI_SIGNAL_CONDITION("Memory access to locked page fails")
+		KAPI_SIGNAL_DESC("Can be generated if accessing a locked page that cannot be brought into memory (e.g., truncated file mapping)")
+	KAPI_SIGNAL_END
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_ALLOC_MEMORY,
+			 "process memory",
+			 "Locks pages into physical memory, preventing swapping")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("Pages become resident in RAM")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE,
+			 "mm->locked_vm",
+			 "Increases process locked memory counter")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("Counted against RLIMIT_MEMLOCK")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_ALLOC_MEMORY,
+			 "page tables",
+			 "May allocate and populate page table entries")
+		KAPI_EFFECT_CONDITION("Pages not already present")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_MODIFY_STATE,
+			 "VMA flags",
+			 "Sets VM_LOCKED and optionally VM_LOCKONFAULT on affected VMAs")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(4, KAPI_EFFECT_FILESYSTEM,
+			 "page fault behavior",
+			 "With MLOCK_ONFAULT, changes how future page faults are handled")
+		KAPI_EFFECT_CONDITION("MLOCK_ONFAULT flag specified")
+	KAPI_SIDE_EFFECT_END
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "memory pages",
+			 "swappable", "locked in RAM",
+			 "Pages become non-swappable and pinned in physical memory")
+		KAPI_STATE_TRANS_COND("Without MLOCK_ONFAULT")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "VMA flags",
+			 "unlocked", "VM_LOCKED set",
+			 "Virtual memory area marked as locked")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "VMA flags",
+			 "normal fault", "VM_LOCKONFAULT set",
+			 "VMA marked to lock pages on future faults")
+		KAPI_STATE_TRANS_COND("MLOCK_ONFAULT flag specified")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "page residency",
+			 "may be swapped", "resident in memory",
+			 "Pages brought into RAM and kept there")
+		KAPI_STATE_TRANS_COND("Without MLOCK_ONFAULT")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(4, "process statistics",
+			 "normal memory accounting", "locked memory accounting",
+			 "Memory counted against RLIMIT_MEMLOCK")
+	KAPI_STATE_TRANS_END
+
+	/* Locking information */
+	KAPI_LOCK(0, "mmap_lock", KAPI_LOCK_RWLOCK)
+		KAPI_LOCK_DESC("Process memory map write lock")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects VMA modifications during lock operation")
+	KAPI_LOCK_END
+
+	KAPI_LOCK(1, "lru_lock", KAPI_LOCK_SPINLOCK)
+		KAPI_LOCK_DESC("Per-memcg LRU list lock")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Taken when moving pages to unevictable list when locking pages")
+	KAPI_LOCK_END
+
+	.error_count = 5,
+	.param_count = 3,
+	.since_version = "4.4",
+	.signal_count = 2,
+	.side_effect_count = 5,
+	.state_trans_count = 5,
+	.lock_count = 2,
+	.examples = "mlock2(addr, len, 0);            // Same as mlock()\n"
+		    "mlock2(addr, len, MLOCK_ONFAULT); // Lock on fault",
+	.notes = "MLOCK_ONFAULT flag defers actual page locking until pages are accessed. "
+		 "Memory locks do not stack. Locks are not inherited by child processes.",
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE3(mlock2, unsigned long, start, size_t, len, int, flags)
 {
 	vm_flags_t vm_flags = VM_LOCKED;
Signature · 1 line
2.39.5
#16 lore raw

RFC 12/19 mm/mlock: add API specification for mlockall

In reply to Sasha Levin

Add kernel API specification for the mlockall() system call.

---
 mm/mlock.c | 144 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 144 insertions(+)
mm/mlock.c +144 -0
index af2ab78acc226..95ee707c5922f 100644
@@ -997,6 +997,150 @@ static int apply_mlockall_flags(int flags)
 	return 0;
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_mlockall)
+	KAPI_DESCRIPTION("Lock all process pages in memory")
+	KAPI_LONG_DESC("Locks all pages mapped into the process address space. "
+		       "MCL_CURRENT locks current pages, MCL_FUTURE locks future mappings, "
+		       "MCL_ONFAULT defers locking until page fault.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "flags", "int", "Flags controlling which pages to lock")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_INT,
+		.constraint_type = KAPI_CONSTRAINT_MASK,
+		.valid_mask = MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT,
+		.constraints = "Must specify MCL_CURRENT and/or MCL_FUTURE; MCL_ONFAULT can be OR'd",
+	KAPI_PARAM_END
+
+	/* Return specification */
+	KAPI_RETURN("long", "0 on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.success_value = 0,
+	KAPI_RETURN_END
+
+	/* Error codes */
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "Invalid flags", "Invalid combination of flags specified, or no flags set, or only MCL_ONFAULT without MCL_CURRENT or MCL_FUTURE.")
+	KAPI_ERROR(1, -EPERM, "EPERM", "Insufficient privileges", "The caller is not privileged (no CAP_IPC_LOCK) and RLIMIT_MEMLOCK is 0.")
+	KAPI_ERROR(2, -ENOMEM, "ENOMEM", "Insufficient resources", "MCL_CURRENT is set and total VM size exceeds RLIMIT_MEMLOCK and caller lacks CAP_IPC_LOCK.")
+	KAPI_ERROR(3, -EINTR, "EINTR", "Interrupted by signal", "The operation was interrupted by a signal before completion.")
+	KAPI_ERROR(4, -EAGAIN, "EAGAIN", "Some memory could not be locked", "Some pages could not be locked, possibly due to memory pressure.")
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, 0, "FATAL_SIGNALS", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Fatal signal pending during mmap_write_lock_killable")
+		KAPI_SIGNAL_DESC("Fatal signals (SIGKILL, SIGTERM, etc.) can interrupt the operation when acquiring mmap_write_lock_killable(), causing -EINTR return")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	KAPI_SIGNAL(1, SIGBUS, "SIGBUS", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_DEFAULT)
+		KAPI_SIGNAL_TARGET("Current process")
+		KAPI_SIGNAL_CONDITION("Memory access to locked page fails")
+		KAPI_SIGNAL_DESC("Can be generated later if accessing a locked page that cannot be brought into memory (e.g., truncated file mapping)")
+	KAPI_SIGNAL_END
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_ALLOC_MEMORY,
+			 "all process memory",
+			 "Locks all current pages into physical memory, preventing swapping")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("MCL_CURRENT flag set")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE,
+			 "mm->def_flags",
+			 "Sets VM_LOCKED in default flags for future mappings")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("MCL_FUTURE flag set")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_MODIFY_STATE,
+			 "mm->locked_vm",
+			 "Increases process locked memory counter for entire address space")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("MCL_CURRENT flag set")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_ALLOC_MEMORY,
+			 "page tables",
+			 "May allocate and populate page table entries for all mappings")
+		KAPI_EFFECT_CONDITION("MCL_CURRENT without MCL_ONFAULT")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(4, KAPI_EFFECT_MODIFY_STATE,
+			 "VMA flags",
+			 "Sets VM_LOCKED on all existing VMAs")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("MCL_CURRENT flag set")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(5, KAPI_EFFECT_SCHEDULE,
+			 "mm_populate",
+			 "Triggers population of entire address space")
+		KAPI_EFFECT_CONDITION("MCL_CURRENT without MCL_ONFAULT")
+	KAPI_SIDE_EFFECT_END
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "all memory pages",
+			 "swappable", "locked in RAM",
+			 "All pages in process become non-swappable")
+		KAPI_STATE_TRANS_COND("MCL_CURRENT flag set")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "future mappings",
+			 "normal", "auto-locked",
+			 "New mappings will be automatically locked")
+		KAPI_STATE_TRANS_COND("MCL_FUTURE flag set")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "VMA flags",
+			 "varied", "all VM_LOCKED",
+			 "All virtual memory areas marked as locked")
+		KAPI_STATE_TRANS_COND("MCL_CURRENT flag set")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "page fault behavior",
+			 "normal faulting", "lock on fault",
+			 "Pages locked when faulted in rather than immediately")
+		KAPI_STATE_TRANS_COND("MCL_ONFAULT flag set")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(4, "process statistics",
+			 "partial locked memory", "all memory locked",
+			 "Entire VM size counted against RLIMIT_MEMLOCK")
+		KAPI_STATE_TRANS_COND("MCL_CURRENT flag set")
+	KAPI_STATE_TRANS_END
+
+	/* Locking information */
+	KAPI_LOCK(0, "mmap_lock", KAPI_LOCK_RWLOCK)
+		KAPI_LOCK_DESC("Process memory map write lock")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects VMA modifications during mlockall operation")
+	KAPI_LOCK_END
+
+	KAPI_LOCK(1, "lru_lock", KAPI_LOCK_SPINLOCK)
+		KAPI_LOCK_DESC("Per-memcg LRU list lock")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Taken when moving pages to unevictable list for all locked pages")
+	KAPI_LOCK_END
+
+	.error_count = 5,
+	.param_count = 1,
+	.since_version = "2.0",
+	.signal_count = 2,
+	.side_effect_count = 6,
+	.state_trans_count = 5,
+	.lock_count = 2,
+	.examples = "mlockall(MCL_CURRENT);                    // Lock current mappings\n"
+		    "mlockall(MCL_CURRENT | MCL_FUTURE);       // Lock current and future\n"
+		    "mlockall(MCL_CURRENT | MCL_ONFAULT);      // Lock current on fault",
+	.notes = "Affects all current VMAs and optionally future mappings via mm->def_flags",
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE1(mlockall, int, flags)
 {
 	unsigned long lock_limit;
Signature · 1 line
2.39.5
#17 lore raw

RFC 13/19 mm/mlock: add API specification for munlock

In reply to Sasha Levin

Add kernel API specification for the munlock() system call.

---
 mm/mlock.c | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 129 insertions(+)
mm/mlock.c +129 -0
index 95ee707c5922f..ef691adc78ad7 100644
@@ -929,6 +929,135 @@ SYSCALL_DEFINE3(mlock2, unsigned long, start, size_t, len, int, flags)
 	return do_mlock(start, len, vm_flags);
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_munlock)
+	KAPI_DESCRIPTION("Unlock pages in memory")
+	KAPI_LONG_DESC("Unlocks pages in the specified address range, allowing them "
+		       "to be paged out to swap if needed.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "start", "unsigned long", "Starting address of memory range to unlock")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_NONE,
+		.constraints = "Rounded down to page boundary",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "len", "size_t", "Length of memory range to unlock in bytes")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		KAPI_PARAM_RANGE(0, LONG_MAX)
+		.constraints = "Rounded up to page boundary",
+	KAPI_PARAM_END
+
+	/* Return specification */
+	KAPI_RETURN("long", "0 on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.success_value = 0,
+	KAPI_RETURN_END
+
+	/* Error codes */
+	KAPI_ERROR(0, -ENOMEM, "ENOMEM", "Memory range not mapped", "(Linux 2.6.9 and later) Some of the specified address range does not correspond to mapped pages in the process address space.")
+	KAPI_ERROR(1, -EINTR, "EINTR", "Interrupted by signal", "The operation was interrupted by a signal before completion.")
+	KAPI_ERROR(2, -EINVAL, "EINVAL", "Address overflow", "The result of the addition start+len was less than start (arithmetic overflow).")
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, 0, "FATAL_SIGNALS", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Fatal signal pending during mmap_write_lock_killable")
+		KAPI_SIGNAL_DESC("Fatal signals (SIGKILL, SIGTERM, etc.) can interrupt the operation when acquiring mmap_write_lock_killable(), causing -EINTR return")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE,
+			 "process memory",
+			 "Unlocks pages, making them eligible for swapping")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("Pages were previously locked")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE,
+			 "mm->locked_vm",
+			 "Decreases process locked memory counter")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("Pages were counted in locked_vm")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_MODIFY_STATE,
+			 "VMA flags",
+			 "Clears VM_LOCKED and VM_LOCKONFAULT from affected VMAs")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_MODIFY_STATE,
+			 "page flags",
+			 "Clears PG_mlocked flag from unlocked pages")
+		KAPI_EFFECT_CONDITION("Pages had PG_mlocked set")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(4, KAPI_EFFECT_MODIFY_STATE,
+			 "LRU lists",
+			 "Moves pages from unevictable to appropriate LRU list")
+		KAPI_EFFECT_CONDITION("Pages were on unevictable list")
+	KAPI_SIDE_EFFECT_END
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "memory pages",
+			 "locked in RAM", "swappable",
+			 "Pages become eligible for swap out")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "VMA flags",
+			 "VM_LOCKED set", "VM_LOCKED cleared",
+			 "Virtual memory areas no longer marked as locked")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "page residency",
+			 "guaranteed resident", "may be swapped",
+			 "Pages can now be evicted under memory pressure")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "process statistics",
+			 "locked memory accounted", "normal memory accounting",
+			 "Memory no longer counted against RLIMIT_MEMLOCK")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(4, "page LRU status",
+			 "unevictable list", "active/inactive list",
+			 "Pages moved to normal LRU lists for reclaim")
+		KAPI_STATE_TRANS_COND("Pages were mlocked")
+	KAPI_STATE_TRANS_END
+
+	/* Locking information */
+	KAPI_LOCK(0, "mmap_lock", KAPI_LOCK_RWLOCK)
+		KAPI_LOCK_DESC("Process memory map write lock")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects VMA modifications during unlock operation")
+	KAPI_LOCK_END
+
+	KAPI_LOCK(1, "lru_lock", KAPI_LOCK_SPINLOCK)
+		KAPI_LOCK_DESC("Per-memcg LRU list lock")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Taken when moving pages from unevictable to normal LRU lists")
+	KAPI_LOCK_END
+
+	.error_count = 3,
+	.param_count = 2,
+	.since_version = "2.0",
+	.signal_count = 1,
+	.side_effect_count = 5,
+	.state_trans_count = 5,
+	.lock_count = 2,
+	.examples = "munlock(addr, 4096);  // Unlock one page\n"
+		    "munlock(addr, len);   // Unlock range of pages",
+	.notes = "No special permissions required to unlock memory",
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE2(munlock, unsigned long, start, size_t, len)
 {
 	int ret;
Signature · 1 line
2.39.5
#18 lore raw

RFC 14/19 mm/mlock: add API specification for munlockall

In reply to Sasha Levin

Add kernel API specification for the munlockall() system call.

---
 mm/mlock.c | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 120 insertions(+)
mm/mlock.c +120 -0
index ef691adc78ad7..80f51e932aa95 100644
@@ -1299,6 +1299,126 @@ SYSCALL_DEFINE1(mlockall, int, flags)
 	return ret;
 }
 
+
+DEFINE_KERNEL_API_SPEC(sys_munlockall)
+	KAPI_DESCRIPTION("Unlock all process pages")
+	KAPI_LONG_DESC("Unlocks all pages mapped into the process address space and "
+		       "clears the MCL_FUTURE flag if set.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* No parameters - this is a SYSCALL_DEFINE0 */
+	.param_count = 0,
+
+	/* Return specification */
+	KAPI_RETURN("long", "0 on success, negative error code on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.success_value = 0,
+	KAPI_RETURN_END
+
+	/* Error codes */
+	KAPI_ERROR(0, -EINTR, "EINTR", "Interrupted by signal", "The operation was interrupted by a signal before completion.")
+	KAPI_ERROR(1, -ENOMEM, "ENOMEM", "Memory operation failed", "Failed to modify memory mappings (should not normally occur).")
+
+	/* Signal specifications */
+	KAPI_SIGNAL(0, 0, "FATAL_SIGNALS", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RETURN)
+		KAPI_SIGNAL_CONDITION("Fatal signal pending during mmap_write_lock_killable")
+		KAPI_SIGNAL_DESC("Fatal signals (SIGKILL, SIGTERM, etc.) can interrupt the operation when acquiring mmap_write_lock_killable(), causing -EINTR return")
+		KAPI_SIGNAL_RESTARTABLE
+	KAPI_SIGNAL_END
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE,
+			 "all process memory",
+			 "Unlocks all pages, making entire address space swappable")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("Process had locked pages")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE,
+			 "mm->def_flags",
+			 "Clears VM_LOCKED from default flags for future mappings")
+		KAPI_EFFECT_REVERSIBLE
+		KAPI_EFFECT_CONDITION("MCL_FUTURE was previously set")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_MODIFY_STATE,
+			 "mm->locked_vm",
+			 "Resets process locked memory counter to zero")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_MODIFY_STATE,
+			 "all VMA flags",
+			 "Clears VM_LOCKED and VM_LOCKONFAULT from all VMAs")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(4, KAPI_EFFECT_MODIFY_STATE,
+			 "page flags",
+			 "Clears PG_mlocked flag from all locked pages")
+		KAPI_EFFECT_CONDITION("Pages had PG_mlocked set")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(5, KAPI_EFFECT_MODIFY_STATE,
+			 "LRU lists",
+			 "Moves all pages from unevictable to normal LRU lists")
+		KAPI_EFFECT_CONDITION("Pages were on unevictable list")
+	KAPI_SIDE_EFFECT_END
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "all memory pages",
+			 "locked in RAM", "swappable",
+			 "All pages in process become eligible for swap out")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "future mappings",
+			 "auto-locked", "normal",
+			 "New mappings will no longer be automatically locked")
+		KAPI_STATE_TRANS_COND("MCL_FUTURE was set")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "all VMA flags",
+			 "VM_LOCKED set", "VM_LOCKED cleared",
+			 "All virtual memory areas no longer marked as locked")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(3, "process statistics",
+			 "all memory locked", "no memory locked",
+			 "Entire locked memory accounting reset to zero")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(4, "page LRU status",
+			 "unevictable list", "active/inactive list",
+			 "All pages moved to normal LRU lists for reclaim")
+		KAPI_STATE_TRANS_COND("Pages were mlocked")
+	KAPI_STATE_TRANS_END
+
+	/* Locking information */
+	KAPI_LOCK(0, "mmap_lock", KAPI_LOCK_RWLOCK)
+		KAPI_LOCK_DESC("Process memory map write lock")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Protects VMA modifications during munlockall operation")
+	KAPI_LOCK_END
+
+	KAPI_LOCK(1, "lru_lock", KAPI_LOCK_SPINLOCK)
+		KAPI_LOCK_DESC("Per-memcg LRU list lock")
+		KAPI_LOCK_ACQUIRED
+		KAPI_LOCK_RELEASED
+		KAPI_LOCK_DESC("Taken when moving all pages from unevictable to normal LRU lists")
+	KAPI_LOCK_END
+
+	.error_count = 2,
+	.since_version = "2.0",
+	.signal_count = 1,
+	.side_effect_count = 6,
+	.state_trans_count = 5,
+	.lock_count = 2,
+	.examples = "munlockall();  // Unlock all pages",
+	.notes = "Clears VM_LOCKED and VM_LOCKONFAULT from all VMAs and mm->def_flags",
+KAPI_END_SPEC;
+
 SYSCALL_DEFINE0(munlockall)
 {
 	int ret;
Signature · 1 line
2.39.5
#19 lore raw

RFC 15/19 kernel/api: add debugfs interface for kernel API specifications

In reply to Sasha Levin

Add a debugfs interface to expose kernel API specifications at runtime. This allows tools and users to query the complete API specifications through the debugfs filesystem.

The interface provides:
- /sys/kernel/debug/kapi/list - lists all available API specifications
- /sys/kernel/debug/kapi/specs/<name> - detailed info for each API

Each specification file includes:
- Function name, version, and descriptions
- Execution context requirements and flags
- Parameter details with types, flags, and constraints
- Return value specifications and success conditions
- Error codes with descriptions and conditions
- Locking requirements and constraints
- Signal handling specifications
- Examples, notes, and deprecation status

This enables runtime introspection of kernel APIs for documentation tools, static analyzers, and debugging purposes.

---
 kernel/api/Kconfig        |  20 +++
 kernel/api/Makefile       |   5 +-
 kernel/api/kapi_debugfs.c | 340 ++++++++++++++++++++++++++++++++++++++
 3 files changed, 364 insertions(+), 1 deletion(-)
 create mode 100644 kernel/api/kapi_debugfs.c
kernel/api/Kconfig +20 -0
index fde25ec70e134..d2754b21acc43 100644
@@ -33,3 +33,23 @@ config KAPI_RUNTIME_CHECKS
 	  development. The checks use WARN_ONCE to report violations.
 
 	  If unsure, say N.
+
+config KAPI_SPEC_DEBUGFS
+	bool "Export kernel API specifications via debugfs"
+	depends on KAPI_SPEC
+	depends on DEBUG_FS
+	help
+	  This option enables exporting kernel API specifications through
+	  the debugfs filesystem. When enabled, specifications can be
+	  accessed at /sys/kernel/debug/kapi/.
+
+	  The debugfs interface provides:
+	  - A list of all available API specifications
+	  - Detailed information for each API including parameters,
+	    return values, errors, locking requirements, and constraints
+	  - Complete machine-readable representation of the specs
+
+	  This is useful for documentation tools, static analyzers, and
+	  runtime introspection of kernel APIs.
+
+	  If unsure, say N.
kernel/api/Makefile +4 -1
index 4120ded7e5cf1..07b8c007ec156 100644
@@ -4,4 +4,7 @@
 #
 
 # Core API specification framework
-obj-$(CONFIG_KAPI_SPEC)		+= kernel_api_spec.o
\ No newline at end of file
+obj-$(CONFIG_KAPI_SPEC)		+= kernel_api_spec.o
+
+# Debugfs interface for kernel API specs
+obj-$(CONFIG_KAPI_SPEC_DEBUGFS)	+= kapi_debugfs.o
\ No newline at end of file
kernel/api/kapi_debugfs.c new file +340 -0

341 lines not on this page · raw message

Signature · 1 line
2.39.5
#20 lore raw

RFC 16/19 kernel/api: add IOCTL specification infrastructure

In reply to Sasha Levin

Add IOCTL API specification support to the kernel API specification framework. This enables detailed documentation and runtime validation of IOCTL interfaces.

Key features:
- IOCTL specification structure with command info and parameter details
- Registration/unregistration functions for IOCTL specs
- Helper macros for defining IOCTL specifications
- KAPI_IOCTL_SPEC_DRIVER macro for simplified driver integration
- Runtime validation support with KAPI_DEFINE_FOPS wrapper
- Validation of IOCTL parameters and return values
- Integration with existing kernel API spec infrastructure

The validation framework checks:
- Parameter constraints (ranges, enums, masks)
- User pointer validity
- Buffer size constraints
- Return value correctness against specification

---
 include/linux/ioctl_api_spec.h  | 540 ++++++++++++++++++++++++++++++++
 include/linux/kernel_api_spec.h |   2 +-
 kernel/api/Makefile             |   5 +-
 kernel/api/ioctl_validation.c   | 360 +++++++++++++++++++++
 kernel/api/kernel_api_spec.c    |  90 +++++-
 5 files changed, 994 insertions(+), 3 deletions(-)
 create mode 100644 include/linux/ioctl_api_spec.h
 create mode 100644 kernel/api/ioctl_validation.c
include/linux/ioctl_api_spec.h new file +540 -0
new file mode 100644
index 0000000000000..ab3337449ad77
@@ -0,0 +1,540 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * ioctl_api_spec.h - IOCTL API specification framework
+ *
+ * Extends the kernel API specification framework to support ioctl validation
+ * and documentation.
+ */
+
+#ifndef _LINUX_IOCTL_API_SPEC_H
+#define _LINUX_IOCTL_API_SPEC_H
+
+#include <linux/kernel_api_spec.h>
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+/* Forward declarations */
+struct file;
+
+/**
+ * struct kapi_ioctl_spec - IOCTL-specific API specification
+ * @api_spec: Base API specification
+ * @cmd: IOCTL command number
+ * @cmd_name: Human-readable command name
+ * @input_size: Size of input structure (0 if none)
+ * @output_size: Size of output structure (0 if none)
+ * @file_ops_name: Name of the file_operations structure
+ */
+struct kapi_ioctl_spec {
+	struct kernel_api_spec api_spec;
+	unsigned int cmd;
+	const char *cmd_name;
+	size_t input_size;
+	size_t output_size;
+	const char *file_ops_name;
+};
+
+/* Registry functions for IOCTL specifications */
+#ifdef CONFIG_KAPI_SPEC
+int kapi_register_ioctl_spec(const struct kapi_ioctl_spec *spec);
+void kapi_unregister_ioctl_spec(unsigned int cmd);
+const struct kapi_ioctl_spec *kapi_get_ioctl_spec(unsigned int cmd);
+
+/* IOCTL validation functions */
+#ifdef CONFIG_KAPI_RUNTIME_CHECKS
+int kapi_validate_ioctl(struct file *filp, unsigned int cmd, void __user *arg);
+int kapi_validate_ioctl_struct(const struct kapi_ioctl_spec *spec,
+			       const void *data, size_t size);
+#else
+static inline int kapi_validate_ioctl(struct file *filp, unsigned int cmd,
+				      void __user *arg)
+{
+	return 0;
+}
+#endif /* CONFIG_KAPI_RUNTIME_CHECKS */
+
+#else /* !CONFIG_KAPI_SPEC */
+static inline int kapi_register_ioctl_spec(const struct kapi_ioctl_spec *spec)
+{
+	return 0;
+}
+static inline void kapi_unregister_ioctl_spec(unsigned int cmd) {}
+static inline const struct kapi_ioctl_spec *kapi_get_ioctl_spec(unsigned int cmd)
+{
+	return NULL;
+}
+#endif /* CONFIG_KAPI_SPEC */
+
+/* Helper macros for IOCTL specification */
+
+/**
+ * DEFINE_IOCTL_API_SPEC - Start an IOCTL API specification
+ * @name: Unique identifier for the specification
+ * @cmd: IOCTL command number
+ * @cmd_name_str: String name of the command
+ */
+#define DEFINE_IOCTL_API_SPEC(name, cmd, cmd_name_str)			\
+static const struct kapi_ioctl_spec name##_spec = {			\
+	.cmd = cmd,							\
+	.cmd_name = cmd_name_str,					\
+	.api_spec = {							\
+		.name = #name,
+
+/**
+ * KAPI_IOCTL_SIZE - Specify input/output structure sizes
+ * @in_size: Size of input structure
+ * @out_size: Size of output structure
+ */
+#define KAPI_IOCTL_SIZE(in_size, out_size)				\
+	},								\
+	.input_size = in_size,						\
+	.output_size = out_size,
+
+/**
+ * KAPI_IOCTL_FILE_OPS - Specify the file_operations structure name
+ * @ops_name: Name of the file_operations structure
+ */
+#define KAPI_IOCTL_FILE_OPS(ops_name)					\
+	.file_ops_name = #ops_name,
+
+/**
+ * Common IOCTL parameter specifications
+ */
+#define KAPI_IOCTL_PARAM_SIZE							\
+	KAPI_PARAM(0, "size", "__u32", "Size of the structure")		\
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)					\
+		.type = KAPI_TYPE_UINT,						\
+		.constraint_type = KAPI_CONSTRAINT_CUSTOM,			\
+		.constraints = "Must match sizeof(struct)",			\
+	KAPI_PARAM_END
+
+#define KAPI_IOCTL_PARAM_FLAGS							\
+	KAPI_PARAM(1, "flags", "__u32", "Feature flags")			\
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)					\
+		.type = KAPI_TYPE_UINT,						\
+		.constraint_type = KAPI_CONSTRAINT_MASK,			\
+		.valid_mask = 0,	/* 0 means no flags currently */	\
+	KAPI_PARAM_END
+
+/**
+ * KAPI_IOCTL_PARAM_USER_BUF - User buffer parameter
+ * @idx: Parameter index
+ * @name: Parameter name
+ * @desc: Parameter description
+ * @len_idx: Index of the length parameter
+ */
+#define KAPI_IOCTL_PARAM_USER_BUF(idx, name, desc, len_idx)		\
+	KAPI_PARAM(idx, name, "__aligned_u64", desc)			\
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER_PTR)	\
+		.type = KAPI_TYPE_USER_PTR,				\
+		.size_param_idx = len_idx,				\
+	KAPI_PARAM_END
+
+/**
+ * KAPI_IOCTL_PARAM_USER_OUT_BUF - User output buffer parameter
+ * @idx: Parameter index
+ * @name: Parameter name
+ * @desc: Parameter description
+ * @len_idx: Index of the length parameter
+ */
+#define KAPI_IOCTL_PARAM_USER_OUT_BUF(idx, name, desc, len_idx)	\
+	KAPI_PARAM(idx, name, "__aligned_u64", desc)			\
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT | KAPI_PARAM_USER_PTR)	\
+		.type = KAPI_TYPE_USER_PTR,				\
+		.size_param_idx = len_idx,				\
+	KAPI_PARAM_END
+
+/**
+ * KAPI_IOCTL_PARAM_LEN - Buffer length parameter
+ * @idx: Parameter index
+ * @name: Parameter name
+ * @desc: Parameter description
+ * @max_size: Maximum allowed size
+ */
+#define KAPI_IOCTL_PARAM_LEN(idx, name, desc, max_size)		\
+	KAPI_PARAM(idx, name, "__u32", desc)				\
+		KAPI_PARAM_FLAGS(KAPI_PARAM_INOUT)			\
+		.type = KAPI_TYPE_UINT,					\
+		.constraint_type = KAPI_CONSTRAINT_RANGE,		\
+		.min_value = 0,						\
+		.max_value = max_size,					\
+	KAPI_PARAM_END
+
+/* End the IOCTL specification */
+#define KAPI_IOCTL_END_SPEC						\
+};									\
+									\
+static int __init name##_spec_init(void)				\
+{									\
+	return kapi_register_ioctl_spec(&name##_spec);			\
+}									\
+									\
+static void __exit name##_spec_exit(void)				\
+{									\
+	kapi_unregister_ioctl_spec(name##_spec.cmd);			\
+}									\
+									\
+module_init(name##_spec_init);						\
+module_exit(name##_spec_exit);
+
+/* Inline IOCTL specification support */
+
+/* Forward declaration */
+struct fwctl_ucmd;
+
+/**
+ * struct kapi_ioctl_handler - IOCTL handler with inline specification
+ * @spec: IOCTL specification
+ * @handler: Original IOCTL handler function
+ */
+struct kapi_ioctl_handler {
+	struct kapi_ioctl_spec spec;
+	int (*handler)(struct fwctl_ucmd *ucmd);
+};
+
+/**
+ * DEFINE_IOCTL_HANDLER - Define an IOCTL handler with inline specification
+ * @name: Handler name
+ * @cmd: IOCTL command number
+ * @handler_func: Handler function
+ * @struct_type: Structure type for this IOCTL
+ * @last_field: Last field in the structure
+ */
+#define DEFINE_IOCTL_HANDLER(name, cmd, handler_func, struct_type, last_field)	\
+static const struct kapi_ioctl_handler name = {				\
+	.spec = {							\
+		.cmd = cmd,						\
+		.cmd_name = #cmd,					\
+		.input_size = sizeof(struct_type),			\
+		.output_size = sizeof(struct_type),			\
+		.api_spec = {						\
+			.name = #name,
+
+#define KAPI_IOCTL_HANDLER_END						\
+		},							\
+	},								\
+	.handler = handler_func,					\
+}
+
+/**
+ * kapi_ioctl_wrapper - Wrapper function for transparent IOCTL validation
+ * @filp: File pointer
+ * @cmd: IOCTL command
+ * @arg: User argument
+ * @real_ioctl: The real ioctl handler
+ *
+ * This wrapper performs validation before and after the actual IOCTL call
+ */
+static inline long kapi_ioctl_wrapper(struct file *filp, unsigned int cmd,
+				      unsigned long arg,
+				      long (*real_ioctl)(struct file *, unsigned int, unsigned long))
+{
+	long ret;
+
+#ifdef CONFIG_KAPI_RUNTIME_CHECKS
+	/* Pre-validation */
+	ret = kapi_validate_ioctl(filp, cmd, (void __user *)arg);
+	if (ret)
+		return ret;
+#endif
+
+	/* Call the real IOCTL handler */
+	ret = real_ioctl(filp, cmd, arg);
+
+#ifdef CONFIG_KAPI_RUNTIME_CHECKS
+	/* Post-validation could be added here if needed */
+	/* For example, validating output parameters */
+#endif
+
+	return ret;
+}
+
+/**
+ * KAPI_IOCTL_OPS - Define file_operations with transparent validation
+ * @name: Name of the file_operations structure
+ * @real_ioctl: The real ioctl handler function
+ * @... : Other file operation handlers
+ */
+#define KAPI_IOCTL_OPS(name, real_ioctl, ...)				\
+static long name##_validated_ioctl(struct file *filp, unsigned int cmd, \
+				   unsigned long arg)			\
+{									\
+	return kapi_ioctl_wrapper(filp, cmd, arg, real_ioctl);		\
+}									\
+									\
+static const struct file_operations name = {				\
+	.unlocked_ioctl = name##_validated_ioctl,			\
+	__VA_ARGS__							\
+}
+
+/**
+ * KAPI_IOCTL_OP_ENTRY - Define an IOCTL operation table entry with spec
+ * @_ioctl: IOCTL command macro
+ * @_handler: Handler structure (defined with DEFINE_IOCTL_HANDLER)
+ * @_struct: Structure type
+ * @_last: Last field name
+ */
+#define KAPI_IOCTL_OP_ENTRY(_ioctl, _handler, _struct, _last)		\
+	[_IOC_NR(_ioctl) - FWCTL_CMD_BASE] = {				\
+		.size = sizeof(_struct) +				\
+			BUILD_BUG_ON_ZERO(sizeof(union fwctl_ucmd_buffer) < \
+					  sizeof(_struct)),		\
+		.min_size = offsetofend(_struct, _last),		\
+		.ioctl_num = _ioctl,					\
+		.execute = _handler.handler,				\
+	}
+
+/* Helper to register all handlers in a module */
+#define KAPI_REGISTER_IOCTL_HANDLERS(handlers, count)			\
+static int __init kapi_ioctl_handlers_init(void)			\
+{									\
+	int i, ret;							\
+	for (i = 0; i < count; i++) {					\
+		ret = kapi_register_ioctl_spec(&handlers[i].spec);	\
+		if (ret) {						\
+			while (--i >= 0)				\
+				kapi_unregister_ioctl_spec(handlers[i].spec.cmd); \
+			return ret;					\
+		}							\
+	}								\
+	return 0;							\
+}									\
+									\
+static void __exit kapi_ioctl_handlers_exit(void)			\
+{									\
+	int i;								\
+	for (i = 0; i < count; i++)					\
+		kapi_unregister_ioctl_spec(handlers[i].spec.cmd);	\
+}									\
+									\
+module_init(kapi_ioctl_handlers_init);					\
+module_exit(kapi_ioctl_handlers_exit)
+
+/**
+ * KAPI_REGISTER_IOCTL_SPECS - Register an array of IOCTL specifications
+ * @specs: Array of pointers to kapi_ioctl_spec
+ * @count: Number of specifications
+ *
+ * This macro generates init/exit functions to register/unregister
+ * the IOCTL specifications. The functions return 0 on success or
+ * negative error code on failure.
+ *
+ * Usage:
+ *   static const struct kapi_ioctl_spec *my_ioctl_specs[] = {
+ *       &spec1, &spec2, &spec3,
+ *   };
+ *   KAPI_REGISTER_IOCTL_SPECS(my_ioctl_specs, ARRAY_SIZE(my_ioctl_specs))
+ *
+ * Then call the generated functions in your module init/exit:
+ *   ret = kapi_register_##name();
+ *   kapi_unregister_##name();
+ */
+#define KAPI_REGISTER_IOCTL_SPECS(name, specs)				\
+static int kapi_register_##name(void)					\
+{									\
+	int i, ret;							\
+	for (i = 0; i < ARRAY_SIZE(specs); i++) {			\
+		ret = kapi_register_ioctl_spec(specs[i]);		\
+		if (ret) {						\
+			pr_warn("Failed to register IOCTL spec for %s: %d\n", \
+				specs[i]->cmd_name, ret);		\
+			while (--i >= 0)				\
+				kapi_unregister_ioctl_spec(specs[i]->cmd); \
+			return ret;					\
+		}							\
+	}								\
+	pr_info("Registered %zu IOCTL specifications\n", 		\
+		ARRAY_SIZE(specs));					\
+	return 0;							\
+}									\
+									\
+static void kapi_unregister_##name(void)				\
+{									\
+	int i;								\
+	for (i = 0; i < ARRAY_SIZE(specs); i++)			\
+		kapi_unregister_ioctl_spec(specs[i]->cmd);		\
+}
+
+/**
+ * KAPI_DEFINE_IOCTL_SPEC - Define a single IOCTL specification
+ * @name: Name of the specification variable
+ * @cmd: IOCTL command number
+ * @cmd_name: String name of the command
+ * @in_size: Input structure size
+ * @out_size: Output structure size
+ * @fops_name: Name of the file_operations structure
+ *
+ * This macro starts the definition of an IOCTL specification.
+ * It must be followed by the API specification details and
+ * ended with KAPI_END_IOCTL_SPEC.
+ *
+ * Example:
+ *   KAPI_DEFINE_IOCTL_SPEC(my_ioctl_spec, MY_IOCTL, "MY_IOCTL",
+ *                          sizeof(struct my_input), sizeof(struct my_output),
+ *                          "my_fops")
+ *   KAPI_DESCRIPTION("Description here")
+ *   ...
+ *   KAPI_END_IOCTL_SPEC;
+ */
+#define KAPI_DEFINE_IOCTL_SPEC(name, cmd, cmd_name_str, in_size, out_size, fops) \
+static const struct kapi_ioctl_spec name = {				\
+	.cmd = (cmd),							\
+	.cmd_name = cmd_name_str,					\
+	.input_size = in_size,						\
+	.output_size = out_size,					\
+	.file_ops_name = fops,						\
+	.api_spec = {							\
+		.name = #name,
+
+#define KAPI_END_IOCTL_SPEC						\
+	},								\
+}
+
+/**
+ * KAPI_IOCTL_SPEC_DRIVER - Complete IOCTL specification for a driver
+ * @driver_name: Name of the driver (used for logging)
+ * @specs_array: Name of the array containing IOCTL spec pointers
+ *
+ * This macro provides everything needed for IOCTL spec registration:
+ * 1. Generates the specs array declaration
+ * 2. Creates init/exit functions for registration
+ * 3. Provides simple function names to call from module init/exit
+ *
+ * Usage:
+ *   // Define individual specs
+ *   KAPI_DEFINE_IOCTL_SPEC(spec1, ...) ... KAPI_END_IOCTL_SPEC;
+ *   KAPI_DEFINE_IOCTL_SPEC(spec2, ...) ... KAPI_END_IOCTL_SPEC;
+ *
+ *   // Create the driver registration (at end of file)
+ *   KAPI_IOCTL_SPEC_DRIVER("my_driver", {
+ *       &spec1,
+ *       &spec2,
+ *   })
+ *
+ *   // In module init: ret = kapi_ioctl_specs_init();
+ *   // In module exit: kapi_ioctl_specs_exit();
+ */
+#define KAPI_IOCTL_SPEC_DRIVER(driver_name, ...)			\
+static const struct kapi_ioctl_spec *__kapi_ioctl_specs[] = __VA_ARGS__;									\
+									\
+static int __init kapi_ioctl_specs_init(void)				\
+{									\
+	int i, ret;							\
+	for (i = 0; i < ARRAY_SIZE(__kapi_ioctl_specs); i++) {		\
+		ret = kapi_register_ioctl_spec(__kapi_ioctl_specs[i]);	\
+		if (ret) {						\
+			pr_warn("%s: Failed to register %s: %d\n",	\
+				driver_name,				\
+				__kapi_ioctl_specs[i]->cmd_name, ret);	\
+			while (--i >= 0)				\
+				kapi_unregister_ioctl_spec(		\
+					__kapi_ioctl_specs[i]->cmd);	\
+			return ret;					\
+		}							\
+	}								\
+	pr_info("%s: Registered %zu IOCTL specifications\n",		\
+		driver_name, ARRAY_SIZE(__kapi_ioctl_specs));		\
+	return 0;							\
+}									\
+									\
+static void kapi_ioctl_specs_exit(void)				\
+{									\
+	int i;								\
+	for (i = 0; i < ARRAY_SIZE(__kapi_ioctl_specs); i++)		\
+		kapi_unregister_ioctl_spec(__kapi_ioctl_specs[i]->cmd);\
+}
+
+/* Transparent IOCTL validation wrapper support */
+
+#ifdef CONFIG_KAPI_RUNTIME_CHECKS
+
+/**
+ * struct kapi_fops_wrapper - Wrapper for file_operations with validation
+ * @real_fops: Original file_operations
+ * @wrapped_fops: Modified file_operations with validation wrapper
+ * @real_ioctl: Original unlocked_ioctl handler
+ */
+struct kapi_fops_wrapper {
+	const struct file_operations *real_fops;
+	const struct file_operations *wrapped_fops;
+	long (*real_ioctl)(struct file *, unsigned int, unsigned long);
+};
+
+/* Forward declarations */
+long kapi_ioctl_validation_wrapper(struct file *filp, unsigned int cmd,
+				   unsigned long arg);
+void kapi_register_wrapper(struct kapi_fops_wrapper *wrapper);
+
+/**
+ * kapi_wrap_file_operations - Wrap file_operations for transparent validation
+ * @fops: Original file_operations to wrap
+ *
+ * This creates a wrapper that intercepts ioctl calls for validation.
+ * The wrapper is stored in a static variable in the calling module.
+ */
+#define kapi_wrap_file_operations(fops)					\
+({										\
+	static struct kapi_fops_wrapper __kapi_wrapper = {		\
+		.real_fops = &(fops),					\
+	};								\
+	if (__kapi_wrapper.real_fops->unlocked_ioctl) {		\
+		__kapi_wrapper.wrapped_fops = (fops);			\
+		__kapi_wrapper.real_ioctl = (fops).unlocked_ioctl;	\
+		__kapi_wrapper.wrapped_fops.unlocked_ioctl = 		\
+			kapi_ioctl_validation_wrapper;			\
+		&__kapi_wrapper.wrapped_fops;				\
+	} else {							\
+		&(fops);						\
+	}								\
+})
+
+
+/**
+ * KAPI_DEFINE_FOPS - Define file_operations with automatic validation
+ * @name: Name of the file_operations structure
+ * @... : File operation handlers
+ *
+ * Usage:
+ *   KAPI_DEFINE_FOPS(my_fops,
+ *       .owner = THIS_MODULE,
+ *       .open = my_open,
+ *       .unlocked_ioctl = my_ioctl,
+ *   );
+ *
+ * Then in your module init, call: kapi_init_fops_##name()
+ */
+#define KAPI_DEFINE_FOPS(name, ...)					\
+static const struct file_operations __kapi_real_##name = {		\
+	__VA_ARGS__							\
+};									\
+static struct file_operations __kapi_wrapped_##name;			\
+static struct kapi_fops_wrapper __kapi_wrapper_##name;			\
+static const struct file_operations *name;				\
+static void kapi_init_fops_##name(void)				\
+{									\
+	if (__kapi_real_##name.unlocked_ioctl) {			\
+		__kapi_wrapped_##name = __kapi_real_##name;		\
+		__kapi_wrapper_##name.real_fops = &__kapi_real_##name;	\
+		__kapi_wrapper_##name.wrapped_fops = &__kapi_wrapped_##name; \
+		__kapi_wrapper_##name.real_ioctl = 			\
+			__kapi_real_##name.unlocked_ioctl;		\
+		__kapi_wrapped_##name.unlocked_ioctl = 		\
+			kapi_ioctl_validation_wrapper;			\
+		kapi_register_wrapper(&__kapi_wrapper_##name);		\
+		name = &__kapi_wrapped_##name;				\
+	} else {							\
+		name = &__kapi_real_##name;				\
+	}								\
+}
+
+#else /* !CONFIG_KAPI_RUNTIME_CHECKS */
+
+/* When runtime checks are disabled, no wrapping occurs */
+#define kapi_wrap_file_operations(fops) (&(fops))
+#define KAPI_DEFINE_FOPS(name, ...) \
+static const struct file_operations name = { __VA_ARGS__ }; \
+static inline void kapi_init_fops_##name(void) {}
+
+#endif /* CONFIG_KAPI_RUNTIME_CHECKS */
+
+#endif /* _LINUX_IOCTL_API_SPEC_H */
\ No newline at end of file
include/linux/kernel_api_spec.h +1 -1
index 04df5892bc6d6..9590fe3bb007c 100644
@@ -849,7 +849,7 @@ struct kernel_api_spec {
 #define KAPI_PARAM_OUT		(KAPI_PARAM_OUT)
 #define KAPI_PARAM_INOUT	(KAPI_PARAM_IN | KAPI_PARAM_OUT)
 #define KAPI_PARAM_OPTIONAL	(KAPI_PARAM_OPTIONAL)
-#define KAPI_PARAM_USER_PTR	(KAPI_PARAM_USER | KAPI_PARAM_PTR)
+#define KAPI_PARAM_USER_PTR	(KAPI_PARAM_USER)
 
 /* Validation and runtime checking */
 
kernel/api/Makefile +4 -1
index 07b8c007ec156..9d2daf38f0029 100644
@@ -6,5 +6,8 @@
 # Core API specification framework
 obj-$(CONFIG_KAPI_SPEC)		+= kernel_api_spec.o
 
+# IOCTL validation framework
+obj-$(CONFIG_KAPI_SPEC)		+= ioctl_validation.o
+
 # Debugfs interface for kernel API specs
-obj-$(CONFIG_KAPI_SPEC_DEBUGFS)	+= kapi_debugfs.o
\ No newline at end of file
+obj-$(CONFIG_KAPI_SPEC_DEBUGFS)	+= kapi_debugfs.o
kernel/api/ioctl_validation.c new file +360 -0

360 lines not on this page · raw message

kernel/api/kernel_api_spec.c +89 -1

94 lines not on this page · raw message

Signature · 1 line
2.39.5
#21 lore raw

RFC 17/19 fwctl: add detailed IOCTL API specifications

In reply to Sasha Levin

Add kernel API specifications to the fwctl driver using the IOCTL specification framework. This provides detailed documentation and enables runtime validation of the fwctl IOCTL interface.

---
 drivers/fwctl/main.c | 295 ++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 293 insertions(+), 2 deletions(-)
drivers/fwctl/main.c +293 -2
index bc6378506296c..fc85d54ecb6a0 100644
@@ -10,6 +10,8 @@
 #include <linux/module.h>
 #include <linux/sizes.h>
 #include <linux/slab.h>
+#include <linux/ioctl_api_spec.h>
+#include <linux/kernel_api_spec.h>
 
 #include <uapi/fwctl/fwctl.h>
 
@@ -261,13 +263,291 @@ static int fwctl_fops_release(struct inode *inode, struct file *filp)
 	return 0;
 }
 
-static const struct file_operations fwctl_fops = {
+/* Use KAPI_DEFINE_FOPS for automatic validation wrapping */
+KAPI_DEFINE_FOPS(fwctl_fops,
 	.owner = THIS_MODULE,
 	.open = fwctl_fops_open,
 	.release = fwctl_fops_release,
 	.unlocked_ioctl = fwctl_fops_ioctl,
+);
+
+/* IOCTL API Specifications */
+
+static const struct kapi_ioctl_spec fwctl_info_spec = {
+	.cmd = FWCTL_INFO,
+	.cmd_name = "FWCTL_INFO",
+	.input_size = sizeof(struct fwctl_info),
+	.output_size = sizeof(struct fwctl_info),
+	.file_ops_name = "fwctl_fops",
+	.api_spec = {
+		.name = "fwctl_info",
+	KAPI_DESCRIPTION("Query device information and capabilities")
+	KAPI_LONG_DESC("Returns basic information about the fwctl instance, "
+		       "including the device type and driver-specific data. "
+		       "The driver-specific data format depends on the device type.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_IOCTL_PARAM_SIZE
+	KAPI_IOCTL_PARAM_FLAGS
+
+	KAPI_PARAM(2, "out_device_type", "__u32", "Device type from enum fwctl_device_type")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_ENUM,
+		.enum_values = (const s64[]){FWCTL_DEVICE_TYPE_ERROR,
+					     FWCTL_DEVICE_TYPE_MLX5,
+					     FWCTL_DEVICE_TYPE_CXL,
+					     FWCTL_DEVICE_TYPE_PDS},
+		.enum_count = 4,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(3, "device_data_len", "__u32", "Length of device data buffer")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_INOUT)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = SZ_1M,	/* Reasonable limit for device info */
+	KAPI_PARAM_END
+
+	KAPI_IOCTL_PARAM_USER_OUT_BUF(4, "out_device_data",
+				      "Driver-specific device data", 3)
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EFAULT, -EOPNOTSUPP, -ENODEV},
+		.error_count = 3,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EFAULT, "EFAULT", "Failed to copy data to/from user space",
+		   "Check that provided pointers are valid user space addresses")
+	KAPI_ERROR(1, -EOPNOTSUPP, "EOPNOTSUPP", "Invalid flags provided",
+		   "Currently flags must be 0")
+	KAPI_ERROR(2, -ENODEV, "ENODEV", "Device has been hot-unplugged",
+		   "The underlying device is no longer available")
+
+	.error_count = 3,
+	.param_count = 5,
+	.since_version = "6.13",
+
+	/* Structure specifications */
+	KAPI_STRUCT_SPEC(0, fwctl_info, "Device information query structure")
+		KAPI_STRUCT_SIZE(sizeof(struct fwctl_info), __alignof__(struct fwctl_info))
+		KAPI_STRUCT_FIELD_COUNT(4)
+
+		KAPI_STRUCT_FIELD(0, "size", KAPI_TYPE_UINT, "__u32",
+				  "Structure size for versioning")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_info, size))
+			KAPI_FIELD_SIZE(sizeof(__u32))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(1, "flags", KAPI_TYPE_UINT, "__u32",
+				  "Must be 0, reserved for future use")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_info, flags))
+			KAPI_FIELD_SIZE(sizeof(__u32))
+			KAPI_FIELD_CONSTRAINT_RANGE(0, 0)
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(2, "out_device_type", KAPI_TYPE_UINT, "__u32",
+				  "Device type identifier")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_info, out_device_type))
+			KAPI_FIELD_SIZE(sizeof(__u32))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(3, "device_data_len", KAPI_TYPE_UINT, "__u32",
+				  "Length of device-specific data")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_info, device_data_len))
+			KAPI_FIELD_SIZE(sizeof(__u32))
+		KAPI_STRUCT_FIELD_END
+	KAPI_STRUCT_SPEC_END
+
+	KAPI_STRUCT_SPEC_COUNT(1)
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_NONE,
+			 "none",
+			 "Read-only operation with no side effects")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(1)
+
+	/* State transitions */
+	KAPI_STATE_TRANS_COUNT(0)	/* No state transitions for query operation */
+	},
 };
 
+static const struct kapi_ioctl_spec fwctl_rpc_spec = {
+	.cmd = FWCTL_RPC,
+	.cmd_name = "FWCTL_RPC",
+	.input_size = sizeof(struct fwctl_rpc),
+	.output_size = sizeof(struct fwctl_rpc),
+	.file_ops_name = "fwctl_fops",
+	.api_spec = {
+		.name = "fwctl_rpc",
+	KAPI_DESCRIPTION("Execute a Remote Procedure Call to device firmware")
+	KAPI_LONG_DESC("Delivers an RPC to the device firmware and returns the response. "
+		       "The RPC format is device-specific and determined by out_device_type "
+		       "from FWCTL_INFO. Different scopes have different permission requirements.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_IOCTL_PARAM_SIZE
+
+	KAPI_PARAM(1, "scope", "__u32", "Access scope from enum fwctl_rpc_scope")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_ENUM,
+		.enum_values = (const s64[]){FWCTL_RPC_CONFIGURATION,
+					     FWCTL_RPC_DEBUG_READ_ONLY,
+					     FWCTL_RPC_DEBUG_WRITE,
+					     FWCTL_RPC_DEBUG_WRITE_FULL},
+		.enum_count = 4,
+		.constraints = "FWCTL_RPC_DEBUG_WRITE_FULL requires CAP_SYS_RAWIO",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "in_len", "__u32", "Length of input buffer")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = MAX_RPC_LEN,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(3, "out_len", "__u32", "Length of output buffer")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_INOUT)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = MAX_RPC_LEN,
+	KAPI_PARAM_END
+
+	KAPI_IOCTL_PARAM_USER_BUF(4, "in", "RPC request in device-specific format", 2)
+	KAPI_IOCTL_PARAM_USER_OUT_BUF(5, "out", "RPC response in device-specific format", 3)
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EMSGSIZE, -EOPNOTSUPP, -EPERM,
+					      -ENOMEM, -EFAULT, -ENODEV},
+		.error_count = 6,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EMSGSIZE, "EMSGSIZE", "RPC message too large",
+		   "in_len or out_len exceeds MAX_RPC_LEN (2MB)")
+	KAPI_ERROR(1, -EOPNOTSUPP, "EOPNOTSUPP", "Invalid scope value",
+		   "scope must be one of the defined fwctl_rpc_scope values")
+	KAPI_ERROR(2, -EPERM, "EPERM", "Insufficient permissions",
+		   "FWCTL_RPC_DEBUG_WRITE_FULL requires CAP_SYS_RAWIO")
+	KAPI_ERROR(3, -ENOMEM, "ENOMEM", "Memory allocation failed",
+		   "Unable to allocate buffers for RPC")
+	KAPI_ERROR(4, -EFAULT, "EFAULT", "Failed to copy data to/from user space",
+		   "Check that provided pointers are valid user space addresses")
+	KAPI_ERROR(5, -ENODEV, "ENODEV", "Device has been hot-unplugged",
+		   "The underlying device is no longer available")
+
+	.error_count = 6,
+	.param_count = 6,
+	.since_version = "6.13",
+	.notes = "FWCTL_RPC_DEBUG_WRITE and FWCTL_RPC_DEBUG_WRITE_FULL will "
+		 "taint the kernel with TAINT_FWCTL on first use",
+
+	/* Structure specifications */
+	KAPI_STRUCT_SPEC(0, fwctl_rpc, "RPC request/response structure")
+		KAPI_STRUCT_SIZE(sizeof(struct fwctl_rpc), __alignof__(struct fwctl_rpc))
+		KAPI_STRUCT_FIELD_COUNT(6)
+
+		KAPI_STRUCT_FIELD(0, "size", KAPI_TYPE_UINT, "__u32",
+				  "Structure size for versioning")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_rpc, size))
+			KAPI_FIELD_SIZE(sizeof(__u32))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(1, "scope", KAPI_TYPE_UINT, "__u32",
+				  "Access scope level")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_rpc, scope))
+			KAPI_FIELD_SIZE(sizeof(__u32))
+			KAPI_FIELD_CONSTRAINT_ENUM((const s64[]){FWCTL_RPC_CONFIGURATION,
+								  FWCTL_RPC_DEBUG_READ_ONLY,
+								  FWCTL_RPC_DEBUG_WRITE,
+								  FWCTL_RPC_DEBUG_WRITE_FULL}, 4)
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(2, "in_len", KAPI_TYPE_UINT, "__u32",
+				  "Input data length")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_rpc, in_len))
+			KAPI_FIELD_SIZE(sizeof(__u32))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(3, "out_len", KAPI_TYPE_UINT, "__u32",
+				  "Output buffer length")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_rpc, out_len))
+			KAPI_FIELD_SIZE(sizeof(__u32))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(4, "in", KAPI_TYPE_PTR, "__aligned_u64",
+				  "Pointer to input data")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_rpc, in))
+			KAPI_FIELD_SIZE(sizeof(__aligned_u64))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(5, "out", KAPI_TYPE_PTR, "__aligned_u64",
+				  "Pointer to output buffer")
+			KAPI_FIELD_OFFSET(offsetof(struct fwctl_rpc, out))
+			KAPI_FIELD_SIZE(sizeof(__aligned_u64))
+		KAPI_STRUCT_FIELD_END
+	KAPI_STRUCT_SPEC_END
+
+	KAPI_STRUCT_SPEC_COUNT(1)
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_HARDWARE | KAPI_EFFECT_MODIFY_STATE,
+			 "device firmware",
+			 "May modify device configuration or firmware state")
+		KAPI_EFFECT_CONDITION("scope >= FWCTL_RPC_DEBUG_WRITE")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE,
+			 "kernel taint",
+			 "Taints kernel with TAINT_FWCTL on first debug write")
+		KAPI_EFFECT_CONDITION("scope >= FWCTL_RPC_DEBUG_WRITE && first use")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_SCHEDULE,
+			 "process",
+			 "May block while firmware processes the RPC")
+		KAPI_EFFECT_CONDITION("firmware operation takes time")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(3)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "device state",
+			 "current configuration", "modified configuration",
+			 "Device configuration changed by RPC command")
+		KAPI_STATE_TRANS_COND("RPC modifies device settings")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "kernel taint state",
+			 "untainted", "TAINT_FWCTL set",
+			 "Kernel marked as tainted due to firmware modification")
+		KAPI_STATE_TRANS_COND("First debug write operation")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(2)
+	},
+};
+
+/* Register all fwctl IOCTL specifications */
+KAPI_IOCTL_SPEC_DRIVER("fwctl", {
+	&fwctl_info_spec,
+	&fwctl_rpc_spec,
+})
+
 static void fwctl_device_release(struct device *device)
 {
 	struct fwctl_device *fwctl =
@@ -325,7 +605,7 @@ struct fwctl_device *_fwctl_alloc_device(struct device *parent,
 	if (!fwctl)
 		return NULL;
 
-	cdev_init(&fwctl->cdev, &fwctl_fops);
+	cdev_init(&fwctl->cdev, fwctl_fops);
 	/*
 	 * The driver module is protected by fwctl_register/unregister(),
 	 * unregister won't complete until we are done with the driver's module.
@@ -395,6 +675,9 @@ static int __init fwctl_init(void)
 {
 	int ret;
 
+	/* Initialize the wrapped file_operations */
+	kapi_init_fops_fwctl_fops();
+
 	ret = alloc_chrdev_region(&fwctl_dev, 0, FWCTL_MAX_DEVICES, "fwctl");
 	if (ret)
 		return ret;
@@ -402,8 +685,15 @@ static int __init fwctl_init(void)
 	ret = class_register(&fwctl_class);
 	if (ret)
 		goto err_chrdev;
+
+	ret = kapi_ioctl_specs_init();
+	if (ret)
+		goto err_class;
+
 	return 0;
 
+err_class:
+	class_unregister(&fwctl_class);
 err_chrdev:
 	unregister_chrdev_region(fwctl_dev, FWCTL_MAX_DEVICES);
 	return ret;
@@ -411,6 +701,7 @@ static int __init fwctl_init(void)
 
 static void __exit fwctl_exit(void)
 {
+	kapi_ioctl_specs_exit();
 	class_unregister(&fwctl_class);
 	unregister_chrdev_region(fwctl_dev, FWCTL_MAX_DEVICES);
 }
Signature · 1 line
2.39.5
#22 lore raw

RFC 18/19 binder: add detailed IOCTL API specifications

In reply to Sasha Levin

Add kernel API specifications to the binder driver using the IOCTL specification framework. This provides detailed documentation and enables runtime validation of all binder IOCTL interfaces.

---
 drivers/android/binder.c | 758 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 758 insertions(+)
drivers/android/binder.c +758 -0
index c463ca4a8fff8..975f07216724b 100644
@@ -67,6 +67,8 @@
 #include <linux/task_work.h>
 #include <linux/sizes.h>
 #include <linux/ktime.h>
+#include <linux/ioctl_api_spec.h>
+#include <linux/kernel_api_spec.h>
 
 #include <uapi/linux/android/binder.h>
 
@@ -6930,6 +6932,7 @@ static int transaction_log_show(struct seq_file *m, void *unused)
 	return 0;
 }
 
+/* Define the actual binder_fops structure */
 const struct file_operations binder_fops = {
 	.owner = THIS_MODULE,
 	.poll = binder_poll,
@@ -6941,6 +6944,751 @@ const struct file_operations binder_fops = {
 	.release = binder_release,
 };
 
+/* Define wrapper for KAPI validation */
+#ifdef CONFIG_KAPI_RUNTIME_CHECKS
+static struct file_operations __kapi_wrapped_binder_fops;
+static struct kapi_fops_wrapper __kapi_wrapper_binder_fops;
+
+static void kapi_init_fops_binder_fops(void)
+{
+	if (binder_fops.unlocked_ioctl) {
+		__kapi_wrapped_binder_fops = binder_fops;
+		__kapi_wrapper_binder_fops.real_fops = &binder_fops;
+		__kapi_wrapper_binder_fops.wrapped_fops = &__kapi_wrapped_binder_fops;
+		__kapi_wrapper_binder_fops.real_ioctl = binder_fops.unlocked_ioctl;
+		__kapi_wrapped_binder_fops.unlocked_ioctl = kapi_ioctl_validation_wrapper;
+		kapi_register_wrapper(&__kapi_wrapper_binder_fops);
+	}
+}
+#else
+static inline void kapi_init_fops_binder_fops(void) {}
+#endif
+
+/* IOCTL API Specifications for Binder */
+
+static const struct kapi_ioctl_spec binder_write_read_spec = {
+	.cmd = BINDER_WRITE_READ,
+	.cmd_name = "BINDER_WRITE_READ",
+	.input_size = sizeof(struct binder_write_read),
+	.output_size = sizeof(struct binder_write_read),
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_write_read",
+	KAPI_DESCRIPTION("Perform read/write operations on binder")
+	KAPI_LONG_DESC("Main workhorse of binder IPC. Allows writing commands to "
+		       "binder driver and reading responses. Commands are encoded "
+		       "in a special protocol format. Both read and write operations "
+		       "can be performed in a single ioctl call.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "write_size", "binder_size_t", "Bytes to write")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = SZ_4M,	/* Reasonable limit for IPC */
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "write_consumed", "binder_size_t", "Bytes consumed by driver")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = SZ_4M,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "write_buffer", "binder_uintptr_t", "User buffer with commands")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_USER_PTR,
+		.size_param_idx = 0,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(3, "read_size", "binder_size_t", "Bytes to read")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = SZ_4M,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(4, "read_consumed", "binder_size_t", "Bytes consumed by driver")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = SZ_4M,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(5, "read_buffer", "binder_uintptr_t", "User buffer for responses")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT | KAPI_PARAM_USER)
+		.type = KAPI_TYPE_USER_PTR,
+		.size_param_idx = 3,
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EFAULT, -EINVAL, -EAGAIN, -EINTR,
+					      -ENOMEM, -ECONNREFUSED},
+		.error_count = 6,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EFAULT, "EFAULT", "Failed to copy data to/from user space",
+		   "Check buffer pointers are valid user space addresses")
+	KAPI_ERROR(1, -EINVAL, "EINVAL", "Invalid parameters",
+		   "Buffer sizes or commands are invalid")
+	KAPI_ERROR(2, -EAGAIN, "EAGAIN", "Try again",
+		   "Non-blocking read with no data available")
+	KAPI_ERROR(3, -EINTR, "EINTR", "Interrupted by signal",
+		   "Operation interrupted, should be retried")
+	KAPI_ERROR(4, -ENOMEM, "ENOMEM", "Out of memory",
+		   "Unable to allocate memory for operation")
+	KAPI_ERROR(5, -ECONNREFUSED, "ECONNREFUSED", "Connection refused",
+		   "Process is being destroyed, no further operations allowed")
+
+	.error_count = 6,
+	.param_count = 6,
+	.since_version = "3.0",
+	.notes = "This is the primary interface for binder IPC. Most other "
+		 "ioctls are for configuration and management.",
+
+	/* Structure specifications */
+	KAPI_STRUCT_SPEC(0, binder_write_read, "Read/write operation structure")
+		KAPI_STRUCT_SIZE(sizeof(struct binder_write_read), __alignof__(struct binder_write_read))
+		KAPI_STRUCT_FIELD_COUNT(6)
+
+		KAPI_STRUCT_FIELD(0, "write_size", KAPI_TYPE_UINT, "binder_size_t",
+				  "Number of bytes to write")
+			KAPI_FIELD_OFFSET(offsetof(struct binder_write_read, write_size))
+			KAPI_FIELD_SIZE(sizeof(binder_size_t))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(1, "write_consumed", KAPI_TYPE_UINT, "binder_size_t",
+				  "Number of bytes consumed by driver")
+			KAPI_FIELD_OFFSET(offsetof(struct binder_write_read, write_consumed))
+			KAPI_FIELD_SIZE(sizeof(binder_size_t))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(2, "write_buffer", KAPI_TYPE_PTR, "binder_uintptr_t",
+				  "Pointer to write buffer")
+			KAPI_FIELD_OFFSET(offsetof(struct binder_write_read, write_buffer))
+			KAPI_FIELD_SIZE(sizeof(binder_uintptr_t))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(3, "read_size", KAPI_TYPE_UINT, "binder_size_t",
+				  "Number of bytes to read")
+			KAPI_FIELD_OFFSET(offsetof(struct binder_write_read, read_size))
+			KAPI_FIELD_SIZE(sizeof(binder_size_t))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(4, "read_consumed", KAPI_TYPE_UINT, "binder_size_t",
+				  "Number of bytes consumed by driver")
+			KAPI_FIELD_OFFSET(offsetof(struct binder_write_read, read_consumed))
+			KAPI_FIELD_SIZE(sizeof(binder_size_t))
+		KAPI_STRUCT_FIELD_END
+
+		KAPI_STRUCT_FIELD(5, "read_buffer", KAPI_TYPE_PTR, "binder_uintptr_t",
+				  "Pointer to read buffer")
+			KAPI_FIELD_OFFSET(offsetof(struct binder_write_read, read_buffer))
+			KAPI_FIELD_SIZE(sizeof(binder_uintptr_t))
+		KAPI_STRUCT_FIELD_END
+	KAPI_STRUCT_SPEC_END
+
+	KAPI_STRUCT_SPEC_COUNT(1)
+
+	/* Side effects */
+	KAPI_SIDE_EFFECT(0, KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_NETWORK,
+			 "binder transaction queue",
+			 "Enqueues transactions or commands to target process")
+		KAPI_EFFECT_CONDITION("write_size > 0")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(1, KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_SCHEDULE,
+			 "process state",
+			 "May block waiting for incoming transactions")
+		KAPI_EFFECT_CONDITION("read_size > 0 && no data available")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(2, KAPI_EFFECT_RESOURCE_CREATE,
+			 "binder nodes/refs",
+			 "May create or destroy binder nodes and references")
+		KAPI_EFFECT_CONDITION("specific commands")
+		KAPI_EFFECT_REVERSIBLE
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT(3, KAPI_EFFECT_SIGNAL_SEND,
+			 "target process",
+			 "May trigger death notifications to linked processes")
+		KAPI_EFFECT_CONDITION("death notification")
+	KAPI_SIDE_EFFECT_END
+
+	KAPI_SIDE_EFFECT_COUNT(4)
+
+	/* State transitions */
+	KAPI_STATE_TRANS(0, "transaction",
+			 "pending in sender", "queued in target",
+			 "Transaction moves from sender to target's queue")
+		KAPI_STATE_TRANS_COND("BC_TRANSACTION command")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(1, "thread state",
+			 "running", "waiting for work",
+			 "Thread blocks waiting for incoming transactions")
+		KAPI_STATE_TRANS_COND("read with no work available")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS(2, "binder ref",
+			 "active", "released",
+			 "Reference count decremented, may trigger cleanup")
+		KAPI_STATE_TRANS_COND("BC_RELEASE command")
+	KAPI_STATE_TRANS_END
+
+	KAPI_STATE_TRANS_COUNT(3)
+	},
+};
+
+static const struct kapi_ioctl_spec binder_set_max_threads_spec = {
+	.cmd = BINDER_SET_MAX_THREADS,
+	.cmd_name = "BINDER_SET_MAX_THREADS",
+	.input_size = sizeof(__u32),
+	.output_size = 0,
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_set_max_threads",
+	KAPI_DESCRIPTION("Set maximum number of binder threads")
+	KAPI_LONG_DESC("Sets the maximum number of threads that the binder driver "
+		       "will request this process to spawn for handling incoming "
+		       "transactions. The driver sends BR_SPAWN_LOOPER when it needs "
+		       "more threads.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "max_threads", "__u32", "Maximum number of threads")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = INT_MAX,
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EINVAL, -EFAULT},
+		.error_count = 2,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "Invalid thread count",
+		   "Thread count exceeds system limits")
+	KAPI_ERROR(1, -EFAULT, "EFAULT", "Failed to copy from user",
+		   "Invalid user pointer provided")
+
+	.error_count = 2,
+	.param_count = 1,
+	.since_version = "3.0",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_set_context_mgr_spec = {
+	.cmd = BINDER_SET_CONTEXT_MGR,
+	.cmd_name = "BINDER_SET_CONTEXT_MGR",
+	.input_size = 0,
+	.output_size = 0,
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_set_context_mgr",
+	KAPI_DESCRIPTION("Become the context manager (handle 0)")
+	KAPI_LONG_DESC("Registers the calling process as the context manager for "
+		       "this binder domain. The context manager has special handle 0 "
+		       "and typically implements the service manager. Only one process "
+		       "per binder domain can be the context manager.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EBUSY, -EPERM, -ENOMEM},
+		.error_count = 3,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EBUSY, "EBUSY", "Context manager already set",
+		   "Another process is already the context manager")
+	KAPI_ERROR(1, -EPERM, "EPERM", "Permission denied",
+		   "Caller lacks permission or wrong UID")
+	KAPI_ERROR(2, -ENOMEM, "ENOMEM", "Out of memory",
+		   "Unable to allocate context manager node")
+
+	.error_count = 3,
+	.param_count = 0,
+	.since_version = "3.0",
+	.notes = "Requires CAP_SYS_NICE or proper SELinux permissions",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_set_context_mgr_ext_spec = {
+	.cmd = BINDER_SET_CONTEXT_MGR_EXT,
+	.cmd_name = "BINDER_SET_CONTEXT_MGR_EXT",
+	.input_size = sizeof(struct flat_binder_object),
+	.output_size = 0,
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_set_context_mgr_ext",
+	KAPI_DESCRIPTION("Become context manager with extended info")
+	KAPI_LONG_DESC("Extended version of BINDER_SET_CONTEXT_MGR that allows "
+		       "specifying additional properties of the context manager "
+		       "through a flat_binder_object structure.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "object", "struct flat_binder_object", "Context manager properties")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_STRUCT,
+		.size = sizeof(struct flat_binder_object),
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EINVAL, -EFAULT, -EBUSY, -EPERM, -ENOMEM},
+		.error_count = 5,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "Invalid parameters",
+		   "Invalid flat_binder_object structure")
+	KAPI_ERROR(1, -EFAULT, "EFAULT", "Failed to copy from user",
+		   "Invalid user pointer provided")
+	KAPI_ERROR(2, -EBUSY, "EBUSY", "Context manager already set",
+		   "Another process is already the context manager")
+	KAPI_ERROR(3, -EPERM, "EPERM", "Permission denied",
+		   "Caller lacks permission or wrong UID")
+	KAPI_ERROR(4, -ENOMEM, "ENOMEM", "Out of memory",
+		   "Unable to allocate context manager node")
+
+	.error_count = 5,
+	.param_count = 1,
+	.since_version = "4.14",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_thread_exit_spec = {
+	.cmd = BINDER_THREAD_EXIT,
+	.cmd_name = "BINDER_THREAD_EXIT",
+	.input_size = 0,
+	.output_size = 0,
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_thread_exit",
+	KAPI_DESCRIPTION("Exit binder thread")
+	KAPI_LONG_DESC("Notifies the binder driver that this thread is exiting. "
+		       "The driver will clean up any pending transactions and "
+		       "remove the thread from the thread pool.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){},
+		.error_count = 0,
+	KAPI_RETURN_END
+
+	.error_count = 0,
+	.param_count = 0,
+	.since_version = "3.0",
+	.notes = "Should be called before thread termination to ensure clean shutdown",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_version_spec = {
+	.cmd = BINDER_VERSION,
+	.cmd_name = "BINDER_VERSION",
+	.input_size = 0,
+	.output_size = sizeof(struct binder_version),
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_version",
+	KAPI_DESCRIPTION("Get binder protocol version")
+	KAPI_LONG_DESC("Returns the current binder protocol version supported "
+		       "by the driver. Used for compatibility checking.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "protocol_version", "__s32", "Binder protocol version")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_INT,
+		.constraint_type = KAPI_CONSTRAINT_ENUM,
+		.enum_values = (const s64[]){BINDER_CURRENT_PROTOCOL_VERSION},
+		.enum_count = 1,
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EINVAL, -EFAULT},
+		.error_count = 2,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "Invalid version structure",
+		   "Invalid user pointer for version structure")
+	KAPI_ERROR(1, -EFAULT, "EFAULT", "Failed to copy to user",
+		   "Unable to write version to user space")
+
+	.error_count = 2,
+	.param_count = 1,
+	.since_version = "3.0",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_get_node_info_for_ref_spec = {
+	.cmd = BINDER_GET_NODE_INFO_FOR_REF,
+	.cmd_name = "BINDER_GET_NODE_INFO_FOR_REF",
+	.input_size = sizeof(struct binder_node_info_for_ref),
+	.output_size = sizeof(struct binder_node_info_for_ref),
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_get_node_info_for_ref",
+	KAPI_DESCRIPTION("Get node information for a reference")
+	KAPI_LONG_DESC("Retrieves information about a binder node given its handle. "
+		       "Returns the current strong and weak reference counts.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "handle", "__u32", "Binder handle")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "strong_count", "__u32", "Strong reference count")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "weak_count", "__u32", "Weak reference count")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EINVAL, -EFAULT, -ENOENT},
+		.error_count = 3,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "Invalid parameters",
+		   "Reserved fields must be zero")
+	KAPI_ERROR(1, -EFAULT, "EFAULT", "Failed to copy data",
+		   "Invalid user pointer provided")
+	KAPI_ERROR(2, -ENOENT, "ENOENT", "Handle not found",
+		   "No node exists for the given handle")
+
+	.error_count = 3,
+	.param_count = 3,
+	.since_version = "4.14",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_get_node_debug_info_spec = {
+	.cmd = BINDER_GET_NODE_DEBUG_INFO,
+	.cmd_name = "BINDER_GET_NODE_DEBUG_INFO",
+	.input_size = sizeof(struct binder_node_debug_info),
+	.output_size = sizeof(struct binder_node_debug_info),
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_get_node_debug_info",
+	KAPI_DESCRIPTION("Get debug info for binder nodes")
+	KAPI_LONG_DESC("Iterates through all binder nodes in the process. "
+		       "Start with ptr=NULL to get first node, then use "
+		       "returned ptr for next call. Returns ptr=0 when done.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "ptr", "binder_uintptr_t", "Node pointer (NULL for first)")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_INOUT)
+		.type = KAPI_TYPE_PTR,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "cookie", "binder_uintptr_t", "Node cookie value")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "has_strong_ref", "__u32", "Has strong references")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = 1,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(3, "has_weak_ref", "__u32", "Has weak references")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = 1,
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EFAULT, -EINVAL},
+		.error_count = 2,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EFAULT, "EFAULT", "Failed to copy data",
+		   "Invalid user pointer provided")
+	KAPI_ERROR(1, -EINVAL, "EINVAL", "Invalid node pointer",
+		   "Provided ptr is not a valid node")
+
+	.error_count = 2,
+	.param_count = 4,
+	.since_version = "4.14",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_freeze_spec = {
+	.cmd = BINDER_FREEZE,
+	.cmd_name = "BINDER_FREEZE",
+	.input_size = sizeof(struct binder_freeze_info),
+	.output_size = 0,
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_freeze",
+	KAPI_DESCRIPTION("Freeze or unfreeze a binder process")
+	KAPI_LONG_DESC("Controls whether a process can receive binder transactions. "
+		       "When frozen, new transactions are blocked. Can wait for "
+		       "existing transactions to complete with timeout.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "pid", "__u32", "Process ID to freeze/unfreeze")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 1,
+		.max_value = PID_MAX_LIMIT,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "enable", "__u32", "1 to freeze, 0 to unfreeze")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = 1,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "timeout_ms", "__u32", "Timeout in milliseconds (0 = no wait)")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = 60000,	/* 1 minute max */
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EINVAL, -EAGAIN, -EFAULT, -ENOMEM},
+		.error_count = 4,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "Invalid process",
+		   "Process not found or invalid parameters")
+	KAPI_ERROR(1, -EAGAIN, "EAGAIN", "Timeout waiting for transactions",
+		   "Existing transactions did not complete within timeout")
+	KAPI_ERROR(2, -EFAULT, "EFAULT", "Failed to copy from user",
+		   "Invalid user pointer provided")
+	KAPI_ERROR(3, -ENOMEM, "ENOMEM", "Out of memory",
+		   "Unable to allocate memory for freeze operation")
+
+	.error_count = 4,
+	.param_count = 3,
+	.since_version = "5.9",
+	.notes = "Requires appropriate permissions to freeze other processes",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_get_frozen_info_spec = {
+	.cmd = BINDER_GET_FROZEN_INFO,
+	.cmd_name = "BINDER_GET_FROZEN_INFO",
+	.input_size = sizeof(struct binder_frozen_status_info),
+	.output_size = sizeof(struct binder_frozen_status_info),
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_get_frozen_info",
+	KAPI_DESCRIPTION("Get frozen status of a process")
+	KAPI_LONG_DESC("Queries whether a process is frozen and if it has "
+		       "received transactions while frozen. Useful for "
+		       "debugging frozen process issues.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "pid", "__u32", "Process ID to query")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 1,
+		.max_value = PID_MAX_LIMIT,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "sync_recv", "__u32", "Sync transactions received while frozen")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+		.constraints = "Bit 0: received after frozen, Bit 1: pending during freeze",
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "async_recv", "__u32", "Async transactions received while frozen")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EINVAL, -EFAULT},
+		.error_count = 2,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EINVAL, "EINVAL", "Process not found",
+		   "No binder process found with given PID")
+	KAPI_ERROR(1, -EFAULT, "EFAULT", "Failed to copy data",
+		   "Invalid user pointer provided")
+
+	.error_count = 2,
+	.param_count = 3,
+	.since_version = "5.9",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_enable_oneway_spam_detection_spec = {
+	.cmd = BINDER_ENABLE_ONEWAY_SPAM_DETECTION,
+	.cmd_name = "BINDER_ENABLE_ONEWAY_SPAM_DETECTION",
+	.input_size = sizeof(__u32),
+	.output_size = 0,
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_enable_oneway_spam_detection",
+	KAPI_DESCRIPTION("Enable/disable oneway spam detection")
+	KAPI_LONG_DESC("Controls whether the driver monitors for excessive "
+		       "oneway transactions that might indicate spam or abuse. "
+		       "When enabled, BR_ONEWAY_SPAM_SUSPECT is sent when threshold exceeded.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "enable", "__u32", "1 to enable, 0 to disable")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
+		.type = KAPI_TYPE_UINT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = 0,
+		.max_value = 1,
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EFAULT},
+		.error_count = 1,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EFAULT, "EFAULT", "Failed to copy from user",
+		   "Invalid user pointer provided")
+
+	.error_count = 1,
+	.param_count = 1,
+	.since_version = "5.13",
+	},
+};
+
+static const struct kapi_ioctl_spec binder_get_extended_error_spec = {
+	.cmd = BINDER_GET_EXTENDED_ERROR,
+	.cmd_name = "BINDER_GET_EXTENDED_ERROR",
+	.input_size = 0,
+	.output_size = sizeof(struct binder_extended_error),
+	.file_ops_name = "binder_fops",
+	.api_spec = {
+		.name = "binder_get_extended_error",
+	KAPI_DESCRIPTION("Get extended error information")
+	KAPI_LONG_DESC("Retrieves detailed error information from the last "
+		       "failed binder operation on this thread. Clears the "
+		       "error after reading.")
+	KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
+
+	/* Parameters */
+	KAPI_PARAM(0, "id", "__u32", "Error identifier")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(1, "command", "__u32", "Binder command that failed")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_UINT,
+	KAPI_PARAM_END
+
+	KAPI_PARAM(2, "param", "__s32", "Error parameter (negative errno)")
+		KAPI_PARAM_FLAGS(KAPI_PARAM_OUT)
+		.type = KAPI_TYPE_INT,
+		.constraint_type = KAPI_CONSTRAINT_RANGE,
+		.min_value = -MAX_ERRNO,
+		.max_value = 0,
+	KAPI_PARAM_END
+
+	/* Return value */
+	KAPI_RETURN("int", "0 on success, negative errno on failure")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+		.error_values = (const s64[]){-EFAULT},
+		.error_count = 1,
+	KAPI_RETURN_END
+
+	/* Errors */
+	KAPI_ERROR(0, -EFAULT, "EFAULT", "Failed to copy to user",
+		   "Invalid user pointer provided")
+
+	.error_count = 1,
+	.param_count = 3,
+	.since_version = "5.16",
+	.notes = "Error is cleared after reading, subsequent calls return BR_OK",
+	},
+};
+
+/* Register all binder IOCTL specifications */
+KAPI_IOCTL_SPEC_DRIVER("binder", {
+	&binder_write_read_spec,
+	&binder_set_max_threads_spec,
+	&binder_set_context_mgr_spec,
+	&binder_set_context_mgr_ext_spec,
+	&binder_thread_exit_spec,
+	&binder_version_spec,
+	&binder_get_node_info_for_ref_spec,
+	&binder_get_node_debug_info_spec,
+	&binder_freeze_spec,
+	&binder_get_frozen_info_spec,
+	&binder_enable_oneway_spam_detection_spec,
+	&binder_get_extended_error_spec,
+})
+
 DEFINE_SHOW_ATTRIBUTE(state);
 DEFINE_SHOW_ATTRIBUTE(state_hashed);
 DEFINE_SHOW_ATTRIBUTE(stats);
@@ -7050,6 +7798,13 @@ static int __init binder_init(void)
 	if (ret)
 		return ret;
 
+	/* Initialize the wrapped file_operations */
+	kapi_init_fops_binder_fops();
+
+	ret = kapi_ioctl_specs_init();
+	if (ret)
+		goto err_kapi_init;
+
 	atomic_set(&binder_transaction_log.cur, ~0U);
 	atomic_set(&binder_transaction_log_failed.cur, ~0U);
 
@@ -7102,6 +7857,9 @@ static int __init binder_init(void)
 
 err_alloc_device_names_failed:
 	debugfs_remove_recursive(binder_debugfs_dir_entry_root);
+	kapi_ioctl_specs_exit();
+
+err_kapi_init:
 	binder_alloc_shrinker_exit();
 
 	return ret;
Signature · 1 line
2.39.5
#23 lore raw

RFC 19/19 tools/kapi: Add kernel API specification extraction tool

In reply to Sasha Levin

The kapi tool extracts and displays kernel API specifications.

---
 Documentation/admin-guide/kernel-api-spec.rst | 198 ++++++-
 tools/kapi/.gitignore                         |   4 +
 tools/kapi/Cargo.toml                         |  19 +
 tools/kapi/src/extractor/debugfs.rs           | 204 ++++++++
 tools/kapi/src/extractor/mod.rs               |  95 ++++
 tools/kapi/src/extractor/source_parser.rs     | 488 ++++++++++++++++++
 .../src/extractor/vmlinux/binary_utils.rs     | 130 +++++
 tools/kapi/src/extractor/vmlinux/mod.rs       | 372 +++++++++++++
 tools/kapi/src/formatter/json.rs              | 170 ++++++
 tools/kapi/src/formatter/mod.rs               |  68 +++
 tools/kapi/src/formatter/plain.rs             |  99 ++++
 tools/kapi/src/formatter/rst.rs               | 144 ++++++
 tools/kapi/src/main.rs                        | 121 +++++
 13 files changed, 2109 insertions(+), 3 deletions(-)
 create mode 100644 tools/kapi/.gitignore
 create mode 100644 tools/kapi/Cargo.toml
 create mode 100644 tools/kapi/src/extractor/debugfs.rs
 create mode 100644 tools/kapi/src/extractor/mod.rs
 create mode 100644 tools/kapi/src/extractor/source_parser.rs
 create mode 100644 tools/kapi/src/extractor/vmlinux/binary_utils.rs
 create mode 100644 tools/kapi/src/extractor/vmlinux/mod.rs
 create mode 100644 tools/kapi/src/formatter/json.rs
 create mode 100644 tools/kapi/src/formatter/mod.rs
 create mode 100644 tools/kapi/src/formatter/plain.rs
 create mode 100644 tools/kapi/src/formatter/rst.rs
 create mode 100644 tools/kapi/src/main.rs
Documentation/admin-guide/kernel-api-spec.rst +195 -3
index 3a63f6711e27b..9b452753111ad 100644
@@ -31,7 +31,9 @@ The framework aims to:
    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.
+   use by static analyzers, documentation generators, and development tools. The
+   ``kapi`` tool (see `The kapi Tool`_) provides comprehensive extraction and
+   formatting capabilities.
 
 4. **Enhance Debugging**: Provide detailed API information at runtime through debugfs
    for debugging and introspection.
@@ -71,6 +73,13 @@ The framework consists of several key components:
    - Type-safe parameter specifications
    - Context and constraint definitions
 
+5. **kapi Tool** (``tools/kapi/``)
+
+   - Userspace utility for extracting specifications
+   - Multiple input sources (source, binary, debugfs)
+   - Multiple output formats (plain, JSON, RST)
+   - Testing and validation utilities
+
 Data Model
 ----------
 
@@ -344,8 +353,177 @@ 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.
+to generate documentation. The ``kapi`` tool provides comprehensive
+extraction and formatting capabilities for kernel API specifications.
+
+The kapi Tool
+=============
+
+Overview
+--------
+
+The ``kapi`` tool is a userspace utility that extracts and displays kernel API
+specifications from multiple sources. It provides a unified interface to access
+API documentation whether from compiled kernels, source code, or runtime systems.
+
+Installation
+------------
+
+Build the tool from the kernel source tree::
+
+    $ cd tools/kapi
+    $ cargo build --release
+
+    # Optional: Install system-wide
+    $ cargo install --path .
+
+The tool requires Rust and Cargo to build. The binary will be available at
+``tools/kapi/target/release/kapi``.
+
+Command-Line Usage
+------------------
+
+Basic syntax::
+
+    kapi [OPTIONS] [API_NAME]
+
+Options:
+
+- ``--vmlinux <PATH>``: Extract from compiled kernel binary
+- ``--source <PATH>``: Extract from kernel source code
+- ``--debugfs <PATH>``: Extract from debugfs (default: /sys/kernel/debug)
+- ``-f, --format <FORMAT>``: Output format (plain, json, rst)
+- ``-h, --help``: Display help information
+- ``-V, --version``: Display version information
+
+Input Modes
+-----------
+
+**1. Source Code Mode**
+
+Extract specifications directly from kernel source::
+
+    # Scan entire kernel source tree
+    $ kapi --source /path/to/linux
+
+    # Extract from specific file
+    $ kapi --source kernel/sched/core.c
+
+    # Get details for specific API
+    $ kapi --source /path/to/linux sys_sched_yield
+
+**2. Vmlinux Mode**
+
+Extract from compiled kernel with debug symbols::
+
+    # List all APIs in vmlinux
+    $ kapi --vmlinux /boot/vmlinux-5.15.0
+
+    # Get specific syscall details
+    $ kapi --vmlinux ./vmlinux sys_read
+
+**3. Debugfs Mode**
+
+Extract from running kernel via debugfs::
+
+    # Use default debugfs path
+    $ kapi
+
+    # Use custom debugfs mount
+    $ kapi --debugfs /mnt/debugfs
+
+    # Get specific API from running kernel
+    $ kapi sys_write
+
+Output Formats
+--------------
+
+**Plain Text Format** (default)::
+
+    $ kapi sys_read
+
+    Detailed information for sys_read:
+    ==================================
+    Description: Read from a file descriptor
+
+    Detailed Description:
+    Reads up to count bytes from file descriptor fd into the buffer starting at buf.
+
+    Execution Context:
+      - KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE
+
+    Parameters (3):
+
+    Available since: 1.0
+
+**JSON Format**::
+
+    $ kapi --format json sys_read
+    {
+      "api_details": {
+        "name": "sys_read",
+        "description": "Read from a file descriptor",
+        "long_description": "Reads up to count bytes...",
+        "context_flags": ["KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE"],
+        "since_version": "1.0"
+      }
+    }
+
+**ReStructuredText Format**::
+
+    $ kapi --format rst sys_read
+
+    sys_read
+    ========
+
+    **Read from a file descriptor**
+
+    Reads up to count bytes from file descriptor fd into the buffer...
+
+Usage Examples
+--------------
+
+**Generate complete API documentation**::
+
+    # Export all kernel APIs to JSON
+    $ kapi --source /path/to/linux --format json > kernel-apis.json
+
+    # Generate RST documentation for all syscalls
+    $ kapi --vmlinux ./vmlinux --format rst > syscalls.rst
+
+    # List APIs from specific subsystem
+    $ kapi --source drivers/gpu/drm/
+
+**Integration with other tools**::
+
+    # Find all APIs that can sleep
+    $ kapi --format json | jq '.apis[] | select(.context_flags[] | contains("SLEEPABLE"))'
+
+    # Generate markdown documentation
+    $ kapi --format rst sys_mmap | pandoc -f rst -t markdown
+
+**Debugging and analysis**::
+
+    # Compare API between kernel versions
+    $ diff <(kapi --vmlinux vmlinux-5.10) <(kapi --vmlinux vmlinux-5.15)
+
+    # Check if specific API exists
+    $ kapi --source . my_custom_api || echo "API not found"
+
+Implementation Details
+----------------------
+
+The tool extracts API specifications from three sources:
+
+1. **Source Code**: Parses KAPI specification macros using regular expressions
+2. **Vmlinux**: Reads the ``.kapi_specs`` ELF section from compiled kernels
+3. **Debugfs**: Reads from ``/sys/kernel/debug/kapi/`` filesystem interface
+
+The tool supports all KAPI specification types:
+
+- System calls (``DEFINE_KERNEL_API_SPEC``)
+- IOCTLs (``DEFINE_IOCTL_API_SPEC``)
+- Kernel functions (``KAPI_DEFINE_SPEC``)
 
 IDE Integration
 ---------------
@@ -357,6 +535,11 @@ Modern IDEs can use the JSON export for:
 - Context validation
 - Error code documentation
 
+Example IDE integration::
+
+    # Generate IDE completion data
+    $ kapi --format json > .vscode/kernel-apis.json
+
 Testing Framework
 -----------------
 
@@ -367,6 +550,15 @@ The framework includes test helpers::
     kapi_test_api("kmalloc", test_cases);
     #endif
 
+The kapi tool can verify specifications against implementations::
+
+    # Run consistency tests
+    $ cd tools/kapi
+    $ ./test_consistency.sh
+
+    # Compare source vs binary specifications
+    $ ./compare_all_syscalls.sh
+
 Best Practices
 ==============
 
tools/kapi/.gitignore new file +4 -0
new file mode 100644
index 0000000000000..1390bfc12686c
@@ -0,0 +1,4 @@
+# Rust build artifacts
+/target/
+**/*.rs.bk
+
tools/kapi/Cargo.toml new file +19 -0
new file mode 100644
index 0000000000000..4e6bcb10d132f
@@ -0,0 +1,19 @@
+[package]
+name = "kapi"
+version = "0.1.0"
+edition = "2024"
+authors = ["Sasha Levin <[email protected]>"]
+description = "Tool for extracting and displaying kernel API specifications"
+license = "GPL-2.0"
+
+[dependencies]
+goblin = "0.10"
+clap = { version = "4.4", features = ["derive"] }
+anyhow = "1.0"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+regex = "1.10"
+walkdir = "2.4"
+
+[dev-dependencies]
+tempfile = "3.8"
tools/kapi/src/extractor/debugfs.rs new file +204 -0

205 lines not on this page · raw message

tools/kapi/src/extractor/mod.rs new file +95 -0

96 lines not on this page · raw message

tools/kapi/src/extractor/source_parser.rs new file +488 -0

489 lines not on this page · raw message

tools/kapi/src/extractor/vmlinux/binary_utils.rs new file +130 -0

131 lines not on this page · raw message

tools/kapi/src/extractor/vmlinux/mod.rs new file +372 -0

373 lines not on this page · raw message

tools/kapi/src/formatter/json.rs new file +170 -0

171 lines not on this page · raw message

tools/kapi/src/formatter/mod.rs new file +68 -0

69 lines not on this page · raw message

tools/kapi/src/formatter/plain.rs new file +99 -0

100 lines not on this page · raw message

tools/kapi/src/formatter/rst.rs new file +144 -0

145 lines not on this page · raw message

tools/kapi/src/main.rs new file +121 -0

121 lines not on this page · raw message

Signature · 1 line
2.39.5
#9 lore raw

Re: [RFC 08/19] exec: add API specification for execve

In reply to Sasha Levin

* Sasha Levin:

fs/exec.c void set_dumpable(struct mm_struct *mm, int value) · line 2034

Quoted 4 lines
fs/exec.c +4 -0
+	KAPI_RETURN("long", "Does not return on success; returns -1 on error")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+	KAPI_RETURN_END

Is the -1 part correct?

Many later errors during execve are not recoverable and result in execve succeeding (nominally) and a fatal signal being delivered to the process instead. Not sure if the description covers that.

What about the effect of unblocking a parent thread that has vfork'ed?

Thanks,
Florian

#10 lore raw

Re: [RFC 08/19] exec: add API specification for execve

Quoted 8 lines · Florian Weimer

* Sasha Levin:

fs/exec.c void set_dumpable(struct mm_struct *mm, int value) · line 2034

Quoted 4 lines
fs/exec.c +4 -0
+	KAPI_RETURN("long", "Does not return on success; returns -1 on error")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+	KAPI_RETURN_END

Is the -1 part correct?

Maybe :) That's one of the things I wasn't sure about: we're documenting the execve syscall rather than the function itself. A user calling execve() will end up with -1 on failure, and errno set with the error code.

You could argue that it's libc that sets errno and we're trying to spec the kernel here, not the userspace interface to it.

At the end I managed to lawyer myself into a decision that I liked: I figured that since klibc is really a kernel library that is merely packaged seperately from the kernel, it is really a kernel interface, and so I followed the libc convention.

Open for suggestions...

Quoted 3 lines

Many later errors during execve are not recoverable and result in execve succeeding (nominally) and a fatal signal being delivered to the process instead. Not sure if the description covers that.

I was afraid of the "signals" rabit hole: from what I recall, you can have fatal signals pending past the point of no return but before execve() completes from both execve() failures as well as external sources.

There's definitely room for a longer explanation of how all of this works together.

I'd suggest that we tackle signal specs in the near future, and see how we can tie those into the rest of the API specs. Right now I'm pretty unhappy with the vague KAPI_SIGNAL().

Quoted 1 line

What about the effect of unblocking a parent thread that has vfork'ed?

In my mind it's vfork() that is waiting for the execve to complete (via wait_for_vfork_done()) rather than execve() actively waking up the vfork() parent.

We can list it as a side effect of execve()? I suppose that its similar to something like read() in one process waking up a different process from epoll_wait(), so we should probably be documenting those as well...

Thanks for the comments!

Signature · 2 lines
Thanks,
Sasha
#11 lore raw

Re: [RFC 08/19] exec: add API specification for execve

* Sasha Levin:

Quoted 10 lines · Florian Weimer
Quoted 8 lines

* Sasha Levin:

fs/exec.c void set_dumpable(struct mm_struct *mm, int value) · line 2034

Quoted 4 lines
fs/exec.c +4 -0
+	KAPI_RETURN("long", "Does not return on success; returns -1 on error")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+	KAPI_RETURN_END

Is the -1 part correct?

Quoted 4 lines

Maybe :) That's one of the things I wasn't sure about: we're documenting the execve syscall rather than the function itself. A user calling execve() will end up with -1 on failure, and errno set with the error code.

Well, it doesn't say execve, it says sys_execve.

Quoted 2 lines

You could argue that it's libc that sets errno and we're trying to spec the kernel here, not the userspace interface to it.

And I think this would be appropriate.

Note that in the future, the glibc version of execve will not be a straightforward system call wrapper because we need to obtain a consistent snapshot of the environment array. That is actually pretty hard because we cannot atomically replace the process image, unblock signals, and unmap a copy of the environment.

So I think it's best for the kernel to stick with the system call interface and not try to document what libcs are doing.

An even more thorny example are the setuid family of system calls, where the kernel is extremely far away from what POSIX requires, and we have to fix it in userspace.

Thanks,
Florian

#24 lore raw
In reply to Sasha Levin
Quoted 6 lines · On Sat, 14 Jun 2025 09:48:39 -0400 Sasha Levin <[email protected]> wrote:

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.

Ugg, looks horrid.
Going to be worse than things like doxygen for getting out of step with the actual code and grep searches are going to hit the comment blocks.

David

#12 lore raw

Re: [RFC 08/19] exec: add API specification for execve

In reply to Florian Weimer
Quoted 24 lines · Florian Weimer

* Sasha Levin:

Quoted 10 lines · Florian Weimer
Quoted 8 lines

* Sasha Levin:

fs/exec.c void set_dumpable(struct mm_struct *mm, int value) · line 2034

Quoted 4 lines
fs/exec.c +4 -0
+	KAPI_RETURN("long", "Does not return on success; returns -1 on error")
+		.type = KAPI_TYPE_INT,
+		.check_type = KAPI_RETURN_ERROR_CHECK,
+	KAPI_RETURN_END

Is the -1 part correct?

Quoted 4 lines

Maybe :) That's one of the things I wasn't sure about: we're documenting the execve syscall rather than the function itself. A user calling execve() will end up with -1 on failure, and errno set with the error code.

Well, it doesn't say execve, it says sys_execve.

Quoted 2 lines

You could argue that it's libc that sets errno and we're trying to spec the kernel here, not the userspace interface to it.

And I think this would be appropriate.

Quoted 8 lines

Note that in the future, the glibc version of execve will not be a straightforward system call wrapper because we need to obtain a consistent snapshot of the environment array. That is actually pretty hard because we cannot atomically replace the process image, unblock signals, and unmap a copy of the environment.

So I think it's best for the kernel to stick with the system call interface and not try to document what libcs are doing.

I hear you - it sounds like the "right" solution technically.

Switching back to signals, how does something like the below look as far as expanding the execve() spec:

+ /* SIGSEGV sent on point of no return failure */
+ KAPI_SIGNAL(9, SIGSEGV, "SIGSEGV", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_COREDUMP)

+               KAPI_SIGNAL_TARGET("Current process")
+               KAPI_SIGNAL_CONDITION("Exec fails after point of no return")
+               KAPI_SIGNAL_DESC("If exec fails after the point of no return (when the old "
+                                "process image has been destroyed), force_fatal_sig(SIGSEGV) "
+                                "is called to terminate the process since it cannot continue.")
+               KAPI_SIGNAL_TIMING(KAPI_SIGNAL_TIME_EXIT)
+               KAPI_SIGNAL_PRIORITY(0)
+               KAPI_SIGNAL_STATE_FORBID(KAPI_SIGNAL_STATE_ZOMBIE | KAPI_SIGNAL_STATE_DEAD)

+ KAPI_SIGNAL_END
+
+ /* Signal mask preserved */
+ KAPI_SIGNAL(10, 0, "SIGNAL_MASK", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM)
+ KAPI_SIGNAL_CONDITION("Process has blocked signals")
+ KAPI_SIGNAL_DESC("The signal mask (blocked signals) is preserved across exec. "
+ "This allows processes to block signals before exec and have "
+ "them remain blocked in the new program.")
+ KAPI_SIGNAL_TIMING(KAPI_SIGNAL_TIME_DURING)
+ KAPI_SIGNAL_END
+
+ /* Realtime signal queues cleared */
+ KAPI_SIGNAL(11, 0, "REALTIME_SIGNALS", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_DISCARD)
+ KAPI_SIGNAL_CONDITION("Realtime signals queued")
+ KAPI_SIGNAL_DESC("All queued realtime signals (SIGRTMIN to SIGRTMAX) are "
+ "discarded during exec. The realtime signal queue is cleared.")
+ KAPI_SIGNAL_TIMING(KAPI_SIGNAL_TIME_DURING)
+ KAPI_SIGNAL_QUEUE(KAPI_SIGNAL_QUEUE_REALTIME)
+ KAPI_SIGNAL_END

What's missing for me is that while we now go into more detail, we should also check this during runtime, but I'm still trying to come up with something that is not ugly.

Signature · 2 lines
Thanks,
Sasha
maintainer
#25 lore raw
In reply to Sasha Levin
Quoted 6 lines · Sasha Levin

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.

I'd much prefer this be more attached to the code in question, otherwise we've go two things to update when changes happen. (Well, 3, since kern-doc already needs updating too.)

Can't we collect error codes programmatically through control flow analysis? Argument mapping is already present in the SYSCALL macros, etc. Let's not repeat this info.

-Kees

Signature · 1 line
Kees Cook
#26 lore raw
Quoted 8 lines · Kees Cook
Quoted 6 lines · Sasha Levin

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.

Quoted 6 lines

I'd much prefer this be more attached to the code in question, otherwise we've go two things to update when changes happen. (Well, 3, since kern-doc already needs updating too.)

Can't we collect error codes programmatically through control flow analysis? Argument mapping is already present in the SYSCALL macros,

I'm not sure what you meant with in the control flow analysis part: we have code to verify that the return value from the macro matches one of the ones defined in the spec.

Quoted 1 line

etc. Let's not repeat this info.

I tried to come up with a way to get rid of the SYSCALL_DEFINEx() macro right after the spec. I agree that it's duplication, but my macro-foo is too weak to get rid of that SYSCALL_DEFINE() call.

Suggestions more than welcome here: I suspect that this might require a bigger change in the code, but I'm still trying to figure it out.

Signature · 2 lines
Thanks,
Sasha
#27 lore raw

Nice!

A bag of assorted comments:

1. I share the same concern of duplicating info.
If there are lots of duplication it may lead to failure of the whole effort since folks won't update these and/or they will get out of sync.
If a syscall arg is e.g. umode_t, we already know that it's an integer
of that enum type, and that it's an input arg.
In syzkaller we have a Clang-tool:
https://github.com/google/syzkaller/blob/master/tools/syz-declextract/clangtool/declextract.cpp
that extracts a bunch of interfaces automatically:
https://raw.githubusercontent.com/google/syzkaller/refs/heads/master/sys/linux/auto.txt
Though, oviously that won't have user-readable string descriptions, can't be used as a source of truth, and may be challenging to integrate into kernel build process. Though, extracting some of that info automatically may be nice.

2. Does this framework ensure that the specified info about args is correct? E.g. number of syscall args, and their types match the actual ones? If such things are not tested/validated during build, I afraid they will be riddled with bugs over time.

3. To reduce duplication we could use more type information, e.g. I was always frustrated that close is just:

SYSCALL_DEFINE1(close, unsigned int, fd)

whereas if we would do:

typedef int fd_t;
SYSCALL_DEFINE1(close, fd_t, fd)

then all semantic info about the arg is already in the code.

4. If we specify e.g. error return values here with descirptions, can that be used as the source of truth to generate man pages? That would eliminate some duplication.

5. We have a long standing dream that kernel developers add fuzzing descirpions along with new kernel interfaces. So far we got very few contributions to syzkaller from kernel developers. This framework can serve as the way to do it, which is nice.

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

7. One of the most useful uses of this framework that I see if testing kernel behavior correctness. I wonder what properties we can test with these descirptions, and if we can add more useful info for that purpose.
Argument validation does not help here (it's userspace bugs at best). Return values potentially may be useful, e.g. if we see a return value that's not specified, potentially it's a kernel bug.
Side-effects specification potentially can be used to detect logical kernel bugs, e.g. if a syscall does not claim to change fs state, but it does, it's a bug. Though, a more useful check should be failure/concurrency atomicity. Namely, if a syscall claims to not alter state on failure, it shouldn't do so. Concurrency atomicity means linearizability of concurrent syscalls (side-effects match one of 2 possible orders of syscalls).
But for these we would need to add additional flags to the descriptions that say that a syscall supports failure/concurrency atomicity.

8. It would be useful to have a mapping of file_operations to actual files in fs. Otherwise the exposed info is not very actionable, since there is no way to understand what actual file/fd the ioctl's can be applied to.

9. I see that syscalls and ioctls say:
KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)
Can't we make this implicit? Are there any other options?
Similarly an ioctl description says it releases a mutex (.released = true,), all ioctls/syscalls must release all acquired mutexes, no?
Generally, the less verbose the descriptions are, the higher chances of their survival. +Marco also works static compiler-enforced lock checking annotations,
I wonder if they can be used to describe this in a more useful way.

#28 lore raw

Hi!

Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

I was looking at that part and thinking that we could generate (at least some) automated conformance tests based on this information. We could make sure that invalid parameters are properly rejected. For open(), some combinations would be difficuilt to model though, e.g. for O_DIRECTORY the pathname is supposed to be a path to a directory and also the file descriptor returned has different properties. Also O_CREAT requires third parameter and changes which kinds of filepaths are invalid. Demultiplexing syscalls like this is going to be difficult to get right.

As for testing purposes, most of the time it would be enough just to say something as "this parameter is an existing file". If we have this information in a machine parseable format we can generate automatic tests for various error conditions e.g. ELOOP, EACESS, ENAMETOOLONG, ENOENT, ...

For paths we could have something as:

file:existing
file:notexisting
file:replaced|nonexisting
file:nonexisting|existing
dir:existing
dir:nonexisting

Then for open() syscall we can do:

flags=O_DIRECTORY path=dir:existing
flags=O_CREAT path=file:nonexisting|existing
flags=O_CREAT|O_EXCL path=file:nonexisting
...

You may wonder if such kind of tests are useful at all, since quite a few of these errors are checked for and generated from a common functions. There are at least two cases I can think of. First of all it makes sure that errors are stable when particular function/subsystem is rewritten. And it can also make sure that errors are consistent across different implementation of the same functionality e.g. filesystems. I remember that some of the less used FUSE filesystems returned puzzling errors in certain corner cases.

Maybe it would be more useful to steer this towards a system that annotates better the types for the syscall parameters and return values. Something that would be an extension to a C types with a description on how particular string or integer is interpreted.

Quoted 9 lines

Side-effects specification potentially can be used to detect logical kernel bugs, e.g. if a syscall does not claim to change fs state, but it does, it's a bug. Though, a more useful check should be failure/concurrency atomicity. Namely, if a syscall claims to not alter state on failure, it shouldn't do so. Concurrency atomicity means linearizability of concurrent syscalls (side-effects match one of 2 possible orders of syscalls).
But for these we would need to add additional flags to the descriptions that say that a syscall supports failure/concurrency atomicity.

Quoted 3 lines

8. It would be useful to have a mapping of file_operations to actual files in fs. Otherwise the exposed info is not very actionable, since there is no way to understand what actual file/fd the ioctl's can be applied to.

+1 There are many different kinds of file descriptors and they differ wildy in what operations they support.

Maybe we would need a subclass for a file descriptor, something as:

fd:file
fd:timerfd
fd:pidfs
...

Signature · 2 lines
Cyril Hrubis
[email protected]
#29 lore raw
Quoted 42 lines · Cyril Hrubis

Hi!

Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

I was looking at that part and thinking that we could generate (at least some) automated conformance tests based on this information. We could make sure that invalid parameters are properly rejected. For open(), some combinations would be difficuilt to model though, e.g. for O_DIRECTORY the pathname is supposed to be a path to a directory and also the file descriptor returned has different properties. Also O_CREAT requires third parameter and changes which kinds of filepaths are invalid. Demultiplexing syscalls like this is going to be difficult to get right.

As for testing purposes, most of the time it would be enough just to say something as "this parameter is an existing file". If we have this information in a machine parseable format we can generate automatic tests for various error conditions e.g. ELOOP, EACESS, ENAMETOOLONG, ENOENT, ...

For paths we could have something as:

file:existing
file:notexisting
file:replaced|nonexisting
file:nonexisting|existing
dir:existing
dir:nonexisting

Then for open() syscall we can do:

flags=O_DIRECTORY path=dir:existing
flags=O_CREAT path=file:nonexisting|existing
flags=O_CREAT|O_EXCL path=file:nonexisting
...

Quoted 8 lines

You may wonder if such kind of tests are useful at all, since quite a few of these errors are checked for and generated from a common functions. There are at least two cases I can think of. First of all it makes sure that errors are stable when particular function/subsystem is rewritten. And it can also make sure that errors are consistent across different implementation of the same functionality e.g. filesystems. I remember that some of the less used FUSE filesystems returned puzzling errors in certain corner cases.

I am not following how this is related to the validation part of the patch series. Can you elaborate?

Generation of such conformance tests would need info about parameter types and their semantic meaning, not the validation part. The conformance tests should test that actual syscall checking of arguments, not the validation added by this framework.

Quoted 4 lines

Maybe it would be more useful to steer this towards a system that annotates better the types for the syscall parameters and return values. Something that would be an extension to a C types with a description on how particular string or integer is interpreted.

+1

Quoted 13 lines
Quoted 9 lines

Side-effects specification potentially can be used to detect logical kernel bugs, e.g. if a syscall does not claim to change fs state, but it does, it's a bug. Though, a more useful check should be failure/concurrency atomicity. Namely, if a syscall claims to not alter state on failure, it shouldn't do so. Concurrency atomicity means linearizability of concurrent syscalls (side-effects match one of 2 possible orders of syscalls).
But for these we would need to add additional flags to the descriptions that say that a syscall supports failure/concurrency atomicity.

Quoted 3 lines

8. It would be useful to have a mapping of file_operations to actual files in fs. Otherwise the exposed info is not very actionable, since there is no way to understand what actual file/fd the ioctl's can be applied to.

Quoted 8 lines

+1 There are many different kinds of file descriptors and they differ wildy in what operations they support.

Maybe we would need a subclass for a file descriptor, something as:

fd:file
fd:timerfd
fd:pidfs

FWIW syzkaller has this for the purpose of automatic generation of test inputs.

#30 lore raw

Hi!

Quoted 11 lines
Quoted 8 lines

You may wonder if such kind of tests are useful at all, since quite a few of these errors are checked for and generated from a common functions. There are at least two cases I can think of. First of all it makes sure that errors are stable when particular function/subsystem is rewritten. And it can also make sure that errors are consistent across different implementation of the same functionality e.g. filesystems. I remember that some of the less used FUSE filesystems returned puzzling errors in certain corner cases.

I am not following how this is related to the validation part of the patch series. Can you elaborate?

This part is me trying to explain that generated conformance tests would be useful for development as well.

Quoted 4 lines

Generation of such conformance tests would need info about parameter types and their semantic meaning, not the validation part. The conformance tests should test that actual syscall checking of arguments, not the validation added by this framework.

Exactly.

I do not think that it makes sense to encode the argument ranges and functions to generate a valid syscall parameters into the kernel. Rather than that the information should encoded in the extended types, if we do that well enough we can generate combination of different valid and invalid parameters for the tests based on that.

Signature · 2 lines
Cyril Hrubis
[email protected]
#31 lore raw
In reply to Dmitry Vyukov
Quoted 17 lines · Dmitry Vyukov

Nice!

A bag of assorted comments:

1. I share the same concern of duplicating info.
If there are lots of duplication it may lead to failure of the whole effort since folks won't update these and/or they will get out of sync.
If a syscall arg is e.g. umode_t, we already know that it's an integer
of that enum type, and that it's an input arg.
In syzkaller we have a Clang-tool:
https://github.com/google/syzkaller/blob/master/tools/syz-declextract/clangtool/declextract.cpp
that extracts a bunch of interfaces automatically:
https://raw.githubusercontent.com/google/syzkaller/refs/heads/master/sys/linux/auto.txt
Though, oviously that won't have user-readable string descriptions, can't be used as a source of truth, and may be challenging to integrate into kernel build process. Though, extracting some of that info automatically may be nice.

Quoted 4 lines

2. Does this framework ensure that the specified info about args is correct? E.g. number of syscall args, and their types match the actual ones? If such things are not tested/validated during build, I afraid they will be riddled with bugs over time.

This is an answer for both (1) and (2): yes! In my mind, whatever we spec out needs to be enforced, because otherwise it will go out of sync.

In this RFC, take a look at the code guarded by CONFIG_KAPI_RUNTIME_CHECKS: the idea is that we can enable runtime checks that verify the things you've mentioned above (and more).

Quoted 11 lines

3. To reduce duplication we could use more type information, e.g. I was always frustrated that close is just:

SYSCALL_DEFINE1(close, unsigned int, fd)

whereas if we would do:

typedef int fd_t;
SYSCALL_DEFINE1(close, fd_t, fd)

then all semantic info about the arg is already in the code.

Yup. It would also be great if we completely drop the SYSCALL_DEFINE() part and have it be automatically generated by the spec itself, but I couldn't wrap my head around doing this in C macro just yet.

Quoted 3 lines

4. If we specify e.g. error return values here with descirptions, can that be used as the source of truth to generate man pages? That would eliminate some duplication.

Ideally yes. One of the formatters that the kapi tool has (see the last patch in this series) is the RST formatter that could be used to generate documentation similar to man pages.

Quoted 3 lines

5. We have a long standing dream that kernel developers add fuzzing descirpions along with new kernel interfaces. So far we got very few contributions to syzkaller from kernel developers. This framework can serve as the way to do it, which is nice.

This was one of the main usecases I had in mind.

In return, we can get back from syzkaller a body of automatically generated tests that we can embed into our testing CIs.

Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

Ideally it would also prevent some of the issues that syzkaller is so good at finding :)

Quoted 6 lines

7. One of the most useful uses of this framework that I see if testing kernel behavior correctness. I wonder what properties we can test with these descirptions, and if we can add more useful info for that purpose.
Argument validation does not help here (it's userspace bugs at best). Return values potentially may be useful, e.g. if we see a return value that's not specified, potentially it's a kernel bug.

Quoted 8 lines

Side-effects specification potentially can be used to detect logical kernel bugs, e.g. if a syscall does not claim to change fs state, but it does, it's a bug. Though, a more useful check should be failure/concurrency atomicity. Namely, if a syscall claims to not alter state on failure, it shouldn't do so. Concurrency atomicity means linearizability of concurrent syscalls (side-effects match one of 2 possible orders of syscalls).
But for these we would need to add additional flags to the descriptions that say that a syscall supports failure/concurrency atomicity.

I agree: being able to fuzz for more than just kernel splats will be great.

Quoted 3 lines

8. It would be useful to have a mapping of file_operations to actual files in fs. Otherwise the exposed info is not very actionable, since there is no way to understand what actual file/fd the ioctl's can be applied to.

Ack. The ioctl() part is a bit hand weavy right now, and at the very least we'd need to spec out ioctl() itself. It's more of a demonstration of how it could look like rather than being too useful at this point.

Quoted 3 lines

9. I see that syscalls and ioctls say:
KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) Can't we make this implicit? Are there any other options?

Maybe? I wasn't sure how we'd describe somthing like getpid() which isn't supposed to sleep.

Quoted 5 lines

Similarly an ioctl description says it releases a mutex (.released = true,), all ioctls/syscalls must release all acquired mutexes, no?
Generally, the less verbose the descriptions are, the higher chances of their survival. +Marco also works static compiler-enforced lock checking annotations,
I wonder if they can be used to describe this in a more useful way.

I was thinking about stuff like futex or flock which can return with a lock back to userspace.

Signature · 2 lines
Thanks,
Sasha
#32 lore raw
Quoted 7 lines · Sasha Levin
Quoted 7 lines

3. To reduce duplication we could use more type information, e.g. I was always frustrated that close is just:

SYSCALL_DEFINE1(close, unsigned int, fd)

whereas if we would do:

Quoted 8 lines
Quoted 4 lines

typedef int fd_t;
SYSCALL_DEFINE1(close, fd_t, fd)

then all semantic info about the arg is already in the code.

Yup. It would also be great if we completely drop the SYSCALL_DEFINE() part and have it be automatically generated by the spec itself, but I couldn't wrap my head around doing this in C macro just yet.

At some point I was looking at boost.pp library as the source of info on how to do things. It provides a set of containers and algorithms on them:
https://www.boost.org/doc/libs/latest/libs/preprocessor/doc/index.html

Sequences may be the most appealing b/c they support variable number of elements, and don't need specifying number of elements explicitly:
https://www.boost.org/doc/libs/latest/libs/preprocessor/doc/data/sequences.html
A sequence then allows generating multiple things from it using foreach over elements.

#33 lore raw
In reply to Sasha Levin
Quoted 11 lines · Sasha Levin
Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

How exactly is this supposed to work?
Even if we run with a unit test suite, a test suite may include some incorrect inputs to check for error conditions. The framework will report violations on these incorrect inputs. These are not bugs in the API specifications, nor in the test suite (read false positives).

#42 lore raw
In reply to Sasha Levin
Quoted 7 lines · Sasha Levin
Quoted 3 lines

9. I see that syscalls and ioctls say:
KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) Can't we make this implicit? Are there any other options?

Maybe? I wasn't sure how we'd describe somthing like getpid() which isn't supposed to sleep.

Quoted 8 lines
Quoted 5 lines

Similarly an ioctl description says it releases a mutex (.released = true,), all ioctls/syscalls must release all acquired mutexes, no?
Generally, the less verbose the descriptions are, the higher chances of their survival. +Marco also works static compiler-enforced lock checking annotations,
I wonder if they can be used to describe this in a more useful way.

I was thinking about stuff like futex or flock which can return with a lock back to userspace.

I see, this makes sense. Then I would go with explicitly specifying rare uncommon cases instead, and require 99% of common cases be the default that does not require saying anything.

E.g. KAPI_CTX_NON_SLEEPABLE, .not_released = true.

KAPI_CTX_NON_SLEEPABLE looks useful, since it allows easy validation:
set current flag, and BUG on any attempt to sleep when the flag is set (lockdep probably already has required pieces for this).

#34 lore raw
In reply to Dmitry Vyukov

Hi!

Quoted 12 lines
Quoted 11 lines
Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

Quoted 5 lines

How exactly is this supposed to work?
Even if we run with a unit test suite, a test suite may include some incorrect inputs to check for error conditions. The framework will report violations on these incorrect inputs. These are not bugs in the API specifications, nor in the test suite (read false positives).

This is what I tried to respond to but I guess that it didn't go well. Let me try to reiterate. I my opinion you shouldn't really put this part into the kernel, but rather than that include more type and semantic information into the data so that tests can be generated and executed in userspace. I do not see how can we validate that we get proper errors from a syscall if one of the input parameters is invalid other than generating and running a C test in userspace. For that part the syscall description does not need to be build into the kernel either, it may be just a build artifact that gets installed with the kernel image.

Signature · 2 lines
Cyril Hrubis
[email protected]
#35 lore raw
In reply to Dmitry Vyukov
Quoted 14 lines · Dmitry Vyukov
Quoted 11 lines · Sasha Levin
Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

Quoted 5 lines

How exactly is this supposed to work?
Even if we run with a unit test suite, a test suite may include some incorrect inputs to check for error conditions. The framework will report violations on these incorrect inputs. These are not bugs in the API specifications, nor in the test suite (read false positives).

Right now it would be something along the lines of the test checking for an expected failure message in dmesg, something along the lines of:

	https://github.com/linux-test-project/ltp/blob/0c99c7915f029d32de893b15b0a213ff3de210af/testcases/commands/sysctl/sysctl02.sh#L67

I'm not opposed to coming up with a better story...

Signature · 2 lines
Thanks,
Sasha
#43 lore raw
In reply to Dmitry Vyukov
Quoted 21 lines · Dmitry Vyukov
Quoted 7 lines · Sasha Levin
Quoted 3 lines

9. I see that syscalls and ioctls say:
KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) Can't we make this implicit? Are there any other options?

Maybe? I wasn't sure how we'd describe somthing like getpid() which isn't supposed to sleep.

Quoted 8 lines
Quoted 5 lines

Similarly an ioctl description says it releases a mutex (.released = true,), all ioctls/syscalls must release all acquired mutexes, no?
Generally, the less verbose the descriptions are, the higher chances of their survival. +Marco also works static compiler-enforced lock checking annotations,
I wonder if they can be used to describe this in a more useful way.

I was thinking about stuff like futex or flock which can return with a lock back to userspace.

I see, this makes sense. Then I would go with explicitly specifying rare uncommon cases instead, and require 99% of common cases be the default that does not require saying anything.

Quoted 5 lines

E.g. KAPI_CTX_NON_SLEEPABLE, .not_released = true.

KAPI_CTX_NON_SLEEPABLE looks useful, since it allows easy validation:
set current flag, and BUG on any attempt to sleep when the flag is set (lockdep probably already has required pieces for this).

Yup, that makes sense. One of the reason I wrapped all the field assignments with macros is that we can easily customize them based on usage, so instead of:

	#define KAPI_LOCK_ACQUIRED \
        	        .acquired = true,

	#define KAPI_LOCK_RELEASED \
        	        .released = true,

We can add:

	#define KAPI_LOCK_USED \
			.acquired = true, \
			.released = true,
Signature · 2 lines
Thanks,
Sasha
#36 lore raw
In reply to Sasha Levin
Quoted 22 lines · Sasha Levin
Quoted 14 lines · Dmitry Vyukov
Quoted 11 lines · Sasha Levin
Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

Quoted 5 lines

How exactly is this supposed to work?
Even if we run with a unit test suite, a test suite may include some incorrect inputs to check for error conditions. The framework will report violations on these incorrect inputs. These are not bugs in the API specifications, nor in the test suite (read false positives).

Quoted 6 lines

Right now it would be something along the lines of the test checking for an expected failure message in dmesg, something along the lines of:

        https://github.com/linux-test-project/ltp/blob/0c99c7915f029d32de893b15b0a213ff3de210af/testcases/commands/sysctl/sysctl02.sh#L67

I'm not opposed to coming up with a better story...

Oh, you mean special tests for this framework (rather than existing tests). I don't think this is going to work in practice. Besides writing all these specifications, we will also need to write dozens of tests per each specification (e.g. for each fd arg one needs at least 3 tests:
-1, valid fd, inclid fd; an enum may need 5 various inputs of something; let alone netlink specifications).

#37 lore raw
Quoted 24 lines · Dmitry Vyukov
Quoted 22 lines · Sasha Levin
Quoted 19 lines · Dmitry Vyukov
Quoted 11 lines · Sasha Levin
Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

How exactly is this supposed to work?
Even if we run with a unit test suite, a test suite may include some incorrect inputs to check for error conditions. The framework will report violations on these incorrect inputs. These are not bugs in the API specifications, nor in the test suite (read false positives).

Quoted 6 lines
Quoted 6 lines

Right now it would be something along the lines of the test checking for an expected failure message in dmesg, something along the lines of:

        https://github.com/linux-test-project/ltp/blob/0c99c7915f029d32de893b15b0a213ff3de210af/testcases/commands/sysctl/sysctl02.sh#L67

I'm not opposed to coming up with a better story...

If the goal of validation is just indirectly validating correctness of the specification itself, then I would look for other ways of validating correctness of the spec.
Either removing duplication between specification and actual code (i.e. generating it from SYSCALL_DEFINE, or the other way around) , then spec is correct by construction. Or, cross-validating it with info automatically extracted from the source (using clang/dwarf/pahole).
This would be more scalable (O(1) work, rather than thousands more manually written tests).

Quoted 6 lines

Oh, you mean special tests for this framework (rather than existing tests). I don't think this is going to work in practice. Besides writing all these specifications, we will also need to write dozens of tests per each specification (e.g. for each fd arg one needs at least 3 tests:
-1, valid fd, inclid fd; an enum may need 5 various inputs of something; let alone netlink specifications).

#38 lore raw
Quoted 32 lines · Dmitry Vyukov
Quoted 24 lines · Dmitry Vyukov
Quoted 22 lines · Sasha Levin
Quoted 19 lines · Dmitry Vyukov
Quoted 11 lines · Sasha Levin
Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

How exactly is this supposed to work?
Even if we run with a unit test suite, a test suite may include some incorrect inputs to check for error conditions. The framework will report violations on these incorrect inputs. These are not bugs in the API specifications, nor in the test suite (read false positives).

Quoted 6 lines
Quoted 6 lines

Right now it would be something along the lines of the test checking for an expected failure message in dmesg, something along the lines of:

        https://github.com/linux-test-project/ltp/blob/0c99c7915f029d32de893b15b0a213ff3de210af/testcases/commands/sysctl/sysctl02.sh#L67

I'm not opposed to coming up with a better story...

Quoted 17 lines

If the goal of validation is just indirectly validating correctness of the specification itself, then I would look for other ways of validating correctness of the spec.
Either removing duplication between specification and actual code (i.e. generating it from SYSCALL_DEFINE, or the other way around) , then spec is correct by construction. Or, cross-validating it with info automatically extracted from the source (using clang/dwarf/pahole).
This would be more scalable (O(1) work, rather than thousands more manually written tests).

Quoted 6 lines

Oh, you mean special tests for this framework (rather than existing tests). I don't think this is going to work in practice. Besides writing all these specifications, we will also need to write dozens of tests per each specification (e.g. for each fd arg one needs at least 3 tests:
-1, valid fd, inclid fd; an enum may need 5 various inputs of something; let alone netlink specifications).

I didn't mean just for the framework: being able to specify the APIs in machine readable format will enable us to automatically generate exhaustive tests for each such API.

I've been playing with the kapi tool (see last patch) which already supports different formatters. Right now it outputs human readable output, but I have proof-of-concept code that outputs testcases for specced APIs.

The dream here is to be able to automatically generate hundreds/thousands of tests for each API in an automated fashion, and verify the results with:

1. Simply checking expected return value.

2. Checking that the actual action happened (i.e. we called close(fd), verify that fd is really closed).

3. Check for side effects (i.e. close(fd) isn't supposed to allocate memory - verify that it didn't allocate memory).

4. Code coverage: our tests are supposed to cover 100% of the code in that APIs call chain, do we have code that didn't run (missing/incorrect specs).

Signature · 2 lines
Thanks,
Sasha
#39 lore raw
Quoted 70 lines · Sasha Levin
Quoted 32 lines · Dmitry Vyukov
Quoted 24 lines · Dmitry Vyukov
Quoted 22 lines · Sasha Levin
Quoted 19 lines · Dmitry Vyukov
Quoted 11 lines · Sasha Levin
Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

How exactly is this supposed to work?
Even if we run with a unit test suite, a test suite may include some incorrect inputs to check for error conditions. The framework will report violations on these incorrect inputs. These are not bugs in the API specifications, nor in the test suite (read false positives).

Quoted 6 lines
Quoted 6 lines

Right now it would be something along the lines of the test checking for an expected failure message in dmesg, something along the lines of:

        https://github.com/linux-test-project/ltp/blob/0c99c7915f029d32de893b15b0a213ff3de210af/testcases/commands/sysctl/sysctl02.sh#L67

I'm not opposed to coming up with a better story...

Quoted 17 lines

If the goal of validation is just indirectly validating correctness of the specification itself, then I would look for other ways of validating correctness of the spec.
Either removing duplication between specification and actual code (i.e. generating it from SYSCALL_DEFINE, or the other way around) , then spec is correct by construction. Or, cross-validating it with info automatically extracted from the source (using clang/dwarf/pahole).
This would be more scalable (O(1) work, rather than thousands more manually written tests).

Quoted 6 lines

Oh, you mean special tests for this framework (rather than existing tests). I don't think this is going to work in practice. Besides writing all these specifications, we will also need to write dozens of tests per each specification (e.g. for each fd arg one needs at least 3 tests:
-1, valid fd, inclid fd; an enum may need 5 various inputs of something; let alone netlink specifications).

I didn't mean just for the framework: being able to specify the APIs in machine readable format will enable us to automatically generate exhaustive tests for each such API.

I've been playing with the kapi tool (see last patch) which already supports different formatters. Right now it outputs human readable output, but I have proof-of-concept code that outputs testcases for specced APIs.

The dream here is to be able to automatically generate hundreds/thousands of tests for each API in an automated fashion, and verify the results with:

1. Simply checking expected return value.

2. Checking that the actual action happened (i.e. we called close(fd), verify that fd is really closed).

Quoted 6 lines

3. Check for side effects (i.e. close(fd) isn't supposed to allocate memory - verify that it didn't allocate memory).

4. Code coverage: our tests are supposed to cover 100% of the code in that APIs call chain, do we have code that didn't run (missing/incorrect specs).

This is all good. I was asking the argument verification part of the framework. Is it required for any of this? How?

#40 lore raw
Quoted 74 lines · Dmitry Vyukov
Quoted 73 lines · Sasha Levin
Quoted 32 lines · Dmitry Vyukov
Quoted 24 lines · Dmitry Vyukov
Quoted 22 lines · Sasha Levin
Quoted 19 lines · Dmitry Vyukov
Quoted 11 lines · Sasha Levin
Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

How exactly is this supposed to work?
Even if we run with a unit test suite, a test suite may include some incorrect inputs to check for error conditions. The framework will report violations on these incorrect inputs. These are not bugs in the API specifications, nor in the test suite (read false positives).

Quoted 6 lines
Quoted 6 lines

Right now it would be something along the lines of the test checking for an expected failure message in dmesg, something along the lines of:

        https://github.com/linux-test-project/ltp/blob/0c99c7915f029d32de893b15b0a213ff3de210af/testcases/commands/sysctl/sysctl02.sh#L67

I'm not opposed to coming up with a better story...

Quoted 17 lines

If the goal of validation is just indirectly validating correctness of the specification itself, then I would look for other ways of validating correctness of the spec.
Either removing duplication between specification and actual code (i.e. generating it from SYSCALL_DEFINE, or the other way around) , then spec is correct by construction. Or, cross-validating it with info automatically extracted from the source (using clang/dwarf/pahole).
This would be more scalable (O(1) work, rather than thousands more manually written tests).

Quoted 6 lines

Oh, you mean special tests for this framework (rather than existing tests). I don't think this is going to work in practice. Besides writing all these specifications, we will also need to write dozens of tests per each specification (e.g. for each fd arg one needs at least 3 tests:
-1, valid fd, inclid fd; an enum may need 5 various inputs of something; let alone netlink specifications).

I didn't mean just for the framework: being able to specify the APIs in machine readable format will enable us to automatically generate exhaustive tests for each such API.

I've been playing with the kapi tool (see last patch) which already supports different formatters. Right now it outputs human readable output, but I have proof-of-concept code that outputs testcases for specced APIs.

The dream here is to be able to automatically generate hundreds/thousands of tests for each API in an automated fashion, and verify the results with:

1. Simply checking expected return value.

2. Checking that the actual action happened (i.e. we called close(fd), verify that fd is really closed).

3. Check for side effects (i.e. close(fd) isn't supposed to allocate memory - verify that it didn't allocate memory).

Quoted 7 lines
Quoted 3 lines

4. Code coverage: our tests are supposed to cover 100% of the code in that APIs call chain, do we have code that didn't run (missing/incorrect specs).

This is all good. I was asking the argument verification part of the framework. Is it required for any of this? How?

Specifications without enforcement are just documentation :)

In my mind, there are a few reasons we want this:

1. For folks coding against the kernel, it's a way for them to know that the code they're writing fits within the spec of the kernel's API.

2. Enforcement around kernel changes: think of a scenario where a flag is added to a syscall - the author of that change will have to also update the spec because otherwise the verification layer will complain about the new flag. This helps prevent divergence between the code and the spec.

3. Extra layer of security: we can choose to enable this as an additional layer to protect us from missing checks in our userspace facing API.

Signature · 2 lines
Thanks,
Sasha
#41 lore raw
Quoted 84 lines · Sasha Levin
Quoted 74 lines · Dmitry Vyukov
Quoted 73 lines · Sasha Levin
Quoted 32 lines · Dmitry Vyukov
Quoted 24 lines · Dmitry Vyukov
Quoted 22 lines · Sasha Levin
Quoted 19 lines · Dmitry Vyukov
Quoted 11 lines · Sasha Levin
Quoted 7 lines

6. What's the goal of validation of the input arguments?
Kernel code must do this validation anyway, right.
Any non-trivial validation is hard, e.g. even for open the validation function for file name would need to have access to flags and check file precense for some flags combinations. That may add significant amount of non-trivial code that duplicates main syscall logic, and that logic may also have bugs and memory leaks.

Mostly to catch divergence from the spec: think of a scenario where someone added a new param/flag/etc but forgot to update the spec - this will help catch it.

How exactly is this supposed to work?
Even if we run with a unit test suite, a test suite may include some incorrect inputs to check for error conditions. The framework will report violations on these incorrect inputs. These are not bugs in the API specifications, nor in the test suite (read false positives).

Quoted 6 lines
Quoted 6 lines

Right now it would be something along the lines of the test checking for an expected failure message in dmesg, something along the lines of:

        https://github.com/linux-test-project/ltp/blob/0c99c7915f029d32de893b15b0a213ff3de210af/testcases/commands/sysctl/sysctl02.sh#L67

I'm not opposed to coming up with a better story...

Quoted 17 lines

If the goal of validation is just indirectly validating correctness of the specification itself, then I would look for other ways of validating correctness of the spec.
Either removing duplication between specification and actual code (i.e. generating it from SYSCALL_DEFINE, or the other way around) , then spec is correct by construction. Or, cross-validating it with info automatically extracted from the source (using clang/dwarf/pahole).
This would be more scalable (O(1) work, rather than thousands more manually written tests).

Quoted 6 lines

Oh, you mean special tests for this framework (rather than existing tests). I don't think this is going to work in practice. Besides writing all these specifications, we will also need to write dozens of tests per each specification (e.g. for each fd arg one needs at least 3 tests:
-1, valid fd, inclid fd; an enum may need 5 various inputs of something; let alone netlink specifications).

I didn't mean just for the framework: being able to specify the APIs in machine readable format will enable us to automatically generate exhaustive tests for each such API.

I've been playing with the kapi tool (see last patch) which already supports different formatters. Right now it outputs human readable output, but I have proof-of-concept code that outputs testcases for specced APIs.

The dream here is to be able to automatically generate hundreds/thousands of tests for each API in an automated fashion, and verify the results with:

1. Simply checking expected return value.

2. Checking that the actual action happened (i.e. we called close(fd), verify that fd is really closed).

3. Check for side effects (i.e. close(fd) isn't supposed to allocate memory - verify that it didn't allocate memory).

Quoted 7 lines
Quoted 3 lines

4. Code coverage: our tests are supposed to cover 100% of the code in that APIs call chain, do we have code that didn't run (missing/incorrect specs).

This is all good. I was asking the argument verification part of the framework. Is it required for any of this? How?

Quoted 6 lines

Specifications without enforcement are just documentation :)

In my mind, there are a few reasons we want this:

1. For folks coding against the kernel, it's a way for them to know that the code they're writing fits within the spec of the kernel's API.

How is this different from just running the kernel normally? Running the kernel normally is simpler, faster, and more precise.

Quoted 5 lines

2. Enforcement around kernel changes: think of a scenario where a flag is added to a syscall - the author of that change will have to also update the spec because otherwise the verification layer will complain about the new flag. This helps prevent divergence between the code and the spec.

It may be more useful to invoke verification, but does not return early on verification errors, but instead memorize the result, and still always run the actual syscall normally. Then if verification produced an error, but the actual syscall has not returned the same error, then WARN loudly.

This should provide the same value. But also does not rely on correctly marked manually written tests to test the specification. It will work automatically with any fuzzing/randomized testing, which I assume will be more valuable for specification testing.

But then, as Cyril mentioned, this verification layer does not really need to live in the kernel. Once the kernel has exported the specification in machine-usable form, the same verification can be done in user-space. Which is always a good idea.

Quoted 3 lines

3. Extra layer of security: we can choose to enable this as an additional layer to protect us from missing checks in our userspace facing API.

This will have additional risks, and performance overhead. Such mitigations are usually assessed with % of past CVEs this could prevent. That would allow us to assess cost/benefit. Intuitively this does not look like worth doing to me.