Kernel API specification framework
Subsystems (15)
v2 cover Kernel API specification framework
Hey folks,
This is a second attempt at a "Kernel API Specification" framework, addressing the feedback from the initial RFC and expanding the scope to include sysfs attribute specifications.
Motivation
==========
The Linux kernel has one fundamental promise to userspace: we don't break it. This promise is the foundation of Linux's success, allowing applications written decades ago to still run on modern kernels. Yet despite this being our most important commitment, we lack reliable mechanisms to detect when we're about to break this promise.
Currently, we rely on:
- Developer vigilance and review
- User reports after release (often too late)
- Limited testing that can't cover all API usage patterns
- Documentation that's often incomplete or outdated
This gap between our commitment and our tooling is a fundamental problem. We have sophisticated tools to catch memory leaks, race conditions, and other bugs, but no systematic way to catch API breakage before it impacts users.
As the kernel continues to grow, so do the interfaces exposed by it. This applies to both the userspace API as well as the numerous internal APIs. Over the years, we've accumulated a lot of documentation, but it's sometimes lacking, spread out, and often out of date.
In the same way that we have runtime and static checkers to validate that code is correct, we need a way to validate that the *use* of the various APIs is correct and that changes don't break existing contracts.
This work aims to provide:
1. A machine-readable format to describe APIs.
2. Runtime validation of API contracts.
3. Generation of documentation and other artifacts.
4. Improved tooling for API exploration and debugging.
5. Most importantly: automated detection of API breakage.
With formal API specifications, we can:
- Detect when patches change API behavior in incompatible ways
- Validate that error codes, parameter constraints, and return values remain consistent across kernel versions
- Generate automated tests that verify API contracts
- Provide userspace with machine-readable guarantees about kernel behavior
- Catch subtle breakage (like removing error codes, changing semantics, or tightening constraints) that manual review might miss
The idea is to have an in-kernel API specification format that can be used by tools such as:
- Static analysis tools (checkpatch, sparse, Coccinelle) to detect API contract violations at compile time
- CI/CD systems to automatically flag potential userspace breakage
- Runtime verification (API contract validation) during testing
- Tracing and debugging (better BPF/ftrace integration)
- Documentation generation (automated, always up-to-date)
- Userspace helpers (interceptors, mocking frameworks, etc.)
- Fuzzers (can detect API contract violations, not just kernel crashes)
Where are we now?
=================
This series introduces a framework that allows developers to declare API specifications directly in their subsystem code. These specifications are then:
1. Exported via debugfs (making them runtime queryable)
2. Compiled into the kernel binary (accessible to tools)
3. Used for runtime validation (when enabled)
The kapi tool in tools/kapi/ can extract API specifications from:
- Source code (by parsing the KAPI macros)
- Running kernel (via debugfs)
- vmlinux binary (for offline analysis)
It produces output in multiple formats (plain text, JSON, RST) for easy integration with existing workflows.
Changes since v1
================
- Added sysfs attribute validation support (patches 19-20)
- Added socket() syscall specification (patch 21)
- Enhanced signal handling with new actions (QUEUE, DISCARD, TRANSFORM)
- Expanded all API specifications with more detailed constraints
- Improved error handling documentation across all patches
- Added network/socket infrastructure to core framework
- Plumbed in syscall runtime validation
Sasha Levin (22):
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
kernel/api: Add sysfs validation support to kernel API specification
framework
block: sysfs API specifications
net/socket: add API specification for socket() 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 + block/blk-integrity.c | 131 ++ block/blk-sysfs.c | 243 +++ block/genhd.c | 99 + drivers/android/binder.c | 701 +++++++ drivers/fwctl/main.c | 285 ++- fs/eventpoll.c | 1163 +++++++++++ fs/exec.c | 702 +++++++ include/asm-generic/vmlinux.lds.h | 20 + include/linux/kernel_api_spec.h | 1841 +++++++++++++++++ include/linux/syscall_api_spec.h | 137 ++ include/linux/syscalls.h | 38 + init/Kconfig | 2 + kernel/Makefile | 1 + kernel/api/Kconfig | 55 + kernel/api/Makefile | 13 + kernel/api/ioctl_validation.c | 355 ++++ kernel/api/kapi_debugfs.c | 340 +++ kernel/api/kernel_api_spec.c | 1531 ++++++++++++++ mm/mlock.c | 774 +++++++ net/socket.c | 489 +++++ tools/kapi/.gitignore | 4 + tools/kapi/Cargo.toml | 19 + tools/kapi/src/extractor/debugfs.rs | 415 ++++ tools/kapi/src/extractor/mod.rs | 411 ++++ tools/kapi/src/extractor/source_parser.rs | 1625 +++++++++++++++ .../src/extractor/vmlinux/binary_utils.rs | 283 +++ tools/kapi/src/extractor/vmlinux/mod.rs | 989 +++++++++ tools/kapi/src/formatter/json.rs | 420 ++++ tools/kapi/src/formatter/mod.rs | 130 ++ tools/kapi/src/formatter/plain.rs | 465 +++++ tools/kapi/src/formatter/rst.rs | 468 +++++ tools/kapi/src/formatter/shall.rs | 605 ++++++ tools/kapi/src/main.rs | 130 ++ 38 files changed, 15598 insertions(+), 3 deletions(-) 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/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/formatter/shall.rs create mode 100644 tools/kapi/src/main.rs
Signature · 1 line
2.39.5
RFC v2 1/22 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 | 1513 +++++++++++++++++ include/linux/syscall_api_spec.h | 137 ++ include/linux/syscalls.h | 38 + init/Kconfig | 2 + kernel/Makefile | 1 + kernel/api/Kconfig | 35 + kernel/api/Makefile | 7 + kernel/api/kernel_api_spec.c | 1122 ++++++++++++ 14 files changed, 3400 insertions(+) create mode 100644 Documentation/admin-guide/kernel-api-spec.rst create mode 100644 include/linux/kernel_api_spec.h create mode 100644 include/linux/syscall_api_spec.h create mode 100644 kernel/api/Kconfig create mode 100644 kernel/api/Makefile create mode 100644 kernel/api/kernel_api_spec.c
Documentation/admin-guide/kernel-api-spec.rst new file +507 -0
@@ -0,0 +1,507 @@ +.. SPDX-License-Identifier: GPL-2.0 + +====================================== +Kernel API Specification Framework +====================================== + +:Author: Sasha Levin <[email protected]> +:Date: June 2025 + +.. contents:: Table of Contents + :depth: 3 + :local: + +Introduction +============ + +The Kernel API Specification Framework (KAPI) provides a comprehensive system for +formally documenting, validating, and introspecting kernel APIs. This framework +addresses the long-standing challenge of maintaining accurate, machine-readable +documentation for the thousands of internal kernel APIs and system calls. + +Purpose and Goals +----------------- + +The framework aims to: + +1. **Improve API Documentation**: Provide structured, inline documentation that + lives alongside the code and is maintained as part of the development process. + +2. **Enable Runtime Validation**: Optionally validate API usage at runtime to catch + common programming errors during development and testing. + +3. **Support Tooling**: Export API specifications in machine-readable formats for + use by static analyzers, documentation generators, and development tools. + +4. **Enhance Debugging**: Provide detailed API information at runtime through debugfs + for debugging and introspection. + +5. **Formalize Contracts**: Explicitly document API contracts including parameter + constraints, execution contexts, locking requirements, and side effects. + +Architecture Overview +===================== + +Components +---------- + +The framework consists of several key components: + +1. **Core Framework** (``kernel/api/kernel_api_spec.c``) + + - API specification registration and storage + - Runtime validation engine + - Specification lookup and querying + +2. **DebugFS Interface** (``kernel/api/kapi_debugfs.c``) + + - Runtime introspection via ``/sys/kernel/debug/kapi/`` + - JSON and XML export formats + - Per-API detailed information + +3. **IOCTL Support** (``kernel/api/ioctl_validation.c``) + + - Extended framework for IOCTL specifications + - Automatic validation wrappers + - Structure field validation + +4. **Specification Macros** (``include/linux/kernel_api_spec.h``) + + - Declarative macros for API documentation + - Type-safe parameter specifications + - Context and constraint definitions + +Data Model +---------- + +The framework uses a hierarchical data model:: + + kernel_api_spec + ├── Basic Information + │ ├── name (API function name) + │ ├── version (specification version) + │ ├── description (human-readable description) + │ └── kernel_version (when API was introduced) + │ + ├── Parameters (up to 16) + │ └── kapi_param_spec + │ ├── name + │ ├── type (int, pointer, string, etc.) + │ ├── direction (in, out, inout) + │ ├── constraints (range, mask, enum values) + │ └── validation rules + │ + ├── Return Value + │ └── kapi_return_spec + │ ├── type + │ ├── success conditions + │ └── validation rules + │ + ├── Error Conditions (up to 32) + │ └── kapi_error_spec + │ ├── error code + │ ├── condition description + │ └── recovery advice + │ + ├── Execution Context + │ ├── allowed contexts (process, interrupt, etc.) + │ ├── locking requirements + │ └── preemption/interrupt state + │ + └── Side Effects + ├── memory allocation + ├── state changes + └── signal handling + +Usage Guide +=========== + +Basic API Specification +----------------------- + +To document a kernel API, use the specification macros in the implementation file: + +.. code-block:: c + + #include <linux/kernel_api_spec.h> + + KAPI_DEFINE_SPEC(kmalloc_spec, kmalloc, "3.0") + KAPI_DESCRIPTION("Allocate kernel memory") + KAPI_PARAM(0, size, KAPI_TYPE_SIZE_T, KAPI_DIR_IN, + "Number of bytes to allocate") + KAPI_PARAM_RANGE(0, 0, KMALLOC_MAX_SIZE) + KAPI_PARAM(1, flags, KAPI_TYPE_FLAGS, KAPI_DIR_IN, + "Allocation flags (GFP_*)") + KAPI_PARAM_MASK(1, __GFP_BITS_MASK) + KAPI_RETURN(KAPI_TYPE_POINTER, "Pointer to allocated memory or NULL") + KAPI_ERROR(ENOMEM, "Out of memory") + KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SOFTIRQ | KAPI_CTX_HARDIRQ) + KAPI_SIDE_EFFECT("Allocates memory from kernel heap") + KAPI_LOCK_NOT_REQUIRED("Any lock") + KAPI_END_SPEC + + void *kmalloc(size_t size, gfp_t flags) + { + /* Implementation */ + } + +System Call Specification +------------------------- + +System calls use specialized macros: + +.. code-block:: c + + KAPI_DEFINE_SYSCALL_SPEC(open_spec, open, "1.0") + KAPI_DESCRIPTION("Open a file") + KAPI_PARAM(0, pathname, KAPI_TYPE_USER_STRING, KAPI_DIR_IN, + "Path to file") + KAPI_PARAM_PATH(0, PATH_MAX) + KAPI_PARAM(1, flags, KAPI_TYPE_FLAGS, KAPI_DIR_IN, + "Open flags (O_*)") + KAPI_PARAM(2, mode, KAPI_TYPE_MODE_T, KAPI_DIR_IN, + "File permissions (if creating)") + KAPI_RETURN(KAPI_TYPE_INT, "File descriptor or -1") + KAPI_ERROR(EACCES, "Permission denied") + KAPI_ERROR(ENOENT, "File does not exist") + KAPI_ERROR(EMFILE, "Too many open files") + KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) + KAPI_SIGNAL(EINTR, "Open can be interrupted by signal") + KAPI_END_SYSCALL_SPEC + +IOCTL Specification +------------------- + +IOCTLs have extended support for structure validation: + +.. code-block:: c + + KAPI_DEFINE_IOCTL_SPEC(vidioc_querycap_spec, VIDIOC_QUERYCAP, + "VIDIOC_QUERYCAP", + sizeof(struct v4l2_capability), + sizeof(struct v4l2_capability), + "video_fops") + KAPI_DESCRIPTION("Query device capabilities") + KAPI_IOCTL_FIELD(driver, KAPI_TYPE_CHAR_ARRAY, KAPI_DIR_OUT, + "Driver name", 16) + KAPI_IOCTL_FIELD(card, KAPI_TYPE_CHAR_ARRAY, KAPI_DIR_OUT, + "Device name", 32) + KAPI_IOCTL_FIELD(version, KAPI_TYPE_U32, KAPI_DIR_OUT, + "Driver version") + KAPI_IOCTL_FIELD(capabilities, KAPI_TYPE_FLAGS, KAPI_DIR_OUT, + "Device capabilities") + KAPI_END_IOCTL_SPEC + +Runtime Validation +================== + +Enabling Validation +------------------- + +Runtime validation is controlled by kernel configuration: + +1. Enable ``CONFIG_KAPI_SPEC`` to build the framework +2. Enable ``CONFIG_KAPI_RUNTIME_CHECKS`` for runtime validation +3. Optionally enable ``CONFIG_KAPI_SPEC_DEBUGFS`` for debugfs interface + +Validation Modes +---------------- + +The framework supports several validation modes: + +.. code-block:: c + + /* Enable validation for specific API */ + kapi_enable_validation("kmalloc"); + + /* Enable validation for all APIs */ + kapi_enable_all_validation(); + + /* Set validation level */ + kapi_set_validation_level(KAPI_VALIDATE_FULL); + +Validation Levels: + +- ``KAPI_VALIDATE_NONE``: No validation +- ``KAPI_VALIDATE_BASIC``: Type and NULL checks only +- ``KAPI_VALIDATE_NORMAL``: Basic + range and constraint checks +- ``KAPI_VALIDATE_FULL``: All checks including custom validators + +Custom Validators +----------------- + +APIs can register custom validation functions: + +.. code-block:: c + + static bool validate_buffer_size(const struct kapi_param_spec *spec, + const void *value, void *context) + { + size_t size = *(size_t *)value; + struct my_context *ctx = context; + + return size > 0 && size <= ctx->max_buffer_size; + } + + KAPI_PARAM_CUSTOM_VALIDATOR(0, validate_buffer_size) + +DebugFS Interface +================= + +The debugfs interface provides runtime access to API specifications: + +Directory Structure +------------------- + +:: + + /sys/kernel/debug/kapi/ + ├── apis/ # All registered APIs + │ ├── kmalloc/ + │ │ ├── specification # Human-readable spec + │ │ ├── json # JSON format + │ │ └── xml # XML format + │ └── open/ + │ └── ... + ├── summary # Overview of all APIs + ├── validation/ # Validation controls + │ ├── enabled # Global enable/disable + │ ├── level # Validation level + │ └── stats # Validation statistics + └── export/ # Bulk export options + ├── all.json # All specs in JSON + └── all.xml # All specs in XML + +Usage Examples +-------------- + +Query specific API:: + + $ cat /sys/kernel/debug/kapi/apis/kmalloc/specification + API: kmalloc + Version: 3.0 + Description: Allocate kernel memory + + Parameters: + [0] size (size_t, in): Number of bytes to allocate + Range: 0 - 4194304 + [1] flags (flags, in): Allocation flags (GFP_*) + Mask: 0x1ffffff + + Returns: pointer - Pointer to allocated memory or NULL + + Errors: + ENOMEM: Out of memory + + Context: process, softirq, hardirq + + Side Effects: + - Allocates memory from kernel heap + +Export all specifications:: + + $ cat /sys/kernel/debug/kapi/export/all.json > kernel-apis.json + +Enable validation for specific API:: + + $ echo 1 > /sys/kernel/debug/kapi/apis/kmalloc/validate + +Performance Considerations +========================== + +Memory Overhead +--------------- + +Each API specification consumes approximately 2-4KB of memory. With thousands +of kernel APIs, this can add up to several megabytes. Consider: + +1. Building with ``CONFIG_KAPI_SPEC=n`` for production kernels +2. Using ``__init`` annotations for APIs only used during boot +3. Implementing lazy loading for rarely used specifications + +Runtime Overhead +---------------- + +When ``CONFIG_KAPI_RUNTIME_CHECKS`` is enabled: + +- Each validated API call adds 50-200ns overhead +- Complex validations (custom validators) may add more +- Use validation only in development/testing kernels + +Optimization Strategies +----------------------- + +1. **Compile-time optimization**: When validation is disabled, all + validation code is optimized away by the compiler. + +2. **Selective validation**: Enable validation only for specific APIs + or subsystems under test. + +3. **Caching**: The framework caches validation results for repeated + calls with identical parameters. + +Documentation Generation +------------------------ + +The framework exports specifications via debugfs that can be used +to generate documentation. Tools for automatic documentation generation +from specifications are planned for future development. + +IDE Integration +--------------- + +Modern IDEs can use the JSON export for: + +- Parameter hints +- Type checking +- Context validation +- Error code documentation + +Testing Framework +----------------- + +The framework includes test helpers:: + + #ifdef CONFIG_KAPI_TESTING + /* Verify API behaves according to specification */ + kapi_test_api("kmalloc", test_cases); + #endif + +Best Practices +============== + +Writing Specifications +---------------------- + +1. **Be Comprehensive**: Document all parameters, errors, and side effects +2. **Keep Updated**: Update specs when API behavior changes +3. **Use Examples**: Include usage examples in descriptions +4. **Validate Constraints**: Define realistic constraints for parameters +5. **Document Context**: Clearly specify allowed execution contexts + +Maintenance +----------- + +1. **Version Specifications**: Increment version when API changes +2. **Deprecation**: Mark deprecated APIs and suggest replacements +3. **Cross-reference**: Link related APIs in descriptions +4. **Test Specifications**: Verify specs match implementation + +Common Patterns +--------------- + +**Optional Parameters**:: + + KAPI_PARAM(2, optional_arg, KAPI_TYPE_POINTER, KAPI_DIR_IN, + "Optional argument (may be NULL)") + KAPI_PARAM_OPTIONAL(2) + +**Variable Arguments**:: + + KAPI_PARAM(1, fmt, KAPI_TYPE_FORMAT_STRING, KAPI_DIR_IN, + "Printf-style format string") + KAPI_PARAM_VARIADIC(2, "Format arguments") + +**Callback Functions**:: + + KAPI_PARAM(1, callback, KAPI_TYPE_FUNCTION_PTR, KAPI_DIR_IN, + "Callback function") + KAPI_PARAM_CALLBACK(1, "int (*)(void *data)", "data") + +Troubleshooting +=============== + +Common Issues +------------- + +**Specification Not Found**:: + + kernel: KAPI: Specification for 'my_api' not found + + Solution: Ensure KAPI_DEFINE_SPEC is in the same translation unit + as the function implementation. + +**Validation Failures**:: + + kernel: KAPI: Validation failed for kmalloc parameter 'size': + value 5242880 exceeds maximum 4194304 + + Solution: Check parameter constraints or adjust specification if + the constraint is incorrect. + +**Build Errors**:: + + error: 'KAPI_TYPE_UNKNOWN' undeclared + + Solution: Include <linux/kernel_api_spec.h> and ensure + CONFIG_KAPI_SPEC is enabled. + +Debug Options +------------- + +Enable verbose debugging:: + + echo 8 > /proc/sys/kernel/printk + echo 1 > /sys/kernel/debug/kapi/debug/verbose + +Future Directions +================= + +Planned Features +---------------- + +1. **Automatic Extraction**: Tool to extract specifications from existing + kernel-doc comments + +2. **Contract Verification**: Static analysis to verify implementation + matches specification + +3. **Performance Profiling**: Measure actual API performance against + documented expectations + +4. **Fuzzing Integration**: Use specifications to guide intelligent + fuzzing of kernel APIs + +5. **Version Compatibility**: Track API changes across kernel versions + +Research Areas +-------------- + +1. **Formal Verification**: Use specifications for mathematical proofs + of correctness + +2. **Runtime Monitoring**: Detect specification violations in production + with minimal overhead + +3. **API Evolution**: Analyze how kernel APIs change over time + +4. **Security Applications**: Use specifications for security policy + enforcement + +Contributing +============ + +Submitting Specifications +------------------------- + +1. Add specifications to the same file as the API implementation +2. Follow existing patterns and naming conventions +3. Test with CONFIG_KAPI_RUNTIME_CHECKS enabled +4. Verify debugfs output is correct +5. Run scripts/checkpatch.pl on your changes + +Review Criteria +--------------- + +Specifications will be reviewed for: + +1. **Completeness**: All parameters and errors documented +2. **Accuracy**: Specification matches implementation +3. **Clarity**: Descriptions are clear and helpful +4. **Consistency**: Follows framework conventions +5. **Performance**: No unnecessary runtime overhead + +Contact +------- + +- Maintainer: Sasha Levin <[email protected]>
MAINTAINERS +9 -0
@@ -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
@@ -102,6 +102,9 @@ SECTIONS init.data : { INIT_DATA } __init_end = .; + /* Kernel API specifications in dedicated section */ + KAPI_SPECS_SECTION() + /* Ensure the __preinit_array_start label is properly aligned. We could instead move the label definition inside the section, but the linker would then create the section even if it turns out to
arch/um/kernel/uml.lds.S +3 -0
@@ -74,6 +74,9 @@ SECTIONS init.data : { INIT_DATA } __init_end = .; + /* Kernel API specifications in dedicated section */ + KAPI_SPECS_SECTION() + .data : { INIT_TASK_DATA(KERNEL_STACK_SIZE)
arch/x86/kernel/vmlinux.lds.S +3 -0
@@ -173,6 +173,9 @@ SECTIONS RO_DATA(PAGE_SIZE) X86_ALIGN_RODATA_END + /* Kernel API specifications in dedicated section */ + KAPI_SPECS_SECTION() + /* Data */ .data : AT(ADDR(.data) - LOAD_OFFSET) { /* Start of data section */
include/asm-generic/vmlinux.lds.h +20 -0
@@ -279,6 +279,26 @@ defined(CONFIG_AUTOFDO_CLANG) || defined(CONFIG_PROPELLER_CLANG)#define TRACE_SYSCALLS ()#endif +#ifdef CONFIG_KAPI_SPEC +#define KAPI_SPECS () \ + . = ALIGN(8); \ + __start_kapi_specs = .; \ + KEEP(*(.kapi_specs)) \ + __stop_kapi_specs = .; + +/* For placing KAPI specs in a dedicated section */ +#define KAPI_SPECS_SECTION () \ + .kapi_specs : AT(ADDR(.kapi_specs) - LOAD_OFFSET) { \ + . = ALIGN(8); \ + __start_kapi_specs = .; \ + KEEP(*(.kapi_specs)) \ + __stop_kapi_specs = .; \ + } +#else +#define KAPI_SPECS () +#define KAPI_SPECS_SECTION () +#endif +#ifdef CONFIG_BPF_EVENTS #define BPF_RAW_TP () STRUCT_ALIGN(); \ BOUNDED_SECTION_BY(__bpf_raw_tp_map, __bpf_raw_tp)
include/linux/kernel_api_spec.h new file +1513 -0
1,513 lines not on this page · raw message
include/linux/syscall_api_spec.h new file +137 -0
138 lines not on this page · raw message
include/linux/syscalls.h +38 -0
@@ -87,6 +87,7 @@ struct xattr_args;#include <linux/bug.h> #include <linux/sem.h> #include <asm/siginfo.h> +#include <linux/syscall_api_spec.h> #include <linux/unistd.h> #include <linux/quota.h> #include <linux/key.h>
@@ -132,6 +133,7 @@ struct xattr_args;#define __SC_TYPE (t, a) t#define __SC_ARGS (t, a) a#define __SC_TEST (t, a) (void)BUILD_BUG_ON_ZERO(!__TYPE_IS_LL(t) && sizeof(t) > sizeof(long)) +#define __SC_CAST_TO_S64 (t, a) (s64)(a)#ifdef CONFIG_FTRACE_SYSCALLS #define __SC_STR_ADECL (t, a) #a
@@ -242,6 +244,41 @@ static inline int is_syscall_trace_event(struct trace_event_call *tp_event)* done within __do_sys_*(). */ #ifndef __SYSCALL_DEFINEx +#ifdef CONFIG_KAPI_RUNTIME_CHECKS +#define __SYSCALL_DEFINEx (x, name, ...) \ + __diag_push(); \ + __diag_ignore(GCC, 8, "-Wattribute-alias", \ + "Type aliasing is used to sanitize syscall arguments");\ + asmlinkage long sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)) \ + __attribute__((alias(__stringify(__se_sys##name)))); \ + ALLOW_ERROR_INJECTION(sys##name, ERRNO); \ + static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__));\ + static inline long __do_kapi_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)); \ + asmlinkage long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__)); \ + asmlinkage long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__)) \ + { \ + long ret = __do_kapi_sys##name(__MAP(x,__SC_CAST,__VA_ARGS__));\ + __MAP(x,__SC_TEST,__VA_ARGS__); \ + __PROTECT(x, ret,__MAP(x,__SC_ARGS,__VA_ARGS__)); \ + return ret; \ + } \ + __diag_pop(); \ + static inline long __do_kapi_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__))\ + { \ + const struct kernel_api_spec *__spec = kapi_get_spec("sys_" #name); \ + if (__spec) { \ + s64 __params[x] = { __MAP(x,__SC_CAST_TO_S64,__VA_ARGS__) }; \ + int __ret = kapi_validate_syscall_params(__spec, __params, x); \ + if (__ret) return __ret; \ + } \ + long ret = __do_sys##name(__MAP(x,__SC_ARGS,__VA_ARGS__)); \ + if (__spec) { \ + kapi_validate_syscall_return(__spec, (s64)ret); \ + } \ + return ret; \ + } \ + static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)) +#else /* !CONFIG_KAPI_RUNTIME_CHECKS */ #define __SYSCALL_DEFINEx (x, name, ...) \ __diag_push(); \ __diag_ignore(GCC, 8, "-Wattribute-alias", \
@@ -260,6 +297,7 @@ static inline int is_syscall_trace_event(struct trace_event_call *tp_event) } \__diag_pop (); \ static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)) +#endif /* CONFIG_KAPI_RUNTIME_CHECKS */ #endif /* __SYSCALL_DEFINEx */ /* For split 64-bit arguments on 32-bit architectures */
init/Kconfig +2 -0
@@ -2079,6 +2079,8 @@ config TRACEPOINTS source "kernel/Kconfig.kexec" +source "kernel/api/Kconfig" + endmenu # General setup source "arch/Kconfig"
kernel/Makefile +1 -0
@@ -56,6 +56,7 @@ obj-y += livepatch/ obj-y += dma/ obj-y += entry/ obj-$(CONFIG_MODULES) += module/ +obj-$(CONFIG_KAPI_SPEC) += api/ obj-$(CONFIG_KCMP) += kcmp.o obj-$(CONFIG_FREEZER) += freezer.o
kernel/api/Kconfig new file +35 -0
@@ -0,0 +1,35 @@ +# SPDX-License-Identifier: GPL-2.0-only +# +# Kernel API Specification Framework Configuration +# + +config KAPI_SPEC + bool "Kernel API Specification Framework" + help + This option enables the kernel API specification framework, + which provides formal documentation of kernel APIs in both + human and machine-readable formats. + + The framework allows developers to document APIs inline with + their implementation, including parameter specifications, + return values, error conditions, locking requirements, and + execution context constraints. + + When enabled, API specifications can be queried at runtime + and exported in various formats (JSON, XML) through debugfs. + + If unsure, say N. + +config KAPI_RUNTIME_CHECKS + bool "Runtime API specification checks" + depends on KAPI_SPEC + depends on DEBUG_KERNEL + help + Enable runtime validation of API usage against specifications. + This includes checking execution context requirements, parameter + validation, and lock state verification. + + This adds overhead and should only be used for debugging and + development. The checks use WARN_ONCE to report violations. + + If unsure, say N.
kernel/api/Makefile new file +7 -0
@@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Makefile for the Kernel API Specification Framework +# + +# Core API specification framework +obj-$(CONFIG_KAPI_SPEC) += kernel_api_spec.o
kernel/api/kernel_api_spec.c new file +1122 -0
654 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.
Jonathan Corbet
maintainerRe: [RFC v2 01/22] kernel/api: introduce kernel API specification framework
Quoted 16 lines · Sasha Levin
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 callsThe 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 existingSYSCALL_DEFINEmacros
Quoted 7 lines
This commit introduces the core infrastructure without modifying any existing APIs. Subsequent patches will add specifications to individual subsystems.
Signed-off-by Sasha Levin <[email protected]>--- Documentation/admin-guide/kernel-api-spec.rst | 507 ++++++
You need to add that file to index.rst in that directory or it won't be pulled into the docs build.
Wouldn't it be nice to integrate all this stuff with out existing kerneldoc mechanism...? :)
Thanks,
jon
Re: [RFC v2 01/22] kernel/api: introduce kernel API specification framework
Em Mon, 30 Jun 2025 13:53:55 -0600
Jonathan Corbet <[email protected]> escreveu:
Quoted 26 lines
Quoted 16 lines · Sasha Levin
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 callsThe 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 existingSYSCALL_DEFINEmacrosQuoted 7 lines
This commit introduces the core infrastructure without modifying any existing APIs. Subsequent patches will add specifications to individual subsystems.
Signed-off-by Sasha Levin <[email protected]>--- Documentation/admin-guide/kernel-api-spec.rst | 507 ++++++
Quoted 5 lines
You need to add that file to
index.rstin that directory or it won't be pulled into the docs build.Wouldn't it be nice to integrate all this stuff with out existing kerneldoc mechanism...? :)
+1
Having two different mechanisms (kapi and kerneldoc) makes a lot harder to maintain kAPI.
Also, IGT (a testing tool for DRM subsystem) used to have a macro based documentation system. It got outdated with time, as people ends forgetting to update the macros when changing the code. Also, sometimes we want to add some rich text there, with graphs, tables, ...
More important than that: people end not remembering to add such macros. As kerneldoc markups are similar to Doxygen and normal C comments, it is more likely that people will remember.
So, IMO the best would be to use kerneldoc syntax there, letting Kerneldoc Sphinx extension handling it for docs, while having tools to implement the other features you mentioned.
Thanks,
Mauro
Re: [RFC v2 01/22] kernel/api: introduce kernel API specification framework
Quoted 32 lines · Mauro Carvalho Chehab
Em Mon, 30 Jun 2025 13:53:55 -0600
Jonathan Corbet <[email protected]> escreveu:Quoted 29 lines
Quoted 16 lines · Sasha Levin
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 callsThe 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 existingSYSCALL_DEFINEmacrosQuoted 7 lines
This commit introduces the core infrastructure without modifying any existing APIs. Subsequent patches will add specifications to individual subsystems.
Signed-off-by Sasha Levin <[email protected]>--- Documentation/admin-guide/kernel-api-spec.rst | 507 ++++++You need to add that file to
index.rstin that directory or it won't be pulled into the docs build.
Quoted 7 lines
Quoted 2 lines
Wouldn't it be nice to integrate all this stuff with out existing kerneldoc mechanism...? :)
+1
Having two different mechanisms (kapi and kerneldoc) makes a lot harder to maintain kAPI.
I hated the idea of not reusing kerneldoc.
My concern with kerneldoc was that I can't manipulate the information it stores in the context of a kernel build. So for example, I wasn't sure how I can expose information stored within kerneldoc via debugfs on a running system (or how I can store it within the vmlinux for later extraction from the binary built kernel).
I did some research based on your proposal, and I think I was incorrect with the assumption above. I suppose we could do something like the following:
1. Add new section patterns to doc_sect regex in to include API specification sections: api-type, api-version, param-type, param-flags, param-constraint, error-code, capability, signal, lock-req, since...
2. Create new output module (scripts/lib/kdoc/kdoc_apispec.py?) to generate C macro invocations from parsed data.
Which will generate output like:
DEFINE_KERNEL_API_SPEC(function_name)
KAPI_DESCRIPTION("...")
KAPI_PARAM(0, "name", "type", "desc")
KAPI_PARAM_TYPE(KAPI_TYPE_INT)
KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
KAPI_PARAM_END KAPI_END_SPEC
3. And then via makefile we can:
- Generate API specs from kerneldoc comments
- Include generated specs conditionally based on CONFIG_KERNEL_API_SPEC
Allowing us to just have these in the relevant source files:
#ifdef CONFIG_KERNEL_API_SPEC
#include "socket.apispec.h"
#endif
In theory, all of that will let us have something like the following in kerneldoc:
- @api-type: syscall
- @api-version: 1
- @context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE
- @param-type: family, KAPI_TYPE_INT
- @param-flags: family, KAPI_PARAM_IN
- @param-range: family, 0, 45
- @param-mask: type, SOCK_TYPE_MASK | SOCK_CLOEXEC | SOCK_NONBLOCK
- @error-code: -EAFNOSUPPORT, "Address family not supported"
- @error-condition: -EAFNOSUPPORT, "family < 0 || family >= NPROTO"
- @capability: CAP_NET_RAW, KAPI_CAP_GRANT_PERMISSION
- @capability-allows: CAP_NET_RAW, "Create SOCK_RAW sockets"
- @since: 2.0
- @return-type: KAPI_TYPE_FD
- @return-check: KAPI_RETURN_ERROR_CHECK
How does it sound? I'm pretty excited about the possiblity to align this with kerneldoc. Please poke holes in the plan :)
Signature · 2 lines
Thanks, Sasha
Re: [RFC v2 01/22] kernel/api: introduce kernel API specification framework
Em Tue, 1 Jul 2025 10:23:03 -0400
Sasha Levin <[email protected]> escreveu:
Quoted 98 lines · Mauro Carvalho Chehab
Quoted 32 lines
Em Mon, 30 Jun 2025 13:53:55 -0600
Jonathan Corbet <[email protected]> escreveu:Quoted 29 lines
Quoted 16 lines · Sasha Levin
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 callsThe 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 existingSYSCALL_DEFINEmacrosQuoted 7 lines
This commit introduces the core infrastructure without modifying any existing APIs. Subsequent patches will add specifications to individual subsystems.
Signed-off-by Sasha Levin <[email protected]>--- Documentation/admin-guide/kernel-api-spec.rst | 507 ++++++You need to add that file to
index.rstin that directory or it won't be pulled into the docs build.Quoted 7 lines
Quoted 2 lines
Wouldn't it be nice to integrate all this stuff with out existing kerneldoc mechanism...? :)
+1
Having two different mechanisms (kapi and kerneldoc) makes a lot harder to maintain kAPI.
I hated the idea of not reusing kerneldoc.
My concern with kerneldoc was that I can't manipulate the information it stores in the context of a kernel build. So for example, I wasn't sure how I can expose information stored within kerneldoc via debugfs on a running system (or how I can store it within the vmlinux for later extraction from the binary built kernel).
I did some research based on your proposal, and I think I was incorrect with the assumption above. I suppose we could do something like the following:
1. Add new section patterns to
doc_sectregex in to include API specification sections: api-type, api-version, param-type, param-flags, param-constraint, error-code, capability, signal, lock-req, since...2. Create new output module (
scripts/lib/kdoc/kdoc_apispec.py?) to generate C macro invocations from parsed data.Which will generate output like:
DEFINE_KERNEL_API_SPEC(function_name) KAPI_DESCRIPTION("...") KAPI_PARAM(0, "name", "type", "desc") KAPI_PARAM_TYPE(KAPI_TYPE_INT) KAPI_PARAM_FLAGS(KAPI_PARAM_IN) KAPI_PARAM_END KAPI_END_SPEC3. And then via makefile we can:
- Generate API specs from kerneldoc comments
- Include generated specs conditionally based onCONFIG_KERNEL_API_SPECAllowing us to just have these in the relevant source files:
#ifdef CONFIG_KERNEL_API_SPEC #include "socket.apispec.h" #endifIn theory, all of that will let us have something like the following in kerneldoc:
- @api-type: syscall
- @api-version: 1
- @context-flags:KAPI_CTX_PROCESS|KAPI_CTX_SLEEPABLE
- @param-type: family,KAPI_TYPE_INT
- @param-flags: family,KAPI_PARAM_IN
- @param-range: family, 0, 45
- @param-mask: type,SOCK_TYPE_MASK|SOCK_CLOEXEC|SOCK_NONBLOCK
- @error-code:-EAFNOSUPPORT, "Address family not supported"
- @error-condition:-EAFNOSUPPORT, "family < 0 || family >= NPROTO"
- @capability:CAP_NET_RAW,KAPI_CAP_GRANT_PERMISSION
- @capability-allows:CAP_NET_RAW, "CreateSOCK_RAWsockets"
- @since: 2.0
- @return-type:KAPI_TYPE_FD
- @return-check:KAPI_RETURN_ERROR_CHECK
Quoted 2 lines
How does it sound? I'm pretty excited about the possiblity to align this with kerneldoc. Please poke holes in the plan :)
Sounds like a plan!
We did something somewhat similar on IGT.
The python classes there were written with the goal to document tests, so its examples are related to test docs, but I wrote it to be generic.
There, all fields comes form a JSON file like this:
which describes what fields will be used. It also lists file patterns that will use it. The fields allow hierarchical grouping, with could be interesting for some types of fields.
From the json example (I dropped the optional field description from the example, to make it cleaner):
"Category": {
"Mega feature": {
"Sub-category": {},
}
...
"Test category": {},
"Issue": {},
...The hierarchical part is useful to properly order kapi content without the need to add multiple Sphinx markups to manually reorder the output inside the .rst files.
(*) I would avoid hardcoding the fields/structures, as eventually
we may need more flexibility to add fields and/or having some fields that are specific, for instance, to debugfs or sysfs.
The python class it uses is at:
https://gitlab.freedesktop.org/drm/igt-gpu-tools/-/blob/master/scripts/test_list.py?ref_type=heads
and caller is at:
https://gitlab.freedesktop.org/drm/igt-gpu-tools/-/blob/master/scripts/igt_doc.py?ref_type=heads
Eventually you may find something useful there. If so, feel free to pick from it.
Regards,
Mauro
Jonathan Corbet
maintainerRe: [RFC v2 01/22] kernel/api: introduce kernel API specification framework
In reply to Sasha Levin[Adding some of the ELISA folks, who are working in a related area and might have thoughts on this. You can find the patch series under discussion at:
https://lore.kernel.org/all/[email protected]
]
Quoted 3 lines · Sasha Levin
1. Add new section patterns to
doc_sectregex in to include API specification sections: api-type, api-version, param-type, param-flags, param-constraint, error-code, capability, signal, lock-req, since...
Easily enough done - you can never have too many regexes :)
Quoted 5 lines
2. Create new output module (
scripts/lib/kdoc/kdoc_apispec.py?) to generate C macro invocations from parsed data.Which will generate output like:
Quoted 7 lines
DEFINE_KERNEL_API_SPEC(function_name)
KAPI_DESCRIPTION("...")
KAPI_PARAM(0, "name", "type", "desc")
KAPI_PARAM_TYPE(KAPI_TYPE_INT)
KAPI_PARAM_FLAGS(KAPI_PARAM_IN)
KAPI_PARAM_END
KAPI_END_SPEC Also shouldn't be all that hard.
Quoted 8 lines
3. And then via makefile we can:
- Generate API specs from kerneldoc comments
- Include generated specs conditionally based onCONFIG_KERNEL_API_SPECAllowing us to just have these in the relevant source files:
#ifdef CONFIG_KERNEL_API_SPEC #include "socket.apispec.h" #endif
...seems like it should work.
Quoted 18 lines
In theory, all of that will let us have something like the following in kerneldoc:
- @api-type: syscall
- @api-version: 1
- @context-flags:KAPI_CTX_PROCESS|KAPI_CTX_SLEEPABLE
- @param-type: family,KAPI_TYPE_INT
- @param-flags: family,KAPI_PARAM_IN
- @param-range: family, 0, 45
- @param-mask: type,SOCK_TYPE_MASK|SOCK_CLOEXEC|SOCK_NONBLOCK
- @error-code:-EAFNOSUPPORT, "Address family not supported"
- @error-condition:-EAFNOSUPPORT, "family < 0 || family >= NPROTO"
- @capability:CAP_NET_RAW,KAPI_CAP_GRANT_PERMISSION
- @capability-allows:CAP_NET_RAW, "CreateSOCK_RAWsockets"
- @since: 2.0
- @return-type:KAPI_TYPE_FD
- @return-check:KAPI_RETURN_ERROR_CHECK
Quoted 2 lines
How does it sound? I'm pretty excited about the possiblity to align this with kerneldoc. Please poke holes in the plan :)
I think we could do it without all the @signs. We'd also want to see how well we could integrate that information with the minimal structure we already have: getting the return-value information into the Returns:
section, for example, and tying the parameter constraints to the parameter descriptions we already have.
The other thing I would really like to see, to the extent we can, is that a bunch of patches adding all this data to the source will actually be accepted by the relevant maintainers. It would be a shame to get all this infrastructure into place, then have things stall out due to maintainer pushback. Maybe you should start by annotating the scheduler-related system calls; if that works the rest should be a piece of cake :)
Thanks,
jon
Re: [RFC v2 01/22] kernel/api: introduce kernel API specification framework
Quoted 5 lines · Jonathan Corbet
[Adding some of the ELISA folks, who are working in a related area and might have thoughts on this. You can find the patch series under discussion at:
Yup, we all met at OSS and reached the conclusion that we should lean towards a machine readable spec, which we thought was closer to my proposal than the kerneldoc work.
However, with your suggestion, I think it makes more sense to go back to kerneldoc as that can be made machine readable.
Quoted 18 lines
Quoted 18 lines
In theory, all of that will let us have something like the following in kerneldoc:
- @api-type: syscall
- @api-version: 1
- @context-flags:KAPI_CTX_PROCESS|KAPI_CTX_SLEEPABLE
- @param-type: family,KAPI_TYPE_INT
- @param-flags: family,KAPI_PARAM_IN
- @param-range: family, 0, 45
- @param-mask: type,SOCK_TYPE_MASK|SOCK_CLOEXEC|SOCK_NONBLOCK
- @error-code:-EAFNOSUPPORT, "Address family not supported"
- @error-condition:-EAFNOSUPPORT, "family < 0 || family >= NPROTO"
- @capability:CAP_NET_RAW,KAPI_CAP_GRANT_PERMISSION
- @capability-allows:CAP_NET_RAW, "CreateSOCK_RAWsockets"
- @since: 2.0
- @return-type:KAPI_TYPE_FD
- @return-check:KAPI_RETURN_ERROR_CHECK
Quoted 8 lines
Quoted 2 lines
How does it sound? I'm pretty excited about the possiblity to align this with kerneldoc. Please poke holes in the plan :)
I think we could do it without all the @signs. We'd also want to see how well we could integrate that information with the minimal structure we already have: getting the return-value information into the Returns:
section, for example, and tying the parameter constraints to the parameter descriptions we already have.
Right!
So I have a proof of concept which during the build process creates .apispec.h which are generated from kerneldoc and contain macros identical to the ones in my RFC.
Here's an example of sys_mlock() spec:
/**
* sys_mlock - Lock pages in memory
* @start: Starting address of memory range to lock
* @len: Length of memory range to lock in bytes
*
* 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.
*
* long-desc: Locks pages in the specified address range into RAM, preventing
* them from being paged to swap. Requires CAP_IPC_LOCK capability
* or RLIMIT_MEMLOCK resource limit.
* context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE
* param-type: start, KAPI_TYPE_UINT
* param-flags: start, KAPI_PARAM_IN
* param-constraint-type: start, KAPI_CONSTRAINT_NONE
* param-constraint: start, Rounded down to page boundary
* param-type: len, KAPI_TYPE_UINT
* param-flags: len, KAPI_PARAM_IN
* param-constraint-type: len, KAPI_CONSTRAINT_RANGE
* param-range: len, 0, LONG_MAX
* param-constraint: len, Rounded up to page boundary
* return-type: KAPI_TYPE_INT
* return-check-type: KAPI_RETURN_ERROR_CHECK
* return-success: 0
* error-code: -ENOMEM, ENOMEM, Address range issue,
* Some of the specified range is not mapped, has unmapped gaps,
* or the lock would cause the number of mapped regions to exceed the limit.
* error-code: -EPERM, EPERM, Insufficient privileges,
* The caller is not privileged (no CAP_IPC_LOCK) and RLIMIT_MEMLOCK is 0.
* error-code: -EINVAL, EINVAL, Address overflow,
* The result of the addition start+len was less than start (arithmetic overflow).
* error-code: -EAGAIN, EAGAIN, Some or all memory could not be locked,
* Some or all of the specified address range could not be locked.
* error-code: -EINTR, EINTR, Interrupted by signal,
* The operation was interrupted by a fatal signal before completion.
* error-code: -EFAULT, EFAULT, Bad address,
* The specified address range contains invalid addresses that cannot be accessed.
* since-version: 2.0
* lock: mmap_lock, KAPI_LOCK_RWLOCK
* lock-acquired: true
* lock-released: true
* lock-desc: Process memory map write lock
* signal: FATAL
* signal-direction: KAPI_SIGNAL_RECEIVE
* signal-action: KAPI_SIGNAL_ACTION_RETURN
* signal-condition: Fatal signal pending
* signal-desc: Fatal signals (SIGKILL) can interrupt the operation at two points:
* when acquiring mmap_write_lock_killable() and during page population * in __mm_populate(). Returns -EINTR. Non-fatal signals do NOT interrupt * mlock - the operation continues even if SIGINT/SIGTERM are received. * signal-error: -EINTR * signal-timing: KAPI_SIGNAL_TIME_DURING * signal-priority: 0 * signal-interruptible: yes * signal-state-req: KAPI_SIGNAL_STATE_RUNNING * examples: mlock(addr, 4096); // Lock one page * mlock(addr, len); // Lock range of pages * notes: Memory locks do not stack - multiple calls on the same range can be * undone by a single munlock. Locks are not inherited by child processes. * Pages are locked on whole page boundaries. Commonly used by real-time * applications to prevent page faults during time-critical operations. * Also used for security to prevent sensitive data (e.g., cryptographic keys) * from being written to swap. Note: locked pages may still be saved to * swap during system suspend/hibernate. * * Tagged addresses are automatically handled via untagged_addr(). The operation * occurs in two phases: first VMAs are marked with VM_LOCKED, then pages are * populated into memory. When checking RLIMIT_MEMLOCK, the kernel optimizes * by recounting locked memory to avoid double-counting overlapping regions.
* side-effect: KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_ALLOC_MEMORY, process memory, Locks pages into physical memory, preventing swapping, reversible=yes
* side-effect: KAPI_EFFECT_MODIFY_STATE, mm->locked_vm, Increases process locked memory counter, reversible=yes
* side-effect: KAPI_EFFECT_ALLOC_MEMORY, physical pages, May allocate and populate page table entries, condition=Pages not already present, reversible=yes
* side-effect: KAPI_EFFECT_MODIFY_STATE | KAPI_EFFECT_ALLOC_MEMORY, page faults, Triggers page faults to bring pages into memory, condition=Pages not already resident
* side-effect: KAPI_EFFECT_MODIFY_STATE, VMA splitting, May split existing VMAs at lock boundaries, condition=Lock range partially overlaps existing VMA
* state-trans: memory pages, swappable, locked in RAM, Pages become non-swappable and pinned in physical memory
* state-trans: VMA flags, unlocked, VM_LOCKED set, Virtual memory area marked as locked
* capability: CAP_IPC_LOCK, KAPI_CAP_BYPASS_CHECK, CAP_IPC_LOCK capability
* capability-allows: Lock unlimited amount of memory (no RLIMIT_MEMLOCK enforcement)
* capability-without: Must respect RLIMIT_MEMLOCK resource limit
* capability-condition: Checked when RLIMIT_MEMLOCK is 0 or locking would exceed limit
* capability-priority: 0
* constraint: RLIMIT_MEMLOCK Resource Limit, The RLIMIT_MEMLOCK soft resource limit specifies the maximum bytes of memory that may be locked into RAM. Unprivileged processes are restricted to this limit. CAP_IPC_LOCK capability allows bypassing this limit entirely. The limit is enforced per-process, not per-user.
* constraint-expr: RLIMIT_MEMLOCK Resource Limit, locked_memory + request_size <= RLIMIT_MEMLOCK || CAP_IPC_LOCK
* constraint: Memory Pressure and OOM, Locking large amounts of memory can cause system-wide memory pressure and potentially trigger the OOM killer. The kernel does not prevent locking memory that would destabilize the system.
* constraint: Special Memory Areas, Some memory types cannot be locked or are silently skipped: VM_IO/VM_PFNMAP areas (device mappings) are skipped; Hugetlb pages are inherently pinned and skipped; DAX mappings are always present in memory and skipped; Secret memory (memfd_secret) mappings are skipped; VM_DROPPABLE memory cannot be locked and is skipped; Gate VMA (kernel entry point) is skipped; VM_LOCKED areas are already locked. These special areas are silently excluded without error. *
* Context: Process context. May sleep. Takes mmap_lock for write.
*
* Return: 0 on success, negative error code on failure
*/
Quoted 7 lines
The other thing I would really like to see, to the extent we can, is that a bunch of patches adding all this data to the source will actually be accepted by the relevant maintainers. It would be a shame to get all this infrastructure into place, then have things stall out due to maintainer pushback. Maybe you should start by annotating the scheduler-related system calls; if that works the rest should be a piece of cake :)
In the RFC I've sent out I've specced out API from different subsystems to solicit some feedback on those, but so fair it's been quiet.
I'll resend a "lean" RFC v3 with just the base macro spec infra + kerneldoc support + "tricker" sched API + "trickier" mm API.
I'm thinking that if it's still quiet in a month or two I'll propose a talk at LPC around it, or maybe try and feedback/consensus during maintainer's summit.
But yes, it doesn't make sense to take it in until we have an ack from a few larger subsystems.
Signature · 2 lines
Thanks, Sasha
Jonathan Corbet
maintainerRe: [RFC v2 01/22] kernel/api: introduce kernel API specification framework
Quoted 5 lines · Sasha Levin
So I have a proof of concept which during the build process creates
.apispec.hwhich are generated from kerneldoc and contain macros identical to the ones in my RFC.Here's an example of
sys_mlock()spec:
So I'm getting ahead of the game, but I have to ask some questions...
Quoted 4 lines
/**
*sys_mlock- Lock pages in memory
* @start: Starting address of memory range to lock
* @len: Length of memory range to lock in bytes
Quoted 8 lines
*
* Locks pages in the specified address range into RAM, preventing them from
* being paged to swap. RequiresCAP_IPC_LOCKcapability orRLIMIT_MEMLOCK
* resource limit.
*
* long-desc: Locks pages in the specified address range into RAM, preventing
* them from being paged to swap. RequiresCAP_IPC_LOCKcapability
* orRLIMIT_MEMLOCKresource limit.
Why duplicate the long description?
Quoted 2 lines
* context-flags:
KAPI_CTX_PROCESS|KAPI_CTX_SLEEPABLE
* param-type: start,KAPI_TYPE_UINT
This is something I wondered before; rather than a bunch of lengthy KAPI_* symbols, why not just say __u64 (or some other familiar type) here?
Quoted 56 lines
* param-flags: start,
KAPI_PARAM_IN
* param-constraint-type: start,KAPI_CONSTRAINT_NONE
* param-constraint: start, Rounded down to page boundary
* param-type: len,KAPI_TYPE_UINT
* param-flags: len,KAPI_PARAM_IN
* param-constraint-type: len,KAPI_CONSTRAINT_RANGE
* param-range: len, 0,LONG_MAX
* param-constraint: len, Rounded up to page boundary
* return-type:KAPI_TYPE_INT
* return-check-type:KAPI_RETURN_ERROR_CHECK
* return-success: 0
* error-code:-ENOMEM, ENOMEM, Address range issue,
* Some of the specified range is not mapped, has unmapped gaps,
* or the lock would cause the number of mapped regions to exceed the limit.
* error-code:-EPERM, EPERM, Insufficient privileges,
* The caller is not privileged (noCAP_IPC_LOCK) andRLIMIT_MEMLOCKis 0.
* error-code:-EINVAL, EINVAL, Address overflow,
* The result of the addition start+len was less than start (arithmetic overflow).
* error-code:-EAGAIN, EAGAIN, Some or all memory could not be locked,
* Some or all of the specified address range could not be locked.
* error-code:-EINTR, EINTR, Interrupted by signal,
* The operation was interrupted by a fatal signal before completion.
* error-code:-EFAULT, EFAULT, Bad address,
* The specified address range contains invalid addresses that cannot be accessed.
* since-version: 2.0
* lock:mmap_lock,KAPI_LOCK_RWLOCK
* lock-acquired: true
* lock-released: true
* lock-desc: Process memory map write lock
* signal: FATAL
* signal-direction:KAPI_SIGNAL_RECEIVE
* signal-action:KAPI_SIGNAL_ACTION_RETURN
* signal-condition: Fatal signal pending
* signal-desc: Fatal signals (SIGKILL) can interrupt the operation at two points:* when acquiring mmap_write_lock_killable() and during page population * in __mm_populate(). Returns -EINTR. Non-fatal signals do NOT interrupt * mlock - the operation continues even if SIGINT/SIGTERM are received. * signal-error: -EINTR * signal-timing: KAPI_SIGNAL_TIME_DURING * signal-priority: 0 * signal-interruptible: yes * signal-state-req: KAPI_SIGNAL_STATE_RUNNING * examples: mlock(addr, 4096); // Lock one page * mlock(addr, len); // Lock range of pages * notes: Memory locks do not stack - multiple calls on the same range can be * undone by a single munlock. Locks are not inherited by child processes. * Pages are locked on whole page boundaries. Commonly used by real-time * applications to prevent page faults during time-critical operations. * Also used for security to prevent sensitive data (e.g., cryptographic keys) * from being written to swap. Note: locked pages may still be saved to * swap during system suspend/hibernate. * * Tagged addresses are automatically handled via untagged_addr(). The operation * occurs in two phases: first VMAs are marked with VM_LOCKED, then pages are * populated into memory. When checking RLIMIT_MEMLOCK, the kernel optimizes * by recounting locked memory to avoid double-counting overlapping regions.
Quoted 1 line
* side-effect:
KAPI_EFFECT_MODIFY_STATE|KAPI_EFFECT_ALLOC_MEMORY, process memory, Locks pages into physical memory, preventing swapping, reversible=yes
I hope the really long lines starting here aren't the intended way to go...:)
Quoted 11 lines
* side-effect:
KAPI_EFFECT_MODIFY_STATE,mm->locked_vm, Increases process locked memory counter, reversible=yes
* side-effect:KAPI_EFFECT_ALLOC_MEMORY, physical pages, May allocate and populate page table entries, condition=Pages not already present, reversible=yes
* side-effect:KAPI_EFFECT_MODIFY_STATE|KAPI_EFFECT_ALLOC_MEMORY, page faults, Triggers page faults to bring pages into memory, condition=Pages not already resident
* side-effect:KAPI_EFFECT_MODIFY_STATE, VMA splitting, May split existing VMAs at lock boundaries, condition=Lock range partially overlaps existing VMA
* state-trans: memory pages, swappable, locked in RAM, Pages become non-swappable and pinned in physical memory
* state-trans: VMA flags, unlocked,VM_LOCKEDset, Virtual memory area marked as locked
* capability:CAP_IPC_LOCK,KAPI_CAP_BYPASS_CHECK,CAP_IPC_LOCKcapability
* capability-allows: Lock unlimited amount of memory (noRLIMIT_MEMLOCKenforcement)
* capability-without: Must respectRLIMIT_MEMLOCKresource limit
* capability-condition: Checked whenRLIMIT_MEMLOCKis 0 or locking would exceed limit
* capability-priority: 0
Quoted 8 lines
* constraint:
RLIMIT_MEMLOCKResource Limit, TheRLIMIT_MEMLOCKsoft resource limit specifies the maximum bytes of memory that may be locked into RAM. Unprivileged processes are restricted to this limit.CAP_IPC_LOCKcapability allows bypassing this limit entirely. The limit is enforced per-process, not per-user.
* constraint-expr:RLIMIT_MEMLOCKResource Limit,locked_memory+request_size<=RLIMIT_MEMLOCK||CAP_IPC_LOCK
* constraint: Memory Pressure and OOM, Locking large amounts of memory can cause system-wide memory pressure and potentially trigger the OOM killer. The kernel does not prevent locking memory that would destabilize the system.
* constraint: Special Memory Areas, Some memory types cannot be locked or are silently skipped: VM_IO/VM_PFNMAP areas (device mappings) are skipped; Hugetlb pages are inherently pinned and skipped; DAX mappings are always present in memory and skipped; Secret memory (memfd_secret) mappings are skipped;VM_DROPPABLEmemory cannot be locked and is skipped; Gate VMA (kernel entry point) is skipped;VM_LOCKEDareas are already locked. These special areas are silently excluded without error. *
* Context: Process context. May sleep. Takesmmap_lockfor write.
*
* Return: 0 on success, negative error code on failure
Both of these, of course, are much less informative versions of the data you have put up above; it would be nice to unify them somehow.
Thanks,
jon
Re: [RFC v2 01/22] kernel/api: introduce kernel API specification framework
Quoted 23 lines · Jonathan Corbet
Quoted 5 lines · Sasha Levin
So I have a proof of concept which during the build process creates
.apispec.hwhich are generated from kerneldoc and contain macros identical to the ones in my RFC.Here's an example of
sys_mlock()spec:So I'm getting ahead of the game, but I have to ask some questions...
Quoted 4 lines
/**
*sys_mlock- Lock pages in memory
* @start: Starting address of memory range to lock
* @len: Length of memory range to lock in bytesQuoted 8 lines
*
* Locks pages in the specified address range into RAM, preventing them from
* being paged to swap. RequiresCAP_IPC_LOCKcapability orRLIMIT_MEMLOCK
* resource limit.
*
* long-desc: Locks pages in the specified address range into RAM, preventing
* them from being paged to swap. RequiresCAP_IPC_LOCKcapability
* orRLIMIT_MEMLOCKresource limit.
Quoted 1 line
Why duplicate the long description?
Will fix.
Quoted 6 lines
Quoted 2 lines
* context-flags:
KAPI_CTX_PROCESS|KAPI_CTX_SLEEPABLE
* param-type: start,KAPI_TYPE_UINTThis is something I wondered before; rather than a bunch of lengthy KAPI_* symbols, why not just say
__u64(or some other familiar type) here?
I think it gets tricky when we got to more complex types. For example, how do we represent a FD or a (struct sockaddr *)?
With macros, KAPI_TYPE_FD or KAPI_TYPE_SOCKADDR make sense, but __sockaddr will be a bit confusing (I think).
Quoted 58 lines
Quoted 56 lines
* param-flags: start,
KAPI_PARAM_IN
* param-constraint-type: start,KAPI_CONSTRAINT_NONE
* param-constraint: start, Rounded down to page boundary
* param-type: len,KAPI_TYPE_UINT
* param-flags: len,KAPI_PARAM_IN
* param-constraint-type: len,KAPI_CONSTRAINT_RANGE
* param-range: len, 0,LONG_MAX
* param-constraint: len, Rounded up to page boundary
* return-type:KAPI_TYPE_INT
* return-check-type:KAPI_RETURN_ERROR_CHECK
* return-success: 0
* error-code:-ENOMEM, ENOMEM, Address range issue,
* Some of the specified range is not mapped, has unmapped gaps,
* or the lock would cause the number of mapped regions to exceed the limit.
* error-code:-EPERM, EPERM, Insufficient privileges,
* The caller is not privileged (noCAP_IPC_LOCK) andRLIMIT_MEMLOCKis 0.
* error-code:-EINVAL, EINVAL, Address overflow,
* The result of the addition start+len was less than start (arithmetic overflow).
* error-code:-EAGAIN, EAGAIN, Some or all memory could not be locked,
* Some or all of the specified address range could not be locked.
* error-code:-EINTR, EINTR, Interrupted by signal,
* The operation was interrupted by a fatal signal before completion.
* error-code:-EFAULT, EFAULT, Bad address,
* The specified address range contains invalid addresses that cannot be accessed.
* since-version: 2.0
* lock:mmap_lock,KAPI_LOCK_RWLOCK
* lock-acquired: true
* lock-released: true
* lock-desc: Process memory map write lock
* signal: FATAL
* signal-direction:KAPI_SIGNAL_RECEIVE
* signal-action:KAPI_SIGNAL_ACTION_RETURN
* signal-condition: Fatal signal pending
* signal-desc: Fatal signals (SIGKILL) can interrupt the operation at two points:* when acquiring mmap_write_lock_killable() and during page population * in __mm_populate(). Returns -EINTR. Non-fatal signals do NOT interrupt * mlock - the operation continues even if SIGINT/SIGTERM are received. * signal-error: -EINTR * signal-timing: KAPI_SIGNAL_TIME_DURING * signal-priority: 0 * signal-interruptible: yes * signal-state-req: KAPI_SIGNAL_STATE_RUNNING * examples: mlock(addr, 4096); // Lock one page * mlock(addr, len); // Lock range of pages * notes: Memory locks do not stack - multiple calls on the same range can be * undone by a single munlock. Locks are not inherited by child processes. * Pages are locked on whole page boundaries. Commonly used by real-time * applications to prevent page faults during time-critical operations. * Also used for security to prevent sensitive data (e.g., cryptographic keys) * from being written to swap. Note: locked pages may still be saved to * swap during system suspend/hibernate. * * Tagged addresses are automatically handled via untagged_addr(). The operation * occurs in two phases: first VMAs are marked with VM_LOCKED, then pages are * populated into memory. When checking RLIMIT_MEMLOCK, the kernel optimizes * by recounting locked memory to avoid double-counting overlapping regions.Quoted 1 line
* side-effect:
KAPI_EFFECT_MODIFY_STATE|KAPI_EFFECT_ALLOC_MEMORY, process memory, Locks pages into physical memory, preventing swapping, reversible=yes
Quoted 1 line
I hope the really long lines starting here aren't the intended way to go...:)
I guess that we have two options around more complex blocks like these.
One, the longer lines you've pointed out. They are indeed long and difficult to read, but they present a relatively static and "not too interesting" information which users are likely to gloss over.
The other one would look something like:
side-effect: KAPI_EFFECT_MODIFY_STATE
side-effect-type: KAPI_EFFECT_MODIFY_STATE
side-effect-target: mm->locked_vm
side-effect-description: Increases process locked memory counter
side-effect-reversible: yes
Which isn't as long, but it occupies a bunch of vertical real estate while not being too interesting for most of the readers.
Quoted 20 lines
Quoted 11 lines
* side-effect:
KAPI_EFFECT_MODIFY_STATE,mm->locked_vm, Increases process locked memory counter, reversible=yes
* side-effect:KAPI_EFFECT_ALLOC_MEMORY, physical pages, May allocate and populate page table entries, condition=Pages not already present, reversible=yes
* side-effect:KAPI_EFFECT_MODIFY_STATE|KAPI_EFFECT_ALLOC_MEMORY, page faults, Triggers page faults to bring pages into memory, condition=Pages not already resident
* side-effect:KAPI_EFFECT_MODIFY_STATE, VMA splitting, May split existing VMAs at lock boundaries, condition=Lock range partially overlaps existing VMA
* state-trans: memory pages, swappable, locked in RAM, Pages become non-swappable and pinned in physical memory
* state-trans: VMA flags, unlocked,VM_LOCKEDset, Virtual memory area marked as locked
* capability:CAP_IPC_LOCK,KAPI_CAP_BYPASS_CHECK,CAP_IPC_LOCKcapability
* capability-allows: Lock unlimited amount of memory (noRLIMIT_MEMLOCKenforcement)
* capability-without: Must respectRLIMIT_MEMLOCKresource limit
* capability-condition: Checked whenRLIMIT_MEMLOCKis 0 or locking would exceed limit
* capability-priority: 0Quoted 8 lines
* constraint:
RLIMIT_MEMLOCKResource Limit, TheRLIMIT_MEMLOCKsoft resource limit specifies the maximum bytes of memory that may be locked into RAM. Unprivileged processes are restricted to this limit.CAP_IPC_LOCKcapability allows bypassing this limit entirely. The limit is enforced per-process, not per-user.
* constraint-expr:RLIMIT_MEMLOCKResource Limit,locked_memory+request_size<=RLIMIT_MEMLOCK||CAP_IPC_LOCK
* constraint: Memory Pressure and OOM, Locking large amounts of memory can cause system-wide memory pressure and potentially trigger the OOM killer. The kernel does not prevent locking memory that would destabilize the system.
* constraint: Special Memory Areas, Some memory types cannot be locked or are silently skipped: VM_IO/VM_PFNMAP areas (device mappings) are skipped; Hugetlb pages are inherently pinned and skipped; DAX mappings are always present in memory and skipped; Secret memory (memfd_secret) mappings are skipped;VM_DROPPABLEmemory cannot be locked and is skipped; Gate VMA (kernel entry point) is skipped;VM_LOCKEDareas are already locked. These special areas are silently excluded without error. *
* Context: Process context. May sleep. Takesmmap_lockfor write.
*
* Return: 0 on success, negative error code on failure
Quoted 2 lines
Both of these, of course, are much less informative versions of the data you have put up above; it would be nice to unify them somehow.
Ack
Signature · 2 lines
Thanks, Sasha
RFC v2 2/22 eventpoll: add API specification for epoll_create1
In reply to Sasha LevinAdd kernel API specification for the epoll_create1() system call.
--- fs/eventpoll.c | 124 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+)
fs/eventpoll.c +124 -0
@@ -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,129 @@ 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) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_ENUM) + KAPI_PARAM_ENUM_VALUES(epoll_create1_valid_values) + KAPI_PARAM_CONSTRAINT("Must be 0 or EPOLL_CLOEXEC") + KAPI_PARAM_END + + KAPI_RETURN("long", "File descriptor on success, negative error code on failure") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_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", + KAPI_EXAMPLES("int epfd = epoll_create1(EPOLL_CLOEXEC);") +KAPI_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. " +"Memory consumption: Each registered fd uses approximately 90 bytes on 32-bit kernels " +"and 160 bytes on 64-bit kernels. The total number of file descriptors registered " +"across all epoll instances is limited by /proc/sys/fs/epoll/max_user_watches. " +"When using dup() or fork(), multiple file descriptors may refer to the same epoll " +"instance and all will receive events." ) + + /* 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING | KAPI_SIGNAL_STATE_SLEEPING) + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING | KAPI_SIGNAL_STATE_SLEEPING) + 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_TIMING(KAPI_SIGNAL_TIME_ANYTIME) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_QUEUE("uncatchable") +KAPI_SIGNAL_END + + .signal_count =3 , + +/* Additional constraints */ +KAPI_CONSTRAINT (0 ,"User Watch Limit" , +"Although epoll_create1() itself doesn't register any watches, the " +"user is subject to a global limit on total watches across all epoll " +"instances. This limit is configured via /proc/sys/fs/epoll/max_user_watches " +"(default: 1/25 of lowmem or 1/32 of total memory). Each registered " + "file descriptor counts against this limit.") + KAPI_CONSTRAINT_EXPR("current_user_watches < max_user_watches") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(1, "Memory Accounting", + "Each epoll instance consumes kernel memory that is not swappable. " + "The instance itself uses approximately 1KB, plus additional memory " + "for each registered file descriptor (90 bytes on 32-bit, 160 bytes " + "on 64-bit systems). This memory is charged to the user's locked " + "memory limit if memory cgroups are enabled.") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT_COUNT(2) + +KAPI_END_SPEC ; SYSCALL_DEFINE1(epoll_create1, int, flags) {return do_epoll_create (flags);
Signature · 1 line
2.39.5
RFC v2 3/22 eventpoll: add API specification for epoll_create
In reply to Sasha LevinAdd kernel API specification for the epoll_create() system call.
--- fs/eventpoll.c | 122 +++++++++++++++++++++++++++++++- include/linux/kernel_api_spec.h | 13 ++++ 2 files changed, 132 insertions(+), 3 deletions(-)
fs/eventpoll.c +119 -3
@@ -2300,8 +2300,8 @@ DEFINE_KERNEL_API_SPEC(sys_epoll_create1)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, + KAPI_ERROR_COUNT(5) +KAPI_PARAM_COUNT (1 ) .since_version ="2.6.27" , KAPI_EXAMPLES("int epfd = epoll_create1(EPOLL_CLOEXEC);") KAPI_NOTES("EPOLL_CLOEXEC sets the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. "
@@ -2366,7 +2366,7 @@ DEFINE_KERNEL_API_SPEC(sys_epoll_create1) KAPI_SIGNAL_QUEUE("uncatchable") KAPI_SIGNAL_END - .signal_count =3 , + KAPI_SIGNAL_COUNT(3)/* Additional constraints */ KAPI_CONSTRAINT(0, "User Watch Limit",
@@ -2394,6 +2394,122 @@ 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) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_CONSTRAINT("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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_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.") + + KAPI_ERROR_COUNT(5) + KAPI_PARAM_COUNT(1) + KAPI_SINCE_VERSION("2.6") + KAPI_DEPRECATED + KAPI_REPLACEMENT("epoll_create1") + KAPI_EXAMPLES("int epfd = epoll_create(1024); // size is ignored since Linux 2.6.8") +KAPI_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. " +"Memory consumption: Each registered fd uses approximately 90 bytes on 32-bit kernels " +"and 160 bytes on 64-bit kernels. The total number of file descriptors registered " +"across all epoll instances is limited by /proc/sys/fs/epoll/max_user_watches. " +"When using dup() or fork(), multiple file descriptors may refer to the same epoll " +"instance and all will receive events." ) + + /* 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 + + KAPI_SIGNAL_COUNT(5) +KAPI_END_SPEC ; + SYSCALL_DEFINE1(epoll_create, int, size) {if (size <=0 )
include/linux/kernel_api_spec.h +13 -0
@@ -963,6 +963,19 @@ struct kernel_api_spec {#define KAPI_NOTES (n) \ .notes = n, +/** +* KAPI_DEPRECATED - Mark API as deprecated +*/ +#define KAPI_DEPRECATED \ + .deprecated = true, + +/** +* KAPI_REPLACEMENT - Set replacement API for deprecated function +* @repl: Replacement API name +*/ +#define KAPI_REPLACEMENT (repl) \ + .replacement = repl, +/** * KAPI_SIGNAL - Define a signal specification * @idx: Signal index
Signature · 1 line
2.39.5
RFC v2 4/22 eventpoll: add API specification for epoll_ctl
In reply to Sasha LevinAdd kernel API specification for the epoll_ctl() system call.
--- fs/eventpoll.c | 254 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 254 insertions(+)
fs/eventpoll.c +254 -0
@@ -2690,6 +2690,260 @@ 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) + KAPI_PARAM_TYPE(KAPI_TYPE_FD) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_END + + KAPI_PARAM(1, "op", "int", "Operation to be performed") + KAPI_PARAM_FLAGS(KAPI_PARAM_IN) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_ENUM) + .enum_values = epoll_ctl_valid_ops, + .enum_count = ARRAY_SIZE(epoll_ctl_valid_ops), + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_FD) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_USER_PTR) + KAPI_PARAM_SIZE(sizeof(struct epoll_event)) + KAPI_PARAM_CONSTRAINT("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, + +/* Capability specifications */ + KAPI_CAPABILITY(0, CAP_BLOCK_SUSPEND, "CAP_BLOCK_SUSPEND", KAPI_CAP_GRANT_PERMISSION) + KAPI_CAP_ALLOWS("Use EPOLLWAKEUP flag to prevent system suspend while epoll events are pending") + KAPI_CAP_WITHOUT("EPOLLWAKEUP flag is silently ignored/stripped from events mask") + KAPI_CAP_CONDITION("Checked when EPOLLWAKEUP flag is set in epoll_event.events") + KAPI_CAP_PRIORITY(0) + KAPI_CAPABILITY_END + + KAPI_CAPABILITY_COUNT(1) + +KAPI_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") +KAPI_NOTES ("EPOLL_CTL_DEL ignores the event parameter (can be NULL). " +"EPOLLEXCLUSIVE flag (Linux 4.5+) can only be used with EPOLL_CTL_ADD and is " +"restricted to EPOLLIN/EPOLLOUT events; it provides exclusive wakeup behavior " +"where only one thread is woken for the event instead of all threads. " +"The epoll instance maintains a reference to registered files until they are " +"explicitly removed with EPOLL_CTL_DEL or the epoll instance is closed. " +"Memory consumption: Each registered fd uses approximately 90 bytes on 32-bit " +"kernels and 160 bytes on 64-bit kernels. " +"When using dup() or fork(), multiple epoll instances may monitor the same " +"underlying file and all will receive events for that file descriptor." ) + + /* Additional constraints */ +KAPI_CONSTRAINT (0 ,"Nested Epoll Depth Limit" , +"Epoll file descriptors can monitor other epoll fds, but nesting is " +"limited to EP_MAX_NESTS (4) levels deep to prevent kernel stack " +"overflow and excessive resource consumption. The limit is checked " + "during EPOLL_CTL_ADD operations.") + KAPI_CONSTRAINT_EXPR("epoll_nesting_depth <= 4") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(1, "Circular Dependency Detection", + "The kernel detects and prevents circular epoll references where " + "epoll instances would monitor each other in a loop. This check " + "involves traversing the epoll tree and has O(N) complexity where " + "N is the number of epoll fds in the potential loop.") + KAPI_CONSTRAINT_END + +KAPI_CONSTRAINT (2 ,"User Watch Limit" , +"Total number of file descriptors a user can watch across all epoll " +"instances is limited by /proc/sys/fs/epoll/max_user_watches " +"(default: 1/25 of lowmem or 1/32 of total memory). This prevents " + "memory exhaustion attacks.") + KAPI_CONSTRAINT_EXPR("user_watches + 1 <= max_user_watches") + KAPI_CONSTRAINT_END + +KAPI_CONSTRAINT (3 ,"EPOLLEXCLUSIVE Restrictions" , +"EPOLLEXCLUSIVE can only be used with EPOLL_CTL_ADD operation and " +"is limited to EPOLLIN and EPOLLOUT events. It cannot be used with " +"EPOLLONESHOT or level-triggered mode. Only applies to sockets and " + "pipes that support exclusive wakeups.") + KAPI_CONSTRAINT_EXPR("EPOLLEXCLUSIVE => (op == EPOLL_CTL_ADD && events & (EPOLLIN|EPOLLOUT))") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT_COUNT(4) + +KAPI_END_SPEC ; +SYSCALL_DEFINE4 (epoll_ctl, int, epfd, int, op, int, fd, struct epoll_event __user *, event) {
Signature · 1 line
2.39.5
RFC v2 5/22 eventpoll: add API specification for epoll_wait
In reply to Sasha LevinAdd kernel API specification for the epoll_wait() system call.
--- fs/eventpoll.c | 187 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 187 insertions(+)
fs/eventpoll.c +187 -0
@@ -3026,6 +3026,193 @@ 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) + KAPI_PARAM_TYPE(KAPI_TYPE_FD) + KAPI_PARAM_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) + KAPI_PARAM_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), + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_RANGE(1, INT_MAX / sizeof(struct epoll_event)) /* EP_MAX_EVENTS */ + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("-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 , + +KAPI_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" + "}") +KAPI_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). " +"Edge-triggered mode (EPOLLET) can cause starvation if not all available data is " +"drained when an event is received - new events are only generated on transitions " +"from no data to data available. Always read/write until EAGAIN to avoid missing events. " +"When using dup() or fork(), events may be delivered to multiple epoll instances " + "monitoring the same file descriptor.") +KAPI_END_SPEC ; + SYSCALL_DEFINE4(epoll_wait, int, epfd, struct epoll_event __user *, events, int, maxevents, int, timeout) {
Signature · 1 line
2.39.5
RFC v2 6/22 eventpoll: add API specification for epoll_pwait
In reply to Sasha LevinAdd kernel API specification for the epoll_pwait() system call.
--- fs/eventpoll.c | 234 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 234 insertions(+)
fs/eventpoll.c +234 -0
@@ -3247,6 +3247,240 @@ 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) + KAPI_PARAM_TYPE(KAPI_TYPE_FD) + KAPI_PARAM_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) + KAPI_PARAM_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), + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_RANGE(1, INT_MAX / sizeof(struct epoll_event)) /* EP_MAX_EVENTS */ + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("-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) + KAPI_PARAM_TYPE(KAPI_TYPE_USER_PTR) + KAPI_PARAM_SIZE(sizeof(sigset_t)) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_RANGE(sizeof(sigset_t), sizeof(sigset_t)) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_CONSTRAINT("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 , + +KAPI_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" + "}") +KAPI_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. " +"Edge-triggered mode (EPOLLET) can cause starvation if not all available data is " +"drained when an event is received. Always read/write until EAGAIN. " +"When using dup() or fork(), events may be delivered to multiple epoll instances " + "monitoring the same file descriptor.") +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
RFC v2 7/22 eventpoll: add API specification for epoll_pwait2
In reply to Sasha LevinAdd kernel API specification for the epoll_pwait2() system call.
--- fs/eventpoll.c | 248 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 248 insertions(+)
fs/eventpoll.c +248 -0
@@ -3492,6 +3492,254 @@ 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) + KAPI_PARAM_TYPE(KAPI_TYPE_FD) + KAPI_PARAM_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) + KAPI_PARAM_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), + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_RANGE(1, INT_MAX / sizeof(struct epoll_event)) /* EP_MAX_EVENTS */ + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_USER_PTR) + KAPI_PARAM_SIZE(sizeof(struct __kernel_timespec)) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_USER_PTR) + KAPI_PARAM_SIZE(sizeof(sigset_t)) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_RANGE(sizeof(sigset_t), sizeof(sigset_t)) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_CONSTRAINT("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 , + +KAPI_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));") +KAPI_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. " +"Edge-triggered mode (EPOLLET) can cause starvation if not all available data is " +"drained when an event is received. Always read/write until EAGAIN. " +"When using dup() or fork(), events may be delivered to multiple epoll instances " + "monitoring the same file descriptor.") +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
RFC v2 8/22 exec: add API specification for execve
In reply to Sasha LevinAdd comprehensive kernel API specification for the execve() system call.
--- fs/exec.c | 364 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 364 insertions(+)
fs/exec.c +364 -0
@@ -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,370 @@ 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) + KAPI_PARAM_TYPE(KAPI_TYPE_PATH) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_USER_PTR) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_USER_PTR) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("NULL-terminated array of pointers to null-terminated strings in form key=value") + KAPI_PARAM_END + + KAPI_RETURN("long", "Does not return on success; negative error code 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.") + + KAPI_ERROR_COUNT(18) + KAPI_PARAM_COUNT(3) + KAPI_SINCE_VERSION("1.0") +KAPI_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);") +KAPI_NOTES ("On success, execve() does not return; the new program is executed. " +"File descriptors remain open unless marked close-on-exec. " +"Signal handling undergoes major changes: handlers reset to default (except SIG_IGN), " +"pending signals cleared, alternate signal stack removed, but signal mask preserved. " +"Fatal signals can interrupt exec causing process termination. " +"Multi-threaded programs: all threads except caller are killed with SIGKILL. " +"Traced processes receive SIGTRAP after successful exec. " +"Point of no return: if exec fails after destroying old image, SIGSEGV is forced." ) + + /* 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING) + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE(KAPI_SIGNAL_QUEUE_STANDARD) + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Handler information cleared from signal struct") + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_SA_FLAGS_FORBID(SA_RESTART | SA_NODEFER | SA_RESETHAND | SA_SIGINFO | SA_ONSTACK) + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Ignored signals remain ignored") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_END + + /* Pending signals cleared */ + KAPI_SIGNAL(4, 0, "PENDING_SIGNALS", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_DISCARD) + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("All pending signals discarded") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Timer signals cleared from pending queue") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + 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_TIMING(KAPI_SIGNAL_TIME_EXIT) + KAPI_SIGNAL_PRIORITY(2) + KAPI_SIGNAL_QUEUE("Standard signal delivery to parent") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Alternate stack configuration cleared") + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_SA_FLAGS_FORBID(SA_ONSTACK) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_END + + /* SIGTRAP sent when process is being traced */ + KAPI_SIGNAL(8, SIGTRAP, "SIGTRAP", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_DEFAULT) + KAPI_SIGNAL_TARGET("Current process") + KAPI_SIGNAL_CONDITION("Process is being traced (PTRACE_ATTACH or PTRACE_TRACEME)") +KAPI_SIGNAL_DESC ("If the process is being traced, a SIGTRAP is sent to the " +"process after successful exec. This allows debuggers to gain " + "control after the new program is loaded but before it starts executing.") + KAPI_SIGNAL_TIMING(KAPI_SIGNAL_TIME_EXIT) + KAPI_SIGNAL_PRIORITY(10) + KAPI_SIGNAL_QUEUE(KAPI_SIGNAL_QUEUE_STANDARD) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_TRACED) + KAPI_SIGNAL_END + + /* 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_PRIORITY(2) + KAPI_SIGNAL_QUEUE("Signal mask preserved across exec") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + 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_PRIORITY(1) + KAPI_SIGNAL_QUEUE(KAPI_SIGNAL_QUEUE_REALTIME) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_END + + .signal_count = 12, + + /* Signal masks */ + KAPI_SIGNAL_MASK(0, "critical_section_mask", "Signals blocked during critical exec sections") + /* During de_thread and other critical sections, certain signals may be blocked */ + KAPI_SIGNAL_MASK_END + + KAPI_SIGNAL_MASK_COUNT(1) + + /* 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 | KAPI_EFFECT_FREE_MEMORY, + "shared memory", + "Detaches and unmaps all POSIX shared memory regions (shm_open/mmap)") + KAPI_SIDE_EFFECT_END + +KAPI_SIDE_EFFECT_COUNT (7 ) + + /* 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 ) + + /* Additional constraints */ +KAPI_CONSTRAINT (0 ,"Argument Size Limits" , +"Total size of argv[] and envp[] is limited by ARG_MAX (usually 2MB on " +"modern systems). This includes both the string data and the pointer " +"arrays. The limit is checked early to prevent excessive memory allocation. " + "Individual argument strings are limited to MAX_ARG_STRLEN (131072 bytes).") + KAPI_CONSTRAINT_EXPR("total_arg_size <= ARG_MAX && each_arg_len <= MAX_ARG_STRLEN") + KAPI_CONSTRAINT_END + +KAPI_CONSTRAINT (1 ,"RLIMIT_NPROC Process Limit" , +"The RLIMIT_NPROC limit is enforced during execve() to prevent fork bombs. " +"If the user would exceed their process limit after exec, the PF_NPROC_EXCEEDED " +"flag is set and exec may fail. This check happens even though exec doesn't " + "create new processes, to catch programs that exec after fork.") + KAPI_CONSTRAINT_EXPR("user_processes < RLIMIT_NPROC || PF_NPROC_EXCEEDED") + KAPI_CONSTRAINT_END + +KAPI_CONSTRAINT (2 ,"Binary Format Handlers" , +"The kernel tries binary format handlers in order: built-in formats " +"(ELF, script, etc.), then modular formats. Script interpreters can " +"recurse up to 5 levels deep (BINPRM_MAX_RECURSION). Each recursion " + "consumes one argv slot for the interpreter path.") + KAPI_CONSTRAINT_EXPR("recursion_depth <= 5") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(3, "Security Transitions", + "Security modules (SELinux, AppArmor, etc.) may deny exec based on " + "policy. Capabilities are recalculated based on file capabilities " + "and setuid/setgid bits. The dumpable flag is cleared for security " + "transitions. AT_SECURE is set in auxiliary vector for secure execs.") + KAPI_CONSTRAINT_END + +KAPI_CONSTRAINT (4 ,"Stack Size Calculation" , +"Stack size is limited by RLIMIT_STACK but adjusted based on " +"personality flags and architecture requirements. The stack must " +"accommodate argv, envp, auxiliary vector, and initial program stack. " + "On some architectures, executable stack is determined by PT_GNU_STACK.") + KAPI_CONSTRAINT_EXPR("stack_size >= ARG_MAX && stack_size <= RLIMIT_STACK") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT_COUNT(5) + +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
RFC v2 9/22 exec: add API specification for execveat
In reply to Sasha LevinAdd comprehensive kernel API specification for the execveat() system call.
--- fs/exec.c | 342 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 340 insertions(+), 2 deletions(-)
fs/exec.c +340 -2
@@ -2029,8 +2029,8 @@ DEFINE_KERNEL_API_SPEC(sys_execve) KAPI_PARAM_END KAPI_RETURN("long", "Does not return on success; negative error code on error") - .type = KAPI_TYPE_INT, - .check_type = KAPI_RETURN_ERROR_CHECK, + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) KAPI_RETURN_END KAPI_ERROR(0, -E2BIG, "E2BIG", "Argument list too long",
@@ -2369,6 +2369,344 @@ 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) + KAPI_PARAM_TYPE(KAPI_TYPE_FD) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_PATH) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_USER_PTR) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_USER_PTR) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_MASK) + KAPI_PARAM_VALID_MASK(AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW | AT_EXECVE_CHECK) + KAPI_PARAM_CONSTRAINT("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); negative error code on error") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_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, or (rare bug) all file descriptors are closed when executing a script.") + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING) + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_QUEUE("Cannot be blocked, caught, or ignored") + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Handler information cleared from signal struct") + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_SA_FLAGS_FORBID(SA_SIGINFO | SA_ONSTACK | SA_RESTART | SA_NODEFER | SA_RESETHAND) + KAPI_SIGNAL_INTERRUPTIBLE + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Ignored signals remain ignored") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("All pending signals discarded") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Timer signals cleared from pending queue") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + 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_TIMING(KAPI_SIGNAL_TIME_EXIT) + KAPI_SIGNAL_PRIORITY(2) + KAPI_SIGNAL_QUEUE("Standard signal delivery to parent") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + 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_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Alternate stack configuration cleared") + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_SA_FLAGS_FORBID(SA_ONSTACK) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_END + + KAPI_SIGNAL(8, SIGTRAP, "SIGTRAP", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_DEFAULT) + KAPI_SIGNAL_TARGET("Current process") + KAPI_SIGNAL_CONDITION("Process is being traced (PTRACE_ATTACH or PTRACE_TRACEME)") + KAPI_SIGNAL_DESC("If the process is being traced, a SIGTRAP is sent to the process after successful exec. This allows debuggers to gain control after the new program is loaded but before it starts executing.") + KAPI_SIGNAL_TIMING(KAPI_SIGNAL_TIME_EXIT) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Standard signal delivery") + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_TRACED) + KAPI_SIGNAL_SA_FLAGS_REQ(SA_SIGINFO) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_END + + KAPI_SIGNAL(9, SIGSEGV, "SIGSEGV", KAPI_SIGNAL_SEND, KAPI_SIGNAL_ACTION_COREDUMP) + KAPI_SIGNAL_TARGET("Current process") + KAPI_SIGNAL_CONDITION("Past point-of-no-return and exec fails") + KAPI_SIGNAL_DESC("If exec fails after the point-of-no-return (after de_thread() or exec_mmap()), SIGSEGV is sent to terminate the process with a core dump.") + KAPI_SIGNAL_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_QUEUE("Cannot be blocked") + KAPI_SIGNAL_STATE_FORBID(KAPI_SIGNAL_STATE_ZOMBIE | KAPI_SIGNAL_STATE_DEAD) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_END + + KAPI_SIGNAL(10, 0, "BLOCKED_SIGNALS", KAPI_SIGNAL_BLOCK, KAPI_SIGNAL_ACTION_CUSTOM) + KAPI_SIGNAL_CONDITION("Signal mask inherited from caller") + KAPI_SIGNAL_DESC("The signal mask is preserved across exec. Blocked signals remain blocked in the new program unless it explicitly changes the mask.") + KAPI_SIGNAL_TIMING(KAPI_SIGNAL_TIME_ANYTIME) + KAPI_SIGNAL_PRIORITY(2) + KAPI_SIGNAL_QUEUE("Signal mask preserved across exec") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_END + + KAPI_SIGNAL(11, 0, "REALTIME_SIGNALS", KAPI_SIGNAL_HANDLE, KAPI_SIGNAL_ACTION_CUSTOM) + KAPI_SIGNAL_CONDITION("Realtime signals (SIGRTMIN-SIGRTMAX)") + KAPI_SIGNAL_DESC("Realtime signals are handled like standard signals - handlers reset to default, pending signals cleared, but signal mask preserved.") + KAPI_SIGNAL_TIMING(KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_QUEUE("Pending realtime signals discarded") +KAPI_SIGNAL_STATE_REQ (KAPI_SIGNAL_STATE_RUNNING) + KAPI_SIGNAL_INTERRUPTIBLE + 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 + +KAPI_SIDE_EFFECT (7 ,KAPI_EFFECT_MODIFY_STATE |KAPI_EFFECT_FREE_MEMORY , +"shared memory" , + "Detaches and unmaps all POSIX shared memory regions (shm_open/mmap)") + 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(8) + 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);", +KAPI_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).\n\n" +"Known bug: If a script is executed and the close-on-exec flag is set for all " +"file descriptors (including 0, 1, and 2), the execveat() call can fail with " +"EBADF when the kernel tries to open the interpreter, as it needs an available " +"file descriptor slot." ) + .signal_count = 9, + .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
RFC v2 10/22 mm/mlock: add API specification for mlock
In reply to Sasha LevinAdd kernel API specification for the mlock() system call.
--- mm/mlock.c | 142 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+)
mm/mlock.c +142 -0
@@ -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,147 @@ static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t flareturn 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") + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_FLAGS(KAPI_PARAM_IN) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("Rounded down to page boundary") + KAPI_PARAM_END + KAPI_PARAM(1, "len", "size_t", "Length of memory range to lock in bytes") + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_FLAGS(KAPI_PARAM_IN) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, LONG_MAX) + KAPI_PARAM_CONSTRAINT("Rounded up to page boundary") + KAPI_PARAM_END + + KAPI_RETURN("long", "0 on success, negative error code on failure") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_SUCCESS(0) + KAPI_RETURN_END + + 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.") + + KAPI_ERROR_COUNT(5) + KAPI_PARAM_COUNT(2) + KAPI_SINCE_VERSION("2.0") + + KAPI_LOCK(0, "mmap_lock", KAPI_LOCK_RWLOCK) + KAPI_LOCK_ACQUIRED + KAPI_LOCK_RELEASED + KAPI_LOCK_DESC("Process memory map write lock") + KAPI_LOCK_END + + KAPI_LOCK_COUNT(1) + + /* Signal specifications */ + KAPI_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 + + KAPI_EXAMPLES("mlock(addr, 4096); // Lock one page\n" + "mlock(addr, len); // Lock range of pages") +KAPI_NOTES ("Memory locks do not stack - multiple calls on the same range can be " +"undone by a single munlock. Locks are not inherited by child processes. " +"Pages are locked on whole page boundaries. Commonly used by real-time " +"applications to prevent page faults during time-critical operations. " +"Also used for security to prevent sensitive data (e.g., cryptographic keys) " +"from being written to swap. Note: locked pages may still be saved to " +"swap during system suspend/hibernate." ) + + /* 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 ) + + /* Capability specifications */ + KAPI_CAPABILITY(0, CAP_IPC_LOCK, "CAP_IPC_LOCK", KAPI_CAP_BYPASS_CHECK) + KAPI_CAP_ALLOWS("Lock unlimited amount of memory (no RLIMIT_MEMLOCK enforcement)") + KAPI_CAP_WITHOUT("Must respect RLIMIT_MEMLOCK resource limit") + KAPI_CAP_CONDITION("Checked when RLIMIT_MEMLOCK is 0 or locking would exceed limit") + KAPI_CAP_PRIORITY(0) + KAPI_CAPABILITY_END + +KAPI_CAPABILITY_COUNT (1 ) + + /* Additional constraints */ +KAPI_CONSTRAINT (0 ,"RLIMIT_MEMLOCK Resource Limit" , +"The RLIMIT_MEMLOCK soft resource limit specifies the maximum bytes " +"of memory that may be locked into RAM. Unprivileged processes are " +"restricted to this limit. CAP_IPC_LOCK capability allows bypassing " + "this limit entirely. The limit is enforced per-process, not per-user.") + KAPI_CONSTRAINT_EXPR("locked_memory + request_size <= RLIMIT_MEMLOCK || CAP_IPC_LOCK") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(1, "Memory Pressure and OOM", + "Locking large amounts of memory can cause system-wide memory pressure " + "and potentially trigger the OOM killer. The kernel does not prevent " + "locking memory that would destabilize the system.") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(2, "Special Memory Areas", + "Some memory types cannot be locked or behave specially: " + "VM_IO/VM_PFNMAP areas fail with EINVAL; " + "Hugetlb pages are inherently pinned; " + "DAX mappings are always present in memory; " + "VM_LOCKED areas are already locked.") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT_COUNT(3) + +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
RFC v2 11/22 mm/mlock: add API specification for mlock2
In reply to Sasha LevinAdd kernel API specification for the mlock2() system call.
--- mm/mlock.c | 163 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 163 insertions(+)
mm/mlock.c +163 -0
@@ -805,6 +805,169 @@ 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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, LONG_MAX) + KAPI_PARAM_CONSTRAINT("Rounded up to page boundary") + KAPI_PARAM_END + + KAPI_PARAM(2, "flags", "int", "Flags controlling lock behavior") + KAPI_PARAM_FLAGS(KAPI_PARAM_IN) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_MASK) + KAPI_PARAM_VALID_MASK(MLOCK_ONFAULT) + KAPI_PARAM_CONSTRAINT("Only MLOCK_ONFAULT flag is currently supported") + KAPI_PARAM_END + + /* Return specification */ + KAPI_RETURN("long", "0 on success, negative error code on failure") +KAPI_RETURN_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 + + KAPI_ERROR_COUNT(5) + KAPI_PARAM_COUNT(3) + KAPI_SINCE_VERSION("4.4") + KAPI_SIGNAL_COUNT(2) + KAPI_SIDE_EFFECT_COUNT(5) + KAPI_STATE_TRANS_COUNT(5) +KAPI_LOCK_COUNT (2 ) + + /* Capability specifications */ + KAPI_CAPABILITY(0, CAP_IPC_LOCK, "CAP_IPC_LOCK", KAPI_CAP_BYPASS_CHECK) + KAPI_CAP_ALLOWS("Lock unlimited amount of memory (no RLIMIT_MEMLOCK enforcement)") + KAPI_CAP_WITHOUT("Must respect RLIMIT_MEMLOCK resource limit") + KAPI_CAP_CONDITION("Checked when RLIMIT_MEMLOCK is 0 or locking would exceed limit") + KAPI_CAP_PRIORITY(0) + KAPI_CAPABILITY_END + + KAPI_CAPABILITY_COUNT(1) + +KAPI_EXAMPLES ("mlock2(addr, len, 0); // Same as mlock()\n" + "mlock2(addr, len, MLOCK_ONFAULT); // Lock on fault") +KAPI_NOTES ("MLOCK_ONFAULT flag defers actual page locking until pages are accessed. " +"Memory locks do not stack. Locks are not inherited by child processes. " +"Commonly used by real-time applications to prevent page faults. Also used " +"for security to prevent sensitive data (e.g., cryptographic keys) from being " +"written to swap. Note: locked pages may still be saved to swap during " + "system suspend/hibernate.") +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
RFC v2 12/22 mm/mlock: add API specification for mlockall
In reply to Sasha LevinAdd kernel API specification for the mlockall() system call.
--- mm/mlock.c | 186 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 186 insertions(+)
mm/mlock.c +186 -0
@@ -1049,6 +1049,192 @@ 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) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_MASK) + .valid_mask = MCL_CURRENT | MCL_FUTURE | MCL_ONFAULT, + KAPI_PARAM_CONSTRAINT("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 + + KAPI_ERROR_COUNT(5) + KAPI_PARAM_COUNT(1) + KAPI_SINCE_VERSION("2.0") + KAPI_SIGNAL_COUNT(2) + KAPI_SIDE_EFFECT_COUNT(6) + KAPI_STATE_TRANS_COUNT(5) +KAPI_LOCK_COUNT (2 ) + + /* Capability specifications */ + KAPI_CAPABILITY(0, CAP_IPC_LOCK, "CAP_IPC_LOCK", KAPI_CAP_BYPASS_CHECK) + KAPI_CAP_ALLOWS("Lock entire process memory exceeding RLIMIT_MEMLOCK") + KAPI_CAP_WITHOUT("Total VM size must not exceed RLIMIT_MEMLOCK when MCL_CURRENT is set") + KAPI_CAP_CONDITION("Checked when MCL_CURRENT is set and total VM size exceeds RLIMIT_MEMLOCK") + KAPI_CAP_PRIORITY(0) + KAPI_CAPABILITY_END + + KAPI_CAPABILITY_COUNT(1) + +KAPI_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") +KAPI_NOTES ("Affects all current VMAs and optionally future mappings via mm->def_flags. " +"Memory locks are not inherited by child processes after fork(). Commonly used " +"by real-time applications to prevent page faults. Also used for security to " +"prevent sensitive data (e.g., cryptographic keys) from being written to swap. " +"Note: locked pages may still be saved to swap during system suspend/hibernate." ) + + /* Additional constraints */ +KAPI_CONSTRAINT (0 ,"MCL_FUTURE Persistence" , +"The MCL_FUTURE flag persists across execve() calls by setting " +"mm->def_flags. This means all future memory mappings in the new " +"program will be locked. Care must be taken as this can cause " + "unexpected memory exhaustion in executed programs.") + KAPI_CONSTRAINT_EXPR("MCL_FUTURE => mm->def_flags |= VM_LOCKED") + KAPI_CONSTRAINT_END + +KAPI_CONSTRAINT (1 ,"Total VM Size Limit" , +"When MCL_CURRENT is set, the total virtual memory size of the " +"process is checked against RLIMIT_MEMLOCK. This differs from " +"mlock() which only counts actually locked pages. CAP_IPC_LOCK " + "bypasses this check entirely.") + KAPI_CONSTRAINT_EXPR("(flags & MCL_CURRENT) => total_vm <= RLIMIT_MEMLOCK || CAP_IPC_LOCK") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(2, "Memory Accounting", + "mlockall() with MCL_CURRENT can lock significantly more memory " + "than expected, including all shared libraries, heap, stack, and " + "mapped files. This can easily exhaust memory limits or cause " + "system-wide memory pressure.") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT_COUNT(3) + +KAPI_END_SPEC ; + SYSCALL_DEFINE1(mlockall, int, flags) {unsigned long lock_limit;
Signature · 1 line
2.39.5
RFC v2 13/22 mm/mlock: add API specification for munlock
In reply to Sasha LevinAdd kernel API specification for the munlock() system call.
--- mm/mlock.c | 130 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+)
mm/mlock.c +130 -0
@@ -981,6 +981,136 @@ 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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, LONG_MAX) + KAPI_PARAM_CONSTRAINT("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 + + KAPI_ERROR_COUNT(3) + KAPI_PARAM_COUNT(2) + KAPI_SINCE_VERSION("2.0") + KAPI_SIGNAL_COUNT(1) + KAPI_SIDE_EFFECT_COUNT(5) + KAPI_STATE_TRANS_COUNT(5) + KAPI_LOCK_COUNT(2) +KAPI_EXAMPLES ("munlock(addr, 4096); // Unlock one page\n" + "munlock(addr, len); // Unlock range of pages") +KAPI_NOTES ("No special permissions required to unlock memory. A single munlock() " + "can undo multiple mlock() calls on the same range since locks don't stack.") +KAPI_END_SPEC ; + SYSCALL_DEFINE2(munlock, unsigned long, start, size_t, len) {int ret;
Signature · 1 line
2.39.5
RFC v2 14/22 mm/mlock: add API specification for munlockall
In reply to Sasha LevinAdd kernel API specification for the munlockall() system call.
--- mm/mlock.c | 153 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+)
mm/mlock.c +153 -0
@@ -719,6 +719,12 @@ DEFINE_KERNEL_API_SPEC(sys_mlock) 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_TIMING(KAPI_SIGNAL_TIME_ENTRY) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING | KAPI_SIGNAL_STATE_SLEEPING) + KAPI_SIGNAL_RESTARTABLE KAPI_SIGNAL_END KAPI_EXAMPLES("mlock(addr, 4096); // Lock one page\n"
@@ -854,6 +860,11 @@ DEFINE_KERNEL_API_SPEC(sys_mlock2) 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_TIMING(KAPI_SIGNAL_TIME_ENTRY) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING | KAPI_SIGNAL_STATE_SLEEPING) KAPI_SIGNAL_RESTARTABLE KAPI_SIGNAL_END
@@ -861,6 +872,9 @@ DEFINE_KERNEL_API_SPEC(sys_mlock2) 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_TIMING(KAPI_SIGNAL_TIME_ANYTIME) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_SA_FLAGS_REQ(SA_SIGINFO) KAPI_SIGNAL_END /* Side effects */
@@ -1020,6 +1034,11 @@ DEFINE_KERNEL_API_SPEC(sys_munlock) 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_TIMING(KAPI_SIGNAL_TIME_ENTRY) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING | KAPI_SIGNAL_STATE_SLEEPING) KAPI_SIGNAL_RESTARTABLE KAPI_SIGNAL_END
@@ -1214,6 +1233,11 @@ DEFINE_KERNEL_API_SPEC(sys_mlockall) 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_TIMING(KAPI_SIGNAL_TIME_ENTRY) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING | KAPI_SIGNAL_STATE_SLEEPING) KAPI_SIGNAL_RESTARTABLE KAPI_SIGNAL_END
@@ -1221,6 +1245,9 @@ DEFINE_KERNEL_API_SPEC(sys_mlockall) 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_TIMING(KAPI_SIGNAL_TIME_ANYTIME) + KAPI_SIGNAL_PRIORITY(1) + KAPI_SIGNAL_SA_FLAGS_REQ(SA_SIGINFO) KAPI_SIGNAL_END /* Side effects */
@@ -1394,6 +1421,132 @@ 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_TIMING(KAPI_SIGNAL_TIME_ENTRY) + KAPI_SIGNAL_PRIORITY(0) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_ERROR(-EINTR) + KAPI_SIGNAL_STATE_REQ(KAPI_SIGNAL_STATE_RUNNING | KAPI_SIGNAL_STATE_SLEEPING) + 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 + + KAPI_ERROR_COUNT(2) + KAPI_SINCE_VERSION("2.0") + KAPI_SIGNAL_COUNT(1) + KAPI_SIDE_EFFECT_COUNT(6) + KAPI_STATE_TRANS_COUNT(5) + KAPI_LOCK_COUNT(2) + KAPI_EXAMPLES("munlockall(); // Unlock all pages") +KAPI_NOTES ("Clears VM_LOCKED and VM_LOCKONFAULT from all VMAs and mm->def_flags. " + "A single munlockall() can undo multiple mlockall() calls since locks don't stack.") +KAPI_END_SPEC ; +SYSCALL_DEFINE0 (munlockall) {int ret;
Signature · 1 line
2.39.5
RFC v2 15/22 kernel/api: add debugfs interface for kernel API specifications
In reply to Sasha LevinAdd 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
@@ -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
@@ -4,4 +4,7 @@ # # Core API specification framework -obj-$(CONFIG_KAPI_SPEC) += kernel_api_spec.o +obj-$(CONFIG_KAPI_SPEC) += kernel_api_spec.o + +# Debugfs interface for kernel API specs +obj-$(CONFIG_KAPI_SPEC_DEBUGFS) += kapi_debugfs.o
kernel/api/kapi_debugfs.c new file +340 -0
341 lines not on this page · raw message
Signature · 1 line
2.39.5
RFC v2 16/22 kernel/api: add IOCTL specification infrastructure
In reply to Sasha LevinAdd 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/kernel_api_spec.h | 199 +++++++++++++++++- kernel/api/Makefile | 5 +- kernel/api/ioctl_validation.c | 355 ++++++++++++++++++++++++++++++++ kernel/api/kernel_api_spec.c | 89 +++++++- 4 files changed, 642 insertions(+), 6 deletions(-) create mode 100644 kernel/api/ioctl_validation.c
include/linux/kernel_api_spec.h +195 -4
@@ -779,6 +779,13 @@ struct kernel_api_spec {char connection_termination[KAPI_MAX_DESC_LEN ];char data_transfer_semantics[KAPI_MAX_DESC_LEN ];#endif /* CONFIG_NET */ + +/* IOCTL-specific fields */ +unsigned int cmd;/* IOCTL command number */ +char cmd_name[KAPI_MAX_NAME_LEN ];/* Human-readable command name */ +size_t input_size;/* Size of input structure (0 if none) */ +size_t output_size;/* Size of output structure (0 if none) */ +char file_ops_name[KAPI_MAX_NAME_LEN ];/* Name of the file_operations structure */ } __attribute__((packed));/* Macros for defining API specifications */
@@ -963,6 +970,13 @@ struct kernel_api_spec {#define KAPI_NOTES (n) \ .notes = n, +/** +* KAPI_SINCE_VERSION - Set the since version +* @version: Version string when the API was introduced +*/ +#define KAPI_SINCE_VERSION (version) \ + .since_version = version, +/** * KAPI_DEPRECATED - Mark API as deprecated */
@@ -1105,10 +1119,10 @@ struct kernel_api_spec { .constraint_type = KAPI_CONSTRAINT_MASK, \ .valid_mask = mask, -#define KAPI_FIELD_CONSTRAINT_ENUM (values, count) \ +#define KAPI_FIELD_CONSTRAINT_ENUM (...) \ .constraint_type = KAPI_CONSTRAINT_ENUM, \ - .enum_values = values, \ - .enum_count = count, + .enum_values = __VA_ARGS__, \ + .enum_count = ARRAY_SIZE(__VA_ARGS__),#define KAPI_STRUCT_FIELD_END },
@@ -1171,6 +1185,20 @@ struct kernel_api_spec {#define KAPI_STATE_TRANS_COUNT (n) \ .state_trans_count = n, +/** +* KAPI_ERROR_COUNT - Set the error count +* @count: Number of errors defined +*/ +#define KAPI_ERROR_COUNT (count) \ + .error_count = count, + +/** +* KAPI_PARAM_COUNT - Set the parameter count +* @count: Number of parameters defined +*/ +#define KAPI_PARAM_COUNT (count) \ + .param_count = count, +/* Helper macros for common side effect patterns */ #define KAPI_EFFECTS_MEMORY (KAPI_EFFECT_ALLOC_MEMORY | KAPI_EFFECT_FREE_MEMORY)#define KAPI_EFFECTS_LOCKING (KAPI_EFFECT_LOCK_ACQUIRE | KAPI_EFFECT_LOCK_RELEASE)
@@ -1183,7 +1211,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)/* Common signal timing constants */ #define KAPI_SIGNAL_TIME_ENTRY "entry"
@@ -1495,6 +1523,169 @@ static inline bool kapi_get_param_constraint(const char *api_name, int param_idx#define KAPI_CONSTRAINT_COUNT (n) \ .constraint_count = n, +/* IOCTL-specific functions */ +#ifdef CONFIG_KAPI_SPEC +int kapi_register_ioctl_spec (const struct kernel_api_spec *spec); +void kapi_unregister_ioctl_spec (unsigned int cmd); +const struct kernel_api_spec *kapi_get_ioctl_spec (unsigned int cmd); + +#ifdef CONFIG_KAPI_RUNTIME_CHECKS +struct file ; +int kapi_validate_ioctl (struct file *filp,unsigned int cmd,void __user *arg); +int kapi_validate_ioctl_struct (const struct kernel_api_spec *spec, +const void *data,size_t size); + +/* IOCTL validation wrapper support */ +struct kapi_fops_wrapper { +const struct file_operations *real_fops; +struct file_operations *wrapped_fops; +long (*real_ioctl)(struct file *,unsigned int ,unsigned long ); +}; + +void kapi_register_wrapper (struct kapi_fops_wrapper *wrapper); +long kapi_ioctl_validation_wrapper (struct file *filp,unsigned int cmd, +unsigned long arg); + +/* Macro for defining file operations with automatic IOCTL validation */ +#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_DEFINE_FOPS (name, ...) \ +static const struct file_operations name = { __VA_ARGS__ }; \ +static inline void kapi_init_fops_##name(void) {} + +#endif /* CONFIG_KAPI_RUNTIME_CHECKS */ +#else /* !CONFIG_KAPI_SPEC */ +static inline int kapi_register_ioctl_spec (const struct kernel_api_spec *spec) +{ +return 0 ; +} +static inline void kapi_unregister_ioctl_spec (unsigned int cmd) {} +static inline const struct kernel_api_spec *kapi_get_ioctl_spec (unsigned int cmd) +{ +return NULL ; +} +#endif /* CONFIG_KAPI_SPEC */ + +/* IOCTL-specific macros */ + +/** +* DEFINE_KAPI_IOCTL_SPEC - Define an IOCTL API specification using kernel_api_spec +* @ioctl_name: IOCTL command name/identifier +*/ +#define DEFINE_KAPI_IOCTL_SPEC (ioctl_name) \ + static struct kernel_api_spec __kapi_ioctl_spec_##ioctl_name \ + __used __section(".kapi_specs") = { \ + .name = __stringify(ioctl_name), \ + .api_type = KAPI_API_IOCTL, \ + .version = 1, + +/** +* KAPI_IOCTL_CMD - Set the IOCTL command number +* @cmd_val: The IOCTL command value +*/ +#define KAPI_IOCTL_CMD (cmd_val) \ + .cmd = cmd_val, + +/** +* KAPI_IOCTL_CMD_NAME - Set the IOCTL command name +* @name_str: String name of the command +*/ +#define KAPI_IOCTL_CMD_NAME (name_str) \ + .cmd_name = name_str, + +/** +* KAPI_IOCTL_INPUT_SIZE - Set the input structure size +* @size: Size of the input structure +*/ +#define KAPI_IOCTL_INPUT_SIZE (size) \ + .input_size = size, + +/** +* KAPI_IOCTL_OUTPUT_SIZE - Set the output structure size +* @size: Size of the output structure +*/ +#define KAPI_IOCTL_OUTPUT_SIZE (size) \ + .output_size = size, + +/** +* KAPI_IOCTL_FILE_OPS_NAME - Set the file operations name +* @ops_name: Name of the file_operations structure +*/ +#define KAPI_IOCTL_FILE_OPS_NAME (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 +/* Network operation characteristics macros */ #define KAPI_NET_CONNECTION_ORIENTED \ .is_connection_oriented = true,
kernel/api/Makefile +4 -1
@@ -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 +obj-$(CONFIG_KAPI_SPEC_DEBUGFS) += kapi_debugfs.o
kernel/api/ioctl_validation.c new file +355 -0
355 lines not on this page · raw message
kernel/api/kernel_api_spec.c +88 -1
93 lines not on this page · raw message
Signature · 1 line
2.39.5
RFC v2 17/22 fwctl: add detailed IOCTL API specifications
In reply to Sasha LevinAdd 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 | 285 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 282 insertions(+), 3 deletions(-)
drivers/fwctl/main.c +282 -3
@@ -10,6 +10,7 @@#include <linux/module.h> #include <linux/sizes.h> #include <linux/slab.h> +#include <linux/kernel_api_spec.h> #include <uapi/fwctl/fwctl.h>
@@ -261,12 +262,279 @@ 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 */ + +DEFINE_KAPI_IOCTL_SPEC(fwctl_info) + KAPI_IOCTL_CMD(FWCTL_INFO) + KAPI_IOCTL_CMD_NAME("FWCTL_INFO") + KAPI_IOCTL_INPUT_SIZE(sizeof(struct fwctl_info)) + KAPI_IOCTL_OUTPUT_SIZE(sizeof(struct fwctl_info)) + KAPI_IOCTL_FILE_OPS_NAME("fwctl_fops") + 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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_ENUM) + KAPI_PARAM_ENUM_VALUES(((const s64[]){FWCTL_DEVICE_TYPE_ERROR, + FWCTL_DEVICE_TYPE_MLX5, + FWCTL_DEVICE_TYPE_CXL, + FWCTL_DEVICE_TYPE_PDS})) + KAPI_PARAM_END + + KAPI_PARAM(3, "device_data_len", "__u32", "Length of device data buffer") + KAPI_PARAM_FLAGS(KAPI_PARAM_INOUT) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, 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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EFAULT, -EOPNOTSUPP, -ENODEV})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(3) + KAPI_PARAM_COUNT(5) + KAPI_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 */ +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(fwctl_rpc) + KAPI_IOCTL_CMD(FWCTL_RPC) + KAPI_IOCTL_CMD_NAME("FWCTL_RPC") + KAPI_IOCTL_INPUT_SIZE(sizeof(struct fwctl_rpc)) + KAPI_IOCTL_OUTPUT_SIZE(sizeof(struct fwctl_rpc)) + KAPI_IOCTL_FILE_OPS_NAME("fwctl_fops") + 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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_ENUM) + KAPI_PARAM_ENUM_VALUES(((const s64[]){FWCTL_RPC_CONFIGURATION, + FWCTL_RPC_DEBUG_READ_ONLY, + FWCTL_RPC_DEBUG_WRITE, + FWCTL_RPC_DEBUG_WRITE_FULL})) + KAPI_PARAM_CONSTRAINT("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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, MAX_RPC_LEN) + KAPI_PARAM_END + + KAPI_PARAM(3, "out_len", "__u32", "Length of output buffer") + KAPI_PARAM_FLAGS(KAPI_PARAM_INOUT) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, 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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EMSGSIZE, -EOPNOTSUPP, -EPERM, + -ENOMEM, -EFAULT, -ENODEV})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(6) + KAPI_PARAM_COUNT(6) + KAPI_SINCE_VERSION("6.13") + KAPI_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_RANGE(FWCTL_RPC_CONFIGURATION, FWCTL_RPC_DEBUG_WRITE_FULL) + 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) +KAPI_END_SPEC; + +static int kapi_ioctl_specs_init(void) +{ + return 0; +} + +static void kapi_ioctl_specs_exit(void) +{ +} static void fwctl_device_release(struct device *device) {
@@ -325,7 +593,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 +663,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 +673,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 +689,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
RFC v2 18/22 binder: add detailed IOCTL API specifications
In reply to Sasha LevinAdd 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 | 701 ++++++++++++++++++++++++++++++++ include/linux/kernel_api_spec.h | 3 + 2 files changed, 704 insertions(+)
drivers/android/binder.c +701 -0
@@ -67,6 +67,7 @@#include <linux/task_work.h> #include <linux/sizes.h> #include <linux/ktime.h> +#include <linux/kernel_api_spec.h> #include <uapi/linux/android/binder.h>
@@ -6930,6 +6931,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 +6943,695 @@ 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 */ + +DEFINE_KAPI_IOCTL_SPEC(binder_write_read) + KAPI_IOCTL_CMD(BINDER_WRITE_READ) + KAPI_IOCTL_CMD_NAME("BINDER_WRITE_READ") + KAPI_IOCTL_INPUT_SIZE(sizeof(struct binder_write_read)) + KAPI_IOCTL_OUTPUT_SIZE(sizeof(struct binder_write_read)) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, 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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, SZ_4M) + KAPI_PARAM_END + + KAPI_IOCTL_PARAM_USER_BUF(2, "write_buffer", "User buffer with commands", 0) + + KAPI_PARAM(3, "read_size", "binder_size_t", "Bytes to read") + KAPI_PARAM_FLAGS(KAPI_PARAM_IN) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, SZ_4M) + KAPI_PARAM_END + + KAPI_PARAM(4, "read_consumed", "binder_size_t", "Bytes consumed by driver") + KAPI_PARAM_FLAGS(KAPI_PARAM_OUT) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, SZ_4M) + KAPI_PARAM_END + + KAPI_IOCTL_PARAM_USER_OUT_BUF(5, "read_buffer", "User buffer for responses", 3) + + /* Return value */ + KAPI_RETURN("int", "0 on success, negative errno on failure") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EFAULT, -EINVAL, -EAGAIN, -EINTR, + -ENOMEM, -ECONNREFUSED})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(6) + KAPI_PARAM_COUNT(6) + KAPI_SINCE_VERSION("3.0") + KAPI_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) +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_set_max_threads) + KAPI_IOCTL_CMD(BINDER_SET_MAX_THREADS) + KAPI_IOCTL_CMD_NAME("BINDER_SET_MAX_THREADS") + KAPI_IOCTL_INPUT_SIZE(sizeof(__u32)) + KAPI_IOCTL_OUTPUT_SIZE(0) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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) + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, INT_MAX) + KAPI_PARAM_END + + /* Return value */ + KAPI_RETURN("int", "0 on success, negative errno on failure") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EINVAL, -EFAULT})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(2) + KAPI_PARAM_COUNT(1) + KAPI_SINCE_VERSION("3.0") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_set_context_mgr) + KAPI_IOCTL_CMD(BINDER_SET_CONTEXT_MGR) + KAPI_IOCTL_CMD_NAME("BINDER_SET_CONTEXT_MGR") + KAPI_IOCTL_INPUT_SIZE(0) + KAPI_IOCTL_OUTPUT_SIZE(0) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EBUSY, -EPERM, -ENOMEM})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(3) + KAPI_PARAM_COUNT(0) + KAPI_SINCE_VERSION("3.0") + KAPI_NOTES("Requires CAP_SYS_NICE or proper SELinux permissions") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_set_context_mgr_ext) + KAPI_IOCTL_CMD(BINDER_SET_CONTEXT_MGR_EXT) + KAPI_IOCTL_CMD_NAME("BINDER_SET_CONTEXT_MGR_EXT") + KAPI_IOCTL_INPUT_SIZE(sizeof(struct flat_binder_object)) + KAPI_IOCTL_OUTPUT_SIZE(0) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EINVAL, -EFAULT, -EBUSY, -EPERM, -ENOMEM})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(5) + KAPI_PARAM_COUNT(1) + KAPI_SINCE_VERSION("4.14") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_thread_exit) + KAPI_IOCTL_CMD(BINDER_THREAD_EXIT) + KAPI_IOCTL_CMD_NAME("BINDER_THREAD_EXIT") + KAPI_IOCTL_INPUT_SIZE(0) + KAPI_IOCTL_OUTPUT_SIZE(0) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES((const s64[]){}) + KAPI_RETURN_ERROR_COUNT(0) + KAPI_RETURN_END + + KAPI_ERROR_COUNT(0) + KAPI_PARAM_COUNT(0) + KAPI_SINCE_VERSION("3.0") + KAPI_NOTES("Should be called before thread termination to ensure clean shutdown") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_version) + KAPI_IOCTL_CMD(BINDER_VERSION) + KAPI_IOCTL_CMD_NAME("BINDER_VERSION") + KAPI_IOCTL_INPUT_SIZE(0) + KAPI_IOCTL_OUTPUT_SIZE(sizeof(struct binder_version)) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EINVAL, -EFAULT})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(2) + KAPI_PARAM_COUNT(1) + KAPI_SINCE_VERSION("3.0") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_get_node_info_for_ref) + KAPI_IOCTL_CMD(BINDER_GET_NODE_INFO_FOR_REF) + KAPI_IOCTL_CMD_NAME("BINDER_GET_NODE_INFO_FOR_REF") + KAPI_IOCTL_INPUT_SIZE(sizeof(struct binder_node_info_for_ref)) + KAPI_IOCTL_OUTPUT_SIZE(sizeof(struct binder_node_info_for_ref)) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EINVAL, -EFAULT, -ENOENT})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(3) + KAPI_PARAM_COUNT(3) + KAPI_SINCE_VERSION("4.14") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_get_node_debug_info) + KAPI_IOCTL_CMD(BINDER_GET_NODE_DEBUG_INFO) + KAPI_IOCTL_CMD_NAME("BINDER_GET_NODE_DEBUG_INFO") + KAPI_IOCTL_INPUT_SIZE(sizeof(struct binder_node_debug_info)) + KAPI_IOCTL_OUTPUT_SIZE(sizeof(struct binder_node_debug_info)) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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, + KAPI_PARAM_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, + KAPI_PARAM_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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EFAULT, -EINVAL})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(2) + KAPI_PARAM_COUNT(4) + KAPI_SINCE_VERSION("4.14") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_freeze) + KAPI_IOCTL_CMD(BINDER_FREEZE) + KAPI_IOCTL_CMD_NAME("BINDER_FREEZE") + KAPI_IOCTL_INPUT_SIZE(sizeof(struct binder_freeze_info)) + KAPI_IOCTL_OUTPUT_SIZE(0) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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, + KAPI_PARAM_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, + KAPI_PARAM_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, + KAPI_PARAM_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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EINVAL, -EAGAIN, -EFAULT, -ENOMEM})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(4) + KAPI_PARAM_COUNT(3) + KAPI_SINCE_VERSION("5.9") + KAPI_NOTES("Requires appropriate permissions to freeze other processes") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_get_frozen_info) + KAPI_IOCTL_CMD(BINDER_GET_FROZEN_INFO) + KAPI_IOCTL_CMD_NAME("BINDER_GET_FROZEN_INFO") + KAPI_IOCTL_INPUT_SIZE(sizeof(struct binder_frozen_status_info)) + KAPI_IOCTL_OUTPUT_SIZE(sizeof(struct binder_frozen_status_info)) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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, + KAPI_PARAM_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, + KAPI_PARAM_CONSTRAINT("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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EINVAL, -EFAULT})) + KAPI_RETURN_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") + + KAPI_ERROR_COUNT(2) + KAPI_PARAM_COUNT(3) + KAPI_SINCE_VERSION("5.9") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_enable_oneway_spam_detection) + KAPI_IOCTL_CMD(BINDER_ENABLE_ONEWAY_SPAM_DETECTION) + KAPI_IOCTL_CMD_NAME("BINDER_ENABLE_ONEWAY_SPAM_DETECTION") + KAPI_IOCTL_INPUT_SIZE(sizeof(__u32)) + KAPI_IOCTL_OUTPUT_SIZE(0) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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, + KAPI_PARAM_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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EFAULT})) + KAPI_RETURN_ERROR_COUNT(1) + KAPI_RETURN_END + + /* Errors */ + KAPI_ERROR(0, -EFAULT, "EFAULT", "Failed to copy from user", + "Invalid user pointer provided") + + KAPI_ERROR_COUNT(1) + KAPI_PARAM_COUNT(1) + KAPI_SINCE_VERSION("5.13") +KAPI_END_SPEC; + +DEFINE_KAPI_IOCTL_SPEC(binder_get_extended_error) + KAPI_IOCTL_CMD(BINDER_GET_EXTENDED_ERROR) + KAPI_IOCTL_CMD_NAME("BINDER_GET_EXTENDED_ERROR") + KAPI_IOCTL_INPUT_SIZE(0) + KAPI_IOCTL_OUTPUT_SIZE(sizeof(struct binder_extended_error)) + KAPI_IOCTL_FILE_OPS_NAME("binder_fops") + 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) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_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") + KAPI_RETURN_TYPE(KAPI_TYPE_INT) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_ERROR_VALUES(((const s64[]){-EFAULT})) + KAPI_RETURN_ERROR_COUNT(1) + KAPI_RETURN_END + + /* Errors */ + KAPI_ERROR(0, -EFAULT, "EFAULT", "Failed to copy to user", + "Invalid user pointer provided") + + KAPI_ERROR_COUNT(1) + KAPI_PARAM_COUNT(3) + KAPI_SINCE_VERSION("5.16") + KAPI_NOTES("Error is cleared after reading, subsequent calls return BR_OK") +KAPI_END_SPEC; + +static int kapi_ioctl_specs_init(void) +{ + return 0; +} + +static void kapi_ioctl_specs_exit(void) +{ +} + DEFINE_SHOW_ATTRIBUTE(state); DEFINE_SHOW_ATTRIBUTE(state_hashed); DEFINE_SHOW_ATTRIBUTE(stats);
@@ -7050,6 +7741,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 +7800,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;
include/linux/kernel_api_spec.h +3 -0
@@ -863,6 +863,9 @@ struct kernel_api_spec { .enum_values = values, \ .enum_count = ARRAY_SIZE(values), +#define KAPI_PARAM_SIZE_PARAM_IDX (idx) \ + .size_param_idx = idx, +#define KAPI_PARAM_END },/**
Signature · 1 line
2.39.5
RFC v2 19/22 kernel/api: Add sysfs validation support to kernel API specification framework
In reply to Sasha LevinExtend the kernel API specification infrastructure to support sysfs attributes, enabling runtime validation and comprehensive documentation of sysfs interfaces.
This patch integrates sysfs support into the existing KAPI framework, maintaining consistency across different kernel API types. The implementation adds new parameter types (STRING, BOOL, HEX, BINARY, BITMAP) specifically for sysfs attributes, along with sysfs-specific fields in the kapi_param_spec structure including path, permissions, default values, units, and allowed string values.
Runtime validation functions have been added to check sysfs read/write operations, validate parameter types and ranges, and enforce permission constraints.
--- include/linux/kernel_api_spec.h | 123 +++++++++++- kernel/api/kernel_api_spec.c | 336 +++++++++++++++++++++++++++++++- 2 files changed, 451 insertions(+), 8 deletions(-)
include/linux/kernel_api_spec.h +122 -1
@@ -43,6 +43,11 @@ struct sigaction;* @KAPI_TYPE_FD: File descriptor - validated in process context * @KAPI_TYPE_USER_PTR: User space pointer - validated for access and size * @KAPI_TYPE_PATH: Pathname - validated for access and path limits +* @KAPI_TYPE_STRING: String type - for sysfs and other string attributes +* @KAPI_TYPE_BOOL: Boolean type - for sysfs and other boolean attributes +* @KAPI_TYPE_HEX: Hexadecimal type - for sysfs hex values +* @KAPI_TYPE_BINARY: Binary data type - for sysfs binary attributes +* @KAPI_TYPE_BITMAP: Bitmap type - for sysfs bitmap attributes * @KAPI_TYPE_CUSTOM: Custom/complex types */ enum kapi_param_type {
@@ -58,6 +63,11 @@ enum kapi_param_type {KAPI_TYPE_FD ,/* File descriptor - validated in process context */ KAPI_TYPE_USER_PTR ,/* User space pointer - validated for access and size */ KAPI_TYPE_PATH ,/* Pathname - validated for access and path limits */ +KAPI_TYPE_STRING ,/* String type - for sysfs and other string attributes */ +KAPI_TYPE_BOOL ,/* Boolean type - for sysfs and other boolean attributes */ +KAPI_TYPE_HEX ,/* Hexadecimal type - for sysfs hex values */ +KAPI_TYPE_BINARY ,/* Binary data type - for sysfs binary attributes */ +KAPI_TYPE_BITMAP ,/* Bitmap type - for sysfs bitmap attributes */ KAPI_TYPE_CUSTOM, };
@@ -72,6 +82,10 @@ enum kapi_param_type {* @KAPI_PARAM_USER: User space pointer * @KAPI_PARAM_DMA: DMA-capable memory required * @KAPI_PARAM_ALIGNED: Alignment requirements +* @KAPI_PARAM_SYSFS_READONLY: Sysfs read-only attribute +* @KAPI_PARAM_SYSFS_WRITEONLY: Sysfs write-only attribute +* @KAPI_PARAM_SYSFS_RW: Sysfs read-write attribute +* @KAPI_PARAM_SYSFS_BINARY: Sysfs binary attribute */ enum kapi_param_flags {KAPI_PARAM_IN = (1 <<0 ),
@@ -83,6 +97,10 @@ enum kapi_param_flags {KAPI_PARAM_USER = (1 <<6 ),KAPI_PARAM_DMA = (1 <<7 ),KAPI_PARAM_ALIGNED = (1 <<8 ), +KAPI_PARAM_SYSFS_READONLY = (1 <<9 ), +KAPI_PARAM_SYSFS_WRITEONLY = (1 <<10 ), +KAPI_PARAM_SYSFS_RW = (1 <<11 ), + KAPI_PARAM_SYSFS_BINARY = (1 << 12), };/**
@@ -164,6 +182,13 @@ enum kapi_constraint_type {* @constraints: Additional constraints description * @size_param_idx: Index of parameter that determines size (-1 if fixed size) * @size_multiplier: Multiplier for size calculation (e.g., sizeof(struct)) +* @sysfs_path: Path in sysfs (for sysfs attributes) +* @sysfs_permissions: Sysfs file permissions (e.g., 0644) +* @default_value: Default value as string (for sysfs) +* @units: Units of measurement (e.g., "ms", "bytes") +* @step: Step value for numeric types +* @allowed_strings: Array of allowed string values +* @allowed_string_count: Number of allowed string values */ struct kapi_param_spec {char name[KAPI_MAX_NAME_LEN ];
@@ -183,6 +208,14 @@ struct kapi_param_spec {char constraints[KAPI_MAX_DESC_LEN ];int size_param_idx;/* Index of param that determines size, -1 if N/A */ size_t size_multiplier;/* Size per unit (e.g., sizeof(struct epoll_event)) */ +/* Sysfs-specific fields */ +char sysfs_path[KAPI_MAX_NAME_LEN ]; +umode_t sysfs_permissions; +char default_value[KAPI_MAX_NAME_LEN ]; +char units[32 ]; +s64 step; +const char **allowed_strings; +u32 allowed_string_count; } __attribute__((packed));/**
@@ -667,9 +700,22 @@ struct kapi_addr_family_spec { } __attribute__((packed));#endif /* CONFIG_NET */ +/** +* enum kapi_api_type - Type of kernel API +* @KAPI_API_FUNCTION: Function/syscall API +* @KAPI_API_IOCTL: IOCTL API +* @KAPI_API_SYSFS: Sysfs attribute API +*/ +enum kapi_api_type { +KAPI_API_FUNCTION =0 , +KAPI_API_IOCTL , +KAPI_API_SYSFS , +}; +/** * struct kernel_api_spec - Complete kernel API specification -* @name: Function name +* @name: Function/attribute name +* @api_type: Type of API (function, ioctl, sysfs) * @version: API version * @description: Brief description * @long_description: Detailed description
@@ -698,9 +744,12 @@ struct kapi_addr_family_spec {* @side_effects: Side effect specifications * @state_trans_count: Number of state transition specifications * @state_transitions: State transition specifications +* @subsystem: Subsystem name (for sysfs) +* @device_type: Device type (for sysfs) */ struct kernel_api_spec {char name[KAPI_MAX_NAME_LEN ]; +enum kapi_api_type api_type;u32 version;char description[KAPI_MAX_DESC_LEN ];char long_description[KAPI_MAX_DESC_LEN *4 ];
@@ -786,6 +835,10 @@ struct kernel_api_spec {size_t input_size;/* Size of input structure (0 if none) */ size_t output_size;/* Size of output structure (0 if none) */ char file_ops_name[KAPI_MAX_NAME_LEN ];/* Name of the file_operations structure */ + +/* Sysfs-specific fields */ +char subsystem[KAPI_MAX_NAME_LEN ]; +char device_type[KAPI_MAX_NAME_LEN ]; } __attribute__((packed));/* Macros for defining API specifications */
@@ -1208,6 +1261,47 @@ struct kernel_api_spec {#define KAPI_EFFECTS_RESOURCES (KAPI_EFFECT_RESOURCE_CREATE | KAPI_EFFECT_RESOURCE_DESTROY)#define KAPI_EFFECTS_IO (KAPI_EFFECT_NETWORK | KAPI_EFFECT_FILESYSTEM) +/* Sysfs-specific macros */ + +/** +* DEFINE_SYSFS_API_SPEC - Define a sysfs attribute API specification +* @attr_name: Sysfs attribute name +*/ +#define DEFINE_SYSFS_API_SPEC (attr_name) \ + static struct kernel_api_spec __kapi_sysfs_spec_##attr_name \ + __used __section(".kapi_specs") = { \ + .name = __stringify(attr_name), \ + .api_type = KAPI_API_SYSFS, \ + .version = 1, + +/** +* For sysfs attributes, use KAPI_PARAM with sysfs-specific fields +*/ +#define KAPI_PATH (path) \ + .sysfs_path = path, + +#define KAPI_PERMISSIONS (perms) \ + .sysfs_permissions = perms, + +#define KAPI_DEFAULT (defval) \ + .default_value = defval, + +#define KAPI_UNITS (unit) \ + .units = unit, + +#define KAPI_STEP (s) \ + .step = s, + +#define KAPI_ALLOWED_STRINGS (strings, count) \ + .allowed_strings = strings, \ + .allowed_string_count = count, + +#define KAPI_SUBSYSTEM (subsys) \ + .subsystem = subsys, + +#define KAPI_DEVICE_TYPE (dtype) \ + .device_type = dtype, +/* Helper macros for common patterns */ #define KAPI_PARAM_IN (KAPI_PARAM_IN)
@@ -1329,6 +1423,13 @@ bool kapi_validate_signal_action(const struct kernel_api_spec *spec, int signum, struct sigaction *act);int kapi_get_signal_error (const struct kernel_api_spec *spec,int signum);bool kapi_is_signal_restartable (const struct kernel_api_spec *spec,int signum); + +/* Sysfs validation functions */ +int kapi_validate_sysfs_write (const char *attr_name,const char *buf,size_t count); +int kapi_validate_sysfs_read (const char *attr_name); +int kapi_validate_sysfs_permission (const char *attr_name,umode_t mode); +bool kapi_validate_sysfs_string (const struct kapi_param_spec *param,const char *buf,size_t count); +bool kapi_validate_sysfs_number (const struct kapi_param_spec *param,const char *buf);#else static inline bool kapi_validate_params (const struct kernel_api_spec *spec, ...) {
@@ -1384,6 +1485,26 @@ static inline bool kapi_is_signal_restartable(const struct kernel_api_spec *spec {return false; } +static inline int kapi_validate_sysfs_write (const char *attr_name,const char *buf,size_t count) +{ +return 0 ; +} +static inline int kapi_validate_sysfs_read (const char *attr_name) +{ +return 0 ; +} +static inline int kapi_validate_sysfs_permission (const char *attr_name,umode_t mode) +{ +return 0 ; +} +static inline bool kapi_validate_sysfs_string (const struct kapi_param_spec *param,const char *buf,size_t count) +{ +return true; +} +static inline bool kapi_validate_sysfs_number (const struct kapi_param_spec *param,const char *buf) +{ +return true; +}#endif /* Export/query functions */
kernel/api/kernel_api_spec.c +329 -7
378 lines not on this page · raw message
Signature · 1 line
2.39.5
RFC v2 20/22 block: sysfs API specifications
In reply to Sasha LevinAdd documentation to block sysfs specifications.
--- block/blk-integrity.c | 131 +++++++++++++++++++++++ block/blk-sysfs.c | 243 ++++++++++++++++++++++++++++++++++++++++++ block/genhd.c | 99 +++++++++++++++++ 3 files changed, 473 insertions(+)
block/blk-integrity.c +131 -0
@@ -13,6 +13,8 @@#include <linux/scatterlist.h> #include <linux/export.h> #include <linux/slab.h> +#include <linux/kernel_api_spec.h> +#include <linux/syscall_api_spec.h> #include "blk.h"
@@ -234,6 +236,29 @@ static ssize_t flag_show(struct device *dev, char *page, unsigned char flag)return sysfs_emit (page,"%d\n" , !(bi->flags & flag)); } +/* +* Sysfs API specifications for integrity attributes +*/ +DEFINE_SYSFS_API_SPEC(format) + KAPI_DESCRIPTION("Metadata format for integrity") +KAPI_LONG_DESC ("Metadata format for integrity capable block device. " +"E.g. T10-DIF-TYPE1-CRC. This field describes the type of T10 " +"Protection Information that the block device can send and receive. " +"If the device can store application integrity metadata but " +"no T10 Protection Information profile is used, this field " +"contains 'nop'. If the device does not support integrity " + "metadata, this field contains 'none'.") + KAPI_PARAM_COUNT(1) + KAPI_PARAM(0, "format", "string", "Integrity metadata format") + KAPI_PARAM_TYPE(KAPI_TYPE_STRING) + KAPI_PERMISSIONS(0444) + KAPI_PATH("/sys/block/<disk>/integrity/format") +KAPI_PARAM_FLAGS (KAPI_PARAM_SYSFS_READONLY) + KAPI_PARAM_END + KAPI_SUBSYSTEM("block") + KAPI_EXAMPLES("cat /sys/block/sda/integrity/format") +KAPI_END_SPEC ; +static ssize_t format_show (struct device *dev,struct device_attribute *attr,char *page) {
@@ -244,6 +269,33 @@ static ssize_t format_show(struct device *dev, struct device_attribute *attr,return sysfs_emit (page,"%s\n" ,blk_integrity_profile_name (bi)); } +DEFINE_SYSFS_API_SPEC(tag_size) + KAPI_DESCRIPTION("Integrity tag size") +KAPI_LONG_DESC ("Number of bytes of integrity tag space available per " +"protection_interval_bytes, which is typically " +"the device's logical block size. " +"This field describes the size of the application tag " +"if the storage device is formatted with T10 Protection " + "Information and permits use of the application tag.") + KAPI_PARAM_COUNT(1) + KAPI_PARAM(0, "tag_size", "unsigned int", "Tag size in bytes") + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PERMISSIONS(0444) + KAPI_PATH("/sys/block/<disk>/integrity/tag_size") + KAPI_PARAM_RANGE(0, 65535) + KAPI_UNITS("bytes") +KAPI_PARAM_FLAGS (KAPI_PARAM_SYSFS_READONLY) + KAPI_PARAM_END + KAPI_SUBSYSTEM("block") + KAPI_EXAMPLES("cat /sys/block/sda/integrity/tag_size") +KAPI_NOTES ("If the device does not support T10 Protection Information (even if the " +"device provides application integrity metadata space), this field is set to 0. " +"The owner of this tag space is the owner of the block device. The filesystem " +"can use this extra space to tag sectors as they see fit. Because the tag space " +"is limited, the block interface allows tagging bigger chunks by way of interleaving. " + "This way, 8*16 bits of information can be attached to a typical 4KB filesystem block.") +KAPI_END_SPEC ; +static ssize_t tag_size_show (struct device *dev,struct device_attribute *attr,char *page) {
@@ -252,6 +304,26 @@ static ssize_t tag_size_show(struct device *dev, struct device_attribute *attr,return sysfs_emit (page,"%u\n" , bi->tag_size); } +DEFINE_SYSFS_API_SPEC(protection_interval_bytes) + KAPI_DESCRIPTION("Protection interval size") +KAPI_LONG_DESC ("Describes the number of data bytes which are protected by one " +"integrity tuple. Typically the device's logical block size. " +"For example, a 512-byte sector with 8-byte integrity metadata " + "would have a protection interval of 512 bytes.") + KAPI_PARAM_COUNT(1) + KAPI_PARAM(0, "protection_interval_bytes", "unsigned int", "Protection interval in bytes") + KAPI_PARAM_TYPE(KAPI_TYPE_UINT) + KAPI_PERMISSIONS(0444) + KAPI_PATH("/sys/block/<disk>/integrity/protection_interval_bytes") + KAPI_PARAM_RANGE(0, 65536) + KAPI_UNITS("bytes") +KAPI_PARAM_FLAGS (KAPI_PARAM_SYSFS_READONLY) + KAPI_PARAM_END + KAPI_SUBSYSTEM("block") + KAPI_EXAMPLES("cat /sys/block/sda/integrity/protection_interval_bytes") + KAPI_NOTES("This is typically the same as the device's logical block size") +KAPI_END_SPEC ; +static ssize_t protection_interval_bytes_show (struct device *dev,struct device_attribute *attr,char *page)
@@ -275,6 +347,25 @@ static ssize_t read_verify_show(struct device *dev,return flag_show (dev, page,BLK_INTEGRITY_NOVERIFY ); } +DEFINE_SYSFS_API_SPEC(read_verify) + KAPI_DESCRIPTION("Read request integrity verification") +KAPI_LONG_DESC ("Indicates whether the block layer should verify the integrity " +"of read requests serviced by devices that support sending " +"integrity metadata. A value of 1 enables verification, while " +"0 disables it. When enabled, the block layer will check " + "integrity metadata on read operations.") + KAPI_PARAM_COUNT(1) + KAPI_PARAM(0, "read_verify", "bool", "Enable read integrity verification") + KAPI_PARAM_TYPE(KAPI_TYPE_BOOL) + KAPI_PERMISSIONS(0644) + KAPI_PATH("/sys/block/<disk>/integrity/read_verify") +KAPI_PARAM_FLAGS (KAPI_PARAM_SYSFS_RW) + KAPI_PARAM_END + KAPI_SUBSYSTEM("block") + KAPI_EXAMPLES("echo 1 > /sys/block/sda/integrity/read_verify") + KAPI_NOTES("This attribute only has effect if the device supports integrity metadata") +KAPI_END_SPEC ; +static ssize_t write_generate_store (struct device *dev,struct device_attribute *attr,const char *page,size_t count)
@@ -288,6 +379,46 @@ static ssize_t write_generate_show(struct device *dev,return flag_show (dev, page,BLK_INTEGRITY_NOGENERATE ); } +DEFINE_SYSFS_API_SPEC(write_generate) + KAPI_DESCRIPTION("Write request integrity generation") +KAPI_LONG_DESC ("Indicates whether the block layer should automatically generate " +"checksums for write requests bound for devices that support " +"receiving integrity metadata. A value of 1 enables generation, " +"while 0 disables it. When enabled, the block layer will compute " + "and attach integrity metadata to write operations.") + KAPI_PARAM_COUNT(1) + KAPI_PARAM(0, "write_generate", "bool", "Enable write integrity generation") + KAPI_PARAM_TYPE(KAPI_TYPE_BOOL) + KAPI_PERMISSIONS(0644) + KAPI_PATH("/sys/block/<disk>/integrity/write_generate") +KAPI_PARAM_FLAGS (KAPI_PARAM_SYSFS_RW) + KAPI_PARAM_END + KAPI_SUBSYSTEM("block") + KAPI_EXAMPLES("echo 1 > /sys/block/sda/integrity/write_generate") + KAPI_NOTES("This attribute only has effect if the device supports integrity metadata") +KAPI_END_SPEC ; + +DEFINE_SYSFS_API_SPEC(device_is_integrity_capable) + KAPI_DESCRIPTION("Device integrity capability") +KAPI_LONG_DESC ("Indicates whether a storage device is capable of storing " +"integrity metadata. Set if the device is T10 PI-capable. " +"This flag is set to 1 if the storage media is formatted " +"with T10 Protection Information. If the storage media is " +"not formatted with T10 Protection Information, this flag " +"is set to 0. This is a key indicator for whether the device " +"supports end-to-end data protection using standards like " + "T10 DIF (Data Integrity Field) for SCSI devices.") + KAPI_PARAM_COUNT(1) + KAPI_PARAM(0, "device_is_integrity_capable", "bool", "Device integrity capability flag") + KAPI_PARAM_TYPE(KAPI_TYPE_BOOL) + KAPI_PERMISSIONS(0444) + KAPI_PATH("/sys/block/<disk>/integrity/device_is_integrity_capable") +KAPI_PARAM_FLAGS (KAPI_PARAM_SYSFS_READONLY) + KAPI_PARAM_END + KAPI_SUBSYSTEM("block") + KAPI_EXAMPLES("cat /sys/block/sda/integrity/device_is_integrity_capable") +KAPI_END_SPEC ; +static ssize_t device_is_integrity_capable_show (struct device *dev,struct device_attribute *attr,char *page)
block/blk-sysfs.c +243 -0
288 lines not on this page · raw message
block/genhd.c +99 -0
135 lines not on this page · raw message
Signature · 1 line
2.39.5
RFC v2 21/22 net/socket: add API specification for socket()
In reply to Sasha LevinAdd kernel API specification for the socket() system call, documenting all aspects of socket creation.
--- net/socket.c | 489 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 489 insertions(+)
net/socket.c +489 -0
@@ -78,6 +78,7 @@#include <linux/pseudo_fs.h> #include <linux/security.h> #include <linux/syscalls.h> +#include <linux/syscall_api_spec.h> #include <linux/compat.h> #include <linux/kmod.h> #include <linux/audit.h>
@@ -89,6 +90,7 @@#include <linux/nospec.h> #include <linux/indirect_call_wrapper.h> #include <linux/io_uring/net.h> +#include <linux/un.h> #include <linux/uaccess.h> #include <asm/unistd.h>
@@ -1692,6 +1694,493 @@ int __sys_socket(int family, int type, int protocol)return sock_map_fd (sock, flags & (O_CLOEXEC |O_NONBLOCK )); } +DEFINE_KERNEL_API_SPEC(sys_socket) + KAPI_DESCRIPTION("Create an endpoint for communication") +KAPI_LONG_DESC ("Creates an endpoint for communication and returns a file descriptor " +"that refers to that endpoint. The file descriptor returned by a successful " +"call will be the lowest-numbered file descriptor not currently open for " +"the process. The socket has the indicated type, which specifies the " +"communication semantics. The socket() system call is the foundation of " +"all network programming in Linux, providing access to various network " + "protocols and communication mechanisms.") + KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) + + KAPI_PARAM(0, "family", "int", "Protocol/address family (domain)") + KAPI_PARAM_FLAGS(KAPI_PARAM_IN) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_RANGE) + KAPI_PARAM_RANGE(0, 45) /* AF_UNSPEC to AF_MCTP */ + KAPI_PARAM_CONSTRAINT("Common families: AF_UNIX (1), AF_INET (2), AF_INET6 (10), " + "AF_NETLINK (16), AF_PACKET (17). Others: AF_BLUETOOTH (31), AF_CAN (29), " + "AF_TIPC (30), AF_VSOCK (40), AF_XDP (44). Range: 0-45 (AF_MCTP). " + "PF_* are aliases. Negative or >= 46 returns EAFNOSUPPORT.") + KAPI_PARAM_END + + KAPI_PARAM(1, "type", "int", "Socket type with optional flags") + KAPI_PARAM_FLAGS(KAPI_PARAM_IN) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_MASK) + KAPI_PARAM_VALID_MASK(SOCK_TYPE_MASK | SOCK_CLOEXEC | SOCK_NONBLOCK) + KAPI_PARAM_CONSTRAINT("Types: SOCK_STREAM (1), SOCK_DGRAM (2), SOCK_RAW (3), " + "SOCK_RDM (4), SOCK_SEQPACKET (5), SOCK_DCCP (6), SOCK_PACKET (10-obsolete). " + "Flags (since 2.6.27): SOCK_NONBLOCK, SOCK_CLOEXEC. Range: 0-10.") + KAPI_PARAM_END + + KAPI_PARAM(2, "protocol", "int", "Protocol within the family") + KAPI_PARAM_FLAGS(KAPI_PARAM_IN) + KAPI_PARAM_TYPE(KAPI_TYPE_INT) + KAPI_PARAM_CONSTRAINT_TYPE(KAPI_CONSTRAINT_NONE) + KAPI_PARAM_CONSTRAINT("Usually 0 to select the default protocol for the given family and type. " + "For AF_INET/AF_INET6: IPPROTO_TCP (6), IPPROTO_UDP (17), IPPROTO_ICMP (1), " + "IPPROTO_RAW (255), etc. Must be >= 0 and < IPPROTO_MAX. " + "For AF_UNIX: only 0 or PF_UNIX (1) accepted. " + "For AF_PACKET: network byte order Ethernet protocol (e.g., ETH_P_IP). " + "For AF_NETLINK: NETLINK_ROUTE, NETLINK_AUDIT, etc. (0-31). " + "Protocol value passed through update_socket_protocol() BPF hook which may modify it.") + KAPI_PARAM_END + + KAPI_RETURN("long", "File descriptor on success; negative error code on failure. " + "On success, returns the lowest available file descriptor. " + "The descriptor is automatically placed in the process's file descriptor table. " + "If SOCK_CLOEXEC is set, FD_CLOEXEC is set on the descriptor. " + "If SOCK_NONBLOCK is set, O_NONBLOCK is set on the file.") + KAPI_RETURN_TYPE(KAPI_TYPE_FD) + KAPI_RETURN_CHECK_TYPE(KAPI_RETURN_ERROR_CHECK) + KAPI_RETURN_SUCCESS(0) + KAPI_RETURN_END + + /* Core error codes from __sock_create() and __sys_socket() */ + KAPI_ERROR(0, -EAFNOSUPPORT, "EAFNOSUPPORT", "Address family not supported", + "The implementation does not support the specified address family. " + "Returned when: family < 0 || family >= NPROTO (46); " + "protocol family not registered in net_families[]; " + "protocol family module cannot be loaded; " + "try_module_get() fails on protocol family owner.") +KAPI_ERROR (1 , -EINVAL ,"EINVAL" ,"Invalid argument" , +"Invalid argument specified. Returned when: " +"type < 0 || type >= SOCK_MAX (11); " +"invalid flags in type ((type & ~SOCK_TYPE_MASK) & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)); " + "other protocol-specific validation failures.") +KAPI_ERROR (2 , -ENFILE ,"ENFILE" ,"File table overflow" , +"The system-wide limit on the total number of open files has been reached. " + "Returned when sock_alloc() fails due to new_inode_pseudo() failure.") +KAPI_ERROR (3 , -EMFILE ,"EMFILE" ,"Too many open files" , +"The per-process limit on the number of open file descriptors has been reached. " + "Returned when sock_map_fd() cannot allocate a new file descriptor.") +KAPI_ERROR (4 , -ENOMEM ,"ENOMEM" ,"Out of memory" , +"Insufficient kernel memory available. Can occur in: " +"sk_alloc() when allocating sock structure; " +"protocol-specific init functions; " +"security_sk_alloc() in LSM hooks; " + "various kmalloc()/kmem_cache_alloc() calls.") +KAPI_ERROR (5 , -ENOBUFS ,"ENOBUFS" ,"No buffer space available" , +"Insufficient resources to create socket. Similar to ENOMEM but used by " + "some protocol families (e.g., AF_PACKET) to indicate resource exhaustion.") +KAPI_ERROR (6 , -EPROTONOSUPPORT ,"EPROTONOSUPPORT" ,"Protocol not supported" , +"The protocol is not supported within this domain. Returned when: " +"AF_UNIX: protocol != 0 && protocol != PF_UNIX; " +"AF_INET/AF_INET6: protocol not found in inetsw[] array; " + "AF_NETLINK: protocol < 0 || protocol >= MAX_LINKS (32).") +KAPI_ERROR (7 , -ESOCKTNOSUPPORT ,"ESOCKTNOSUPPORT" ,"Socket type not supported" , +"The socket type is not supported within this domain. Returned when: " +"AF_UNIX: type not in {STREAM, DGRAM, SEQPACKET, RAW}; " +"AF_INET/AF_INET6: no matching (type, protocol) in inetsw[]; " +"AF_PACKET: type not in {DGRAM, RAW, PACKET}; " + "AF_NETLINK: type not in {RAW, DGRAM}.") +KAPI_ERROR (8 , -EPERM ,"EPERM" ,"Operation not permitted" , +"Permission denied due to insufficient privileges. Returned when: " +"AF_INET/AF_INET6 with SOCK_RAW: missing CAP_NET_RAW; " +"AF_PACKET: missing CAP_NET_RAW; " + "Some protocol families may have additional restrictions.") +KAPI_ERROR (9 , -EACCES ,"EACCES" ,"Permission denied" , +"Permission denied by Linux Security Module (SELinux, AppArmor, etc.). " + "Returned by security_socket_create() or security_socket_post_create() hooks.") +KAPI_ERROR (10 , -EAGAIN ,"EAGAIN" ,"Resource temporarily unavailable" , +"Transient resource shortage. Can be returned by some protocol families " + "during initialization when resources are temporarily exhausted.") +KAPI_ERROR (11 , -EINTR ,"EINTR" ,"Interrupted system call" , +"Operation interrupted by signal. Rare for socket() but possible if " + "module loading is interrupted or during memory allocation with GFP_KERNEL.") +KAPI_ERROR (12 , -EFAULT ,"EFAULT" ,"Bad address" , +"Not directly returned by socket() since all parameters are values, not pointers. " + "Listed for completeness as it appears in documentation.") +KAPI_ERROR (13 , -ENOSYS ,"ENOSYS" ,"Function not implemented" , +"Can occur in containers using alt-syscall where socket() is not whitelisted, " + "or on architectures where socket() is not implemented.") + + KAPI_ERROR_COUNT(14) + KAPI_PARAM_COUNT(3) + KAPI_SINCE_VERSION("4.2BSD") + +KAPI_EXAMPLES ("/* Create a TCP socket */\n" +"int tcp_sock = socket(AF_INET, SOCK_STREAM, 0);\n" +"if (tcp_sock < 0) {\n" +" perror(\"socket\");\n" +" exit(EXIT_FAILURE);\n" +"}\n\n" +"/* Create a non-blocking UDP socket with close-on-exec */\n" +"int udp_sock = socket(AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);\n\n" +"/* Create a raw ICMP socket (requires CAP_NET_RAW) */\n" +"int raw_sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);\n\n" +"/* Create a Unix domain datagram socket */\n" +"int unix_sock = socket(AF_UNIX, SOCK_DGRAM, 0);\n\n" +"/* Create a netlink socket for routing information */\n" +"int nl_sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);\n\n" +"/* Create a packet socket for raw Ethernet frames (requires CAP_NET_RAW) */\n" +"int packet_sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));\n\n" +"/* Create a Bluetooth L2CAP socket */\n" + "int bt_sock = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP);") + +KAPI_NOTES ("Implementation details:\n" +"- Uses RCU to safely access net_families[] array\n" +"- May trigger automatic module loading via request_module(\"net-pf-%d\", family)\n" +"- Allocates inode from sock_inode_cache via new_inode_pseudo()\n" +"- Each protocol family registers via sock_register() with unique family number\n" +"- Socket creation involves: sock_alloc() -> pf->create() -> sock_map_fd()\n" +"- The update_socket_protocol() BPF hook can modify the protocol parameter\n" +"- LSM hooks called: security_socket_create() and security_socket_post_create()\n" +"- Creates struct socket (VFS layer) and struct sock (network layer)\n" +"- Socket state initialized to SS_UNCONNECTED\n" +"- File operations set to socket_file_ops\n" +"- The (PF_INET, SOCK_PACKET) combination is deprecated since Linux 2.0\n" +"Build-time checks ensure SOCK_CLOEXEC == O_CLOEXEC and flag consistency" ) + + /* Lock specifications */ + KAPI_LOCK(0, "rcu_read_lock", KAPI_LOCK_RCU) + KAPI_LOCK_ACQUIRED + KAPI_LOCK_RELEASED + KAPI_LOCK_DESC("Protects net_families[] array access during protocol family lookup. " + "Acquired before rcu_dereference(net_families[family]), " + "released after pf->create() call or on error path.") + KAPI_LOCK_END + + KAPI_LOCK(1, "pf->owner module refcount", KAPI_LOCK_CUSTOM) +KAPI_LOCK_ACQUIRED + KAPI_LOCK_RELEASED +KAPI_LOCK_DESC ("Prevents protocol family module unload during socket creation. " +"try_module_get(pf->owner) before pf->create(), " + "module_put(pf->owner) after completion.") + KAPI_LOCK_END + + KAPI_LOCK(2, "sock->ops->owner module refcount", KAPI_LOCK_CUSTOM) + KAPI_LOCK_ACQUIRED + KAPI_LOCK_DESC("Prevents socket operations module unload during socket lifetime. " + "try_module_get(sock->ops->owner) after successful creation, " + "released only on sock_release() when socket is closed.") + KAPI_LOCK_END + + KAPI_LOCK_COUNT(3) + + /* Signal handling */ + KAPI_SIGNAL(0, 0, "Module loading", KAPI_SIGNAL_RECEIVE, KAPI_SIGNAL_ACTION_RESTART) + KAPI_SIGNAL_CONDITION("CONFIG_MODULES && request_module() called") +KAPI_SIGNAL_DESC ("Module loading via request_module() is interruptible. " + "Signal delivery causes -EINTR from modprobe execution.") +KAPI_SIGNAL_TIMING (KAPI_SIGNAL_TIME_DURING) + KAPI_SIGNAL_INTERRUPTIBLE + KAPI_SIGNAL_END + + KAPI_SIGNAL_COUNT(1) + + /* Side effects */ + KAPI_SIDE_EFFECT(0, KAPI_EFFECT_ALLOC_MEMORY | KAPI_EFFECT_RESOURCE_CREATE, + "socket structures", + "Allocates struct socket (VFS), struct sock (network), and protocol-specific data. " + "Memory from: sock_inode_cache, protocol's slab cache, and general kmalloc.") + KAPI_EFFECT_CONDITION("Always occurs on successful socket creation") + KAPI_EFFECT_REVERSIBLE + KAPI_SIDE_EFFECT_END + + KAPI_SIDE_EFFECT(1, KAPI_EFFECT_RESOURCE_CREATE, + "file descriptor", + "Allocates new file descriptor at lowest available index. " + "Creates struct file with socket_file_ops. Sets up file->private_data = socket.") + KAPI_EFFECT_CONDITION("Always occurs on successful socket creation") + KAPI_EFFECT_REVERSIBLE + KAPI_SIDE_EFFECT_END + + KAPI_SIDE_EFFECT(2, KAPI_EFFECT_FILESYSTEM, + "protocol module", + "May trigger request_module(\"net-pf-%d\", family) to load protocol module. " + "Executes /sbin/modprobe in userspace context.") + KAPI_EFFECT_CONDITION("CONFIG_MODULES=y && !net_families[family] && first attempt") + KAPI_SIDE_EFFECT_END + +KAPI_SIDE_EFFECT (3 ,KAPI_EFFECT_MODIFY_STATE , +"LSM and audit" , +"Calls security_socket_create() pre-creation and security_socket_post_create() " + "post-creation. May generate audit events. SELinux/AppArmor may deny.") + KAPI_EFFECT_CONDITION("CONFIG_SECURITY=y or CONFIG_AUDIT=y") + KAPI_SIDE_EFFECT_END + +KAPI_SIDE_EFFECT (4 ,KAPI_EFFECT_MODIFY_STATE , +"BPF programs" , +"update_socket_protocol() hook can modify protocol parameter. " + "BPF_CGROUP_RUN_PROG_INET_SOCK() may run for AF_INET/AF_INET6.") + KAPI_EFFECT_CONDITION("BPF programs attached to cgroup or socket hooks") + KAPI_SIDE_EFFECT_END + +KAPI_SIDE_EFFECT (5 ,KAPI_EFFECT_NETWORK |KAPI_EFFECT_HARDWARE , +"network stack" , +"Initializes protocol-specific state. May interact with network hardware " + "(e.g., AF_PACKET binds to network interface).") + KAPI_EFFECT_CONDITION("Protocol family specific") + KAPI_SIDE_EFFECT_END + +KAPI_SIDE_EFFECT (6 ,KAPI_EFFECT_MODIFY_STATE , +"resource accounting" , +"Updates task and memory cgroup accounting. Charges socket memory to owner. " + "Increments global socket counters.") + KAPI_EFFECT_CONDITION("CONFIG_MEMCG=y or other accounting enabled") + KAPI_SIDE_EFFECT_END + +KAPI_SIDE_EFFECT_COUNT (7 ) + + /* State transitions */ +KAPI_STATE_TRANS (0 ,"file descriptor table" , +"n open descriptors" ,"n+1 open descriptors" , + "New fd allocated at min(available). Updates current->files->fd_array[]") + KAPI_STATE_TRANS_END + + KAPI_STATE_TRANS(1, "socket state machine", + "non-existent", "SS_UNCONNECTED", + "Socket created in unconnected state, ready for bind() or connect()") + KAPI_STATE_TRANS_END + + KAPI_STATE_TRANS(2, "network namespace", + "no socket", "socket registered", + "Socket associated with current->nsproxy->net_ns network namespace") + KAPI_STATE_TRANS_END + + KAPI_STATE_TRANS(3, "memory accounting", + "pre-allocation", "memory charged", + "Socket memory charged to owner's memcg and rlimits") + KAPI_STATE_TRANS_END + + KAPI_STATE_TRANS_COUNT(4) + + /* Networking-specific specifications */ + + /* Socket state specification */ + KAPI_SOCKET_STATE_REQ(KAPI_SOCK_STATE_UNSPEC) + KAPI_SOCKET_STATE_RESULT(KAPI_SOCK_STATE_OPEN) + KAPI_SOCKET_STATE_COND("Successful socket creation") + KAPI_SOCKET_STATE_PROTOS(KAPI_PROTO_ALL) + KAPI_SOCKET_STATE_END + + /* Protocol-specific behaviors - detailed specifications */ + KAPI_PROTOCOL_BEHAVIOR(0, KAPI_PROTO_TCP, + "TCP (Transmission Control Protocol) creates reliable, ordered, connection-oriented " + "byte streams. Features: 3-way handshake connection establishment; sequence numbers " + "for ordering; acknowledgments and retransmissions for reliability; flow control " + "via sliding window; congestion control (Reno/CUBIC/BBR); Nagle algorithm for " + "small packet aggregation; keep-alive probes; urgent data via MSG_OOB. " + "Socket combines (AF_INET/AF_INET6, SOCK_STREAM, IPPROTO_TCP).") + KAPI_PROTOCOL_FLAGS(0, "TCP-specific socket options via SOL_TCP level") + KAPI_PROTOCOL_BEHAVIOR_END + +KAPI_PROTOCOL_BEHAVIOR (1 ,KAPI_PROTO_UDP , +"UDP (User Datagram Protocol) creates unreliable, connectionless datagram service. " +"Features: no connection establishment; best-effort delivery; message boundaries " +"preserved; no flow/congestion control; optional checksums; multicast/broadcast " +"capable; lower overhead than TCP. Maximum datagram size 65507 bytes (65535 - " +"IP header - UDP header). connect() on UDP socket sets default destination. " + "Socket combines (AF_INET/AF_INET6, SOCK_DGRAM, IPPROTO_UDP).") + KAPI_PROTOCOL_FLAGS(0, "UDP-specific options like UDP_CORK via SOL_UDP") + KAPI_PROTOCOL_BEHAVIOR_END + +KAPI_PROTOCOL_BEHAVIOR (2 ,KAPI_PROTO_UNIX , +"Unix domain sockets provide high-performance local IPC with filesystem-based " +"addressing or Linux abstract namespace. Features: reliable delivery; in-order " +"semantics for SOCK_STREAM; message boundaries for SOCK_DGRAM/SOCK_SEQPACKET; " +"credential passing via SCM_CREDENTIALS; file descriptor passing via SCM_RIGHTS; " +"no network overhead; kernel-only data path. SOCK_RAW mapped to SOCK_DGRAM. " + "Maximum datagram size 130688 bytes by default (net.core.wmem_max).") + KAPI_PROTOCOL_FLAGS(0, "No Unix-specific socket level; uses SOL_SOCKET only") + KAPI_PROTOCOL_BEHAVIOR_END + +KAPI_PROTOCOL_BEHAVIOR (3 ,KAPI_PROTO_RAW , +"Raw sockets provide direct access to network layer (IP) or link layer (Ethernet). " +"Features: receive/send raw IP packets; implement custom protocols; packet " +"sniffing; bypass transport layer. IP header included based on IP_HDRINCL option. " +"Protocol field specifies which protocol to receive (IPPROTO_ICMP, etc.) or " +"IPPROTO_RAW to send any. Link layer access via AF_PACKET. Requires CAP_NET_RAW " + "capability. Used by ping, traceroute, nmap, tcpdump.") + KAPI_PROTOCOL_FLAGS(0, "IP_HDRINCL and raw-specific options via SOL_RAW") + KAPI_PROTOCOL_BEHAVIOR_END + +KAPI_PROTOCOL_BEHAVIOR (4 ,KAPI_PROTO_PACKET , +"Packet sockets provide direct access to link layer (Layer 2). Features: " +"send/receive raw Ethernet frames; implement network protocols in userspace; " +"packet capture and injection; access to all packets on interface. SOCK_RAW " +"provides full Layer 2 header; SOCK_DGRAM provides cooked packets without " +"Layer 2 header. Protocol specifies Ethernet protocol (ETH_P_IP, ETH_P_ALL). " + "High-performance variants: PACKET_MMAP, PACKET_FANOUT. Requires CAP_NET_RAW.") + KAPI_PROTOCOL_FLAGS(0, "Extensive options via SOL_PACKET level") + KAPI_PROTOCOL_BEHAVIOR_END + +KAPI_PROTOCOL_BEHAVIOR (5 ,KAPI_PROTO_NETLINK , +"Netlink sockets provide kernel/user-space communication interface. Features: " +"reliable datagram service; multicast groups; message-based; TLV attributes; " +"async notifications; used for routing, netfilter, audit, SELinux, etc. " +"Protocol specifies subsystem: NETLINK_ROUTE (routing/link), NETLINK_FIREWALL, " +"NETLINK_NETFILTER, NETLINK_AUDIT, etc. No special capabilities for most " + "protocols except administrative operations.") + KAPI_PROTOCOL_FLAGS(0, "Netlink-specific options and attributes") + KAPI_PROTOCOL_BEHAVIOR_END + +KAPI_PROTOCOL_BEHAVIOR (6 ,KAPI_PROTO_SCTP , +"SCTP (Stream Control Transmission Protocol) provides reliable, message-oriented " +"service with multi-streaming and multi-homing. Features: message boundaries; " +"ordered/unordered delivery; multi-streaming prevents head-of-line blocking; " +"multi-homing for redundancy; heartbeats; partial reliability extension. " +"4-way handshake with cookie mechanism prevents SYN floods. " + "Socket combines (AF_INET/AF_INET6, SOCK_STREAM/SOCK_SEQPACKET, IPPROTO_SCTP).") + KAPI_PROTOCOL_FLAGS(0, "SCTP-specific options via SOL_SCTP level") + KAPI_PROTOCOL_BEHAVIOR_END + +KAPI_PROTOCOL_BEHAVIOR_COUNT (7 ) + + /* Buffer specification - not applicable for socket creation */ + KAPI_BUFFER_SPEC(0) + KAPI_BUFFER_SIZE(0, 0, 0) +KAPI_BUFFER_END + +/* Async specification - socket creation is synchronous */ + KAPI_ASYNC_SPEC(KAPI_ASYNC_BLOCK, 0) +KAPI_ASYNC_END + +/* Network-specific errors are already covered in main error list */ + +/* Address families supported - comprehensive list */ + KAPI_ADDR_FAMILY(0, AF_UNIX, "AF_UNIX/AF_LOCAL", sizeof(struct sockaddr_un), 2, 110) + KAPI_ADDR_FORMAT("struct sockaddr_un { sa_family_t sun_family; char sun_path[108]; }") + KAPI_ADDR_FEATURES(false, false, false) +KAPI_ADDR_SPECIAL ("Abstract namespace: sun_path[0] == '\\0'; " +"Autobind: empty sun_path gets random abstract address; " + "Filesystem: normal paths follow filesystem permissions") + KAPI_ADDR_PORTS(0, 0) /* No port concept */ + KAPI_ADDR_FAMILY_END + + KAPI_ADDR_FAMILY(1, AF_INET, "AF_INET", sizeof(struct sockaddr_in), 16, 16) +KAPI_ADDR_FORMAT ("struct sockaddr_in { sa_family_t sin_family; __be16 sin_port; " + "struct in_addr sin_addr; char sin_zero[8]; }") + KAPI_ADDR_FEATURES(true, true, true) +KAPI_ADDR_SPECIAL ("INADDR_ANY (0.0.0.0) - wildcard; " +"INADDR_LOOPBACK (127.0.0.1) - loopback; " +"INADDR_BROADCAST (255.255.255.255) - broadcast; " + "224.0.0.0/4 - multicast range") + KAPI_ADDR_PORTS(0, 65535) /* 0 = ephemeral port assignment */ + KAPI_ADDR_FAMILY_END + + KAPI_ADDR_FAMILY(2, AF_INET6, "AF_INET6", sizeof(struct sockaddr_in6), 28, 28) +KAPI_ADDR_FORMAT ("struct sockaddr_in6 { sa_family_t sin6_family; __be16 sin6_port; " + "__be32 sin6_flowinfo; struct in6_addr sin6_addr; __u32 sin6_scope_id; }") + KAPI_ADDR_FEATURES(true, true, false) /* No broadcast in IPv6 */ +KAPI_ADDR_SPECIAL ("in6addr_any (::) - wildcard; " +"in6addr_loopback (::1) - loopback; " +"ff00::/8 - multicast range; " +"fe80::/10 - link-local; " + "::ffff:0:0/96 - IPv4-mapped addresses") + KAPI_ADDR_PORTS(0, 65535) + KAPI_ADDR_FAMILY_END + + KAPI_ADDR_FAMILY(3, AF_NETLINK, "AF_NETLINK", sizeof(struct sockaddr_nl), 12, 12) +KAPI_ADDR_FORMAT ("struct sockaddr_nl { sa_family_t nl_family; __u16 nl_pad; " + "__u32 nl_pid; __u32 nl_groups; }") + KAPI_ADDR_FEATURES(false, true, false) /* Multicast via nl_groups */ +KAPI_ADDR_SPECIAL ("nl_pid: 0 = kernel; getpid() = this process; " + "nl_groups: bitmask of multicast groups") + KAPI_ADDR_PORTS(0, 0) /* Uses nl_pid instead */ + KAPI_ADDR_FAMILY_END + + KAPI_ADDR_FAMILY(4, AF_PACKET, "AF_PACKET", sizeof(struct sockaddr_ll), 20, 20) +KAPI_ADDR_FORMAT ("struct sockaddr_ll { sa_family_t sll_family; __be16 sll_protocol; " +"int sll_ifindex; __u16 sll_hatype; __u8 sll_pkttype; " + "__u8 sll_halen; __u8 sll_addr[8]; }") + KAPI_ADDR_FEATURES(true, true, true) /* Via sll_pkttype */ +KAPI_ADDR_SPECIAL ("sll_ifindex: 0 = any interface; " +"sll_protocol: ETH_P_ALL = all protocols; " + "sll_pkttype: PACKET_HOST/BROADCAST/MULTICAST/OTHERHOST") + KAPI_ADDR_PORTS(0, 0) /* Layer 2, no ports */ + KAPI_ADDR_FAMILY_END + + KAPI_ADDR_FAMILY(5, AF_BLUETOOTH, "AF_BLUETOOTH", sizeof(struct sockaddr), 14, 258) +KAPI_ADDR_FORMAT ("Varies by protocol: sockaddr_l2 (L2CAP), sockaddr_rc (RFCOMM), " + "sockaddr_hci (HCI), sockaddr_sco (SCO)") + KAPI_ADDR_FEATURES(false, false, false) +KAPI_ADDR_SPECIAL ("BDADDR_ANY (00:00:00:00:00:00) - any device; " + "BDADDR_LOCAL (00:00:00:ff:ff:ff) - local adapter") + KAPI_ADDR_PORTS(1, 30) /* PSM for L2CAP, channel for RFCOMM */ + KAPI_ADDR_FAMILY_END + +KAPI_ADDR_FAMILY_COUNT (6 ) + + /* Security specification - use existing capability mechanism */ + KAPI_CAPABILITY(0, CAP_NET_RAW, "CAP_NET_RAW", KAPI_CAP_GRANT_PERMISSION) + KAPI_CAP_CONDITION("family == AF_PACKET || type == SOCK_RAW") + KAPI_CAP_ALLOWS("Raw socket creation and packet injection") + KAPI_CAP_WITHOUT("Permission denied (EPERM)") + KAPI_CAPABILITY_END + +KAPI_CAPABILITY_COUNT (1 ) + +/* Operation characteristics */ + .is_connection_oriented = false, + .is_message_oriented = false, + .supports_oob_data = false, + .supports_peek = false, + .supports_select_poll = false, + .is_reentrant = true, + + /* Semantic descriptions */ + KAPI_NET_DATA_TRANSFER("Not applicable - socket() only creates the endpoint") + +/* Additional constraints and validation rules */ +KAPI_CONSTRAINT (0 ,"Protocol/Type Compatibility" , +"Not all (family, type, protocol) combinations are valid. " +"Common valid combinations: " +"(AF_INET, SOCK_STREAM, IPPROTO_TCP); " +"(AF_INET, SOCK_DGRAM, IPPROTO_UDP); " +"(AF_INET, SOCK_RAW, IPPROTO_ICMP); " +"(AF_UNIX, SOCK_STREAM, 0); " +"(AF_UNIX, SOCK_DGRAM, 0); " +"(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); " + "(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE)") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(1, "Module Loading", + "If protocol family module not loaded, socket() may block during " + "request_module() execution. This is interruptible and may take " + "significant time. Modules loaded: net-pf-N where N is family number.") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(2, "Capability Requirements", + "CAP_NET_RAW required for: " + "- AF_INET/AF_INET6 with SOCK_RAW " + "- AF_PACKET with any socket type " + "- Some AF_NETLINK operations require CAP_NET_ADMIN " + "- AF_BLUETOOTH may require CAP_NET_ADMIN for some operations") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(3, "Network Namespace", + "Socket is created in current->nsproxy->net_ns network namespace. " + "Socket is bound to this namespace for its lifetime. " + "Different namespaces have independent network stacks.") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT(4, "Memory Limits", + "Socket creation respects: " + "- RLIMIT_NOFILE for file descriptor limits " + "- Memory cgroup limits for socket memory " + "- System-wide socket memory limits (net.core.somaxconn, etc.) " + "- Per-protocol memory limits") + KAPI_CONSTRAINT_END + + KAPI_CONSTRAINT_COUNT(5) + +KAPI_END_SPEC; + SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol) {return __sys_socket (family, type, protocol);
Signature · 1 line
2.39.5
RFC v2 22/22 tools/kapi: Add kernel API specification extraction tool
In reply to Sasha LevinThe 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 | 415 +++++ tools/kapi/src/extractor/mod.rs | 411 +++++ tools/kapi/src/extractor/source_parser.rs | 1625 +++++++++++++++++ .../src/extractor/vmlinux/binary_utils.rs | 283 +++ tools/kapi/src/extractor/vmlinux/mod.rs | 989 ++++++++++ tools/kapi/src/formatter/json.rs | 420 +++++ tools/kapi/src/formatter/mod.rs | 130 ++ tools/kapi/src/formatter/plain.rs | 465 +++++ tools/kapi/src/formatter/rst.rs | 468 +++++ tools/kapi/src/formatter/shall.rs | 605 ++++++ tools/kapi/src/main.rs | 130 ++ 14 files changed, 6159 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/formatter/shall.rs create mode 100644 tools/kapi/src/main.rs
Documentation/admin-guide/kernel-api-spec.rst +195 -3
@@ -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
@@ -0,0 +1,4 @@ +# Rust build artifacts +/target/ +**/*.rs.bk +
tools/kapi/Cargo.toml new file +19 -0
@@ -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 +415 -0
416 lines not on this page · raw message
tools/kapi/src/extractor/mod.rs new file +411 -0
412 lines not on this page · raw message
tools/kapi/src/extractor/source_parser.rs new file +1625 -0
1,626 lines not on this page · raw message
tools/kapi/src/extractor/vmlinux/binary_utils.rs new file +283 -0
284 lines not on this page · raw message
tools/kapi/src/extractor/vmlinux/mod.rs new file +989 -0
11 lines not on this page · raw message
tools/kapi/src/formatter/json.rs new file +420 -0
420 lines not on this page · raw message
tools/kapi/src/formatter/mod.rs new file +130 -0
130 lines not on this page · raw message
tools/kapi/src/formatter/plain.rs new file +465 -0
465 lines not on this page · raw message
tools/kapi/src/formatter/rst.rs new file +468 -0
468 lines not on this page · raw message
tools/kapi/src/formatter/shall.rs new file +605 -0
605 lines not on this page · raw message
tools/kapi/src/main.rs new file +130 -0
130 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.
Hi Sasha,
Quoted 5 lines · Sasha Levin
Hey folks,
This is a second attempt at a "Kernel API Specification" framework, addressing the feedback from the initial RFC and expanding the scope to include sysfs attribute specifications.
In light of your talk at OSS last week [1] (for non-subscribers [2]), I am wondering if any of this code has been written by coding LLMs. It seems like the kind of unpleasant boilerplate that they are said to be good at generating, but also seems like an enormous blob of "code" to review. What is the status of this specification in that regard?
thanks!
jake
[1] https://lwn.net/Articles/1026558/
[2] https://lwn.net/SubscriberLink/1026558/914fa4ec5964b0c5/
Signature · 1 line
Jake Edge - LWN - [email protected] - https://lwn.net
Quoted 11 lines · Jake Edge
Hi Sasha,
Quoted 5 lines · Sasha Levin
Hey folks,
This is a second attempt at a "Kernel API Specification" framework, addressing the feedback from the initial RFC and expanding the scope to include sysfs attribute specifications.
Quoted 5 lines
In light of your talk at OSS last week [1] (for non-subscribers [2]), I am wondering if any of this code has been written by coding LLMs. It seems like the kind of unpleasant boilerplate that they are said to be good at generating, but also seems like an enormous blob of "code" to review. What is the status of this specification in that regard?
Hey Jake!
The macro definitions were done mostly manually: it ended up being more of a copy/paste/replace exercise to get all the different macros in place (which, yes, ended up being a huge blob).
For the syscall/ioctl/sysfs APIs I used to demonstrate the infrastructure, I started with defining the basic spec skeleton manually based on our existing docs and code review, but then had LLMs extend it based on it's review of the code.
If we do proceed with something along the lines of this spec, I can see LLMs being useful at reviewing incoming code changes and alerting us of required updates/changes to the spec (or, alerting us that we're breaking the spec). Think of something like AUTOSEL but for classification of commits that affect the userspace API.
The tools/kapi/ code is mostly mostly LLM generated.
Signature · 2 lines
Thanks, Sasha