Kernel API Specification Framework
Subsystems (9)
cover Kernel API Specification Framework
This proposal introduces machinery for documenting kernel APIs, addressing the long-standing challenge of maintaining stable interfaces between the kernel and user-space programs. Despite the kernel's commitment to never breaking user space, the lack of machine-readable API specifications has led to breakages and across system calls and IOCTLs.
Specifications can document parameter types, valid ranges, constraints, and alignment requirements. They capture return value semantics including success conditions and error codes with their meaning. Execution context requirements, capabilities, locking constraints, signal handling behavior, and side effects can all be formally specified.
These specifications live alongside the code they document and are both human-readable and machine-parseable. They can be validated at runtime when CONFIG_KAPI_RUNTIME_CHECKS is enabled, exported via debugfs for userspace tools, and extracted from either vmlinux or source code.
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
The implementation includes a core framework with ELF section storage, kerneldoc integration for inline specification, a debugfs interface for runtime querying, and a Rust-based extraction tool (tools/kapi) supporting JSON, RST, and plain text output formats. Example specifications are provided for the four fundamental file syscalls (sys_open, sys_close, sys_read, sys_write). The series also includes a KUnit test suite with 38 tests and a runtime verification selftest with 29+ TAP tests.
The series with runtime testing enabled (CONFIG_KAPI_RUNTIME_CHECKS=y) currently survives LTP tests in a KVM VM.
Changes since RFC v5:
- Streamlined example specs: focus on open/close/read/write to start with.
- Added KUnit test suite.
- Added runtime verification selftest.
- Fixed kernel test robot warnings from v5: fixed "document isn't included in any toctree" (kernel-api-spec.rst now properly added to Documentation/dev-tools/index.rst), fixed sparse "non size-preserving integer to pointer cast" warnings in kernel_api_spec.c.
- Rebased on v7.0-rc1.
References:
RFC v5: https://lore.kernel.org/lkml/[email protected]/
RFC v4: https://lore.kernel.org/lkml/[email protected]/
RFC v3: https://lore.kernel.org/lkml/[email protected]/
RFC v2: https://lore.kernel.org/lkml/[email protected]/
RFC v1: https://lore.kernel.org/lkml/[email protected]/
Sasha Levin (9):
kernel/api: introduce kernel API specification framework kernel/api: enable kerneldoc-based API specifications kernel/api: add debugfs interface for kernel API specifications tools/kapi: Add kernel API specification extraction tool kernel/api: add API specification for sys_open kernel/api: add API specification for sys_close kernel/api: add API specification for sys_read kernel/api: add API specification for sys_write kernel/api: add runtime verification selftest
.gitignore | 1 + Documentation/dev-tools/index.rst | 1 + Documentation/dev-tools/kernel-api-spec.rst | 629 +++++++ MAINTAINERS | 12 + arch/x86/include/asm/syscall_wrapper.h | 40 + fs/open.c | 576 +++++- fs/read_write.c | 687 +++++++ include/asm-generic/vmlinux.lds.h | 28 + include/linux/kernel_api_spec.h | 1580 +++++++++++++++++ include/linux/syscall_api_spec.h | 192 ++ include/linux/syscalls.h | 39 + init/Kconfig | 2 + kernel/Makefile | 3 + kernel/api/.gitignore | 2 + kernel/api/Kconfig | 70 + kernel/api/Makefile | 14 + kernel/api/kapi_debugfs.c | 503 ++++++ kernel/api/kapi_kunit.c | 536 ++++++ kernel/api/kernel_api_spec.c | 1277 +++++++++++++ scripts/Makefile.build | 31 + scripts/Makefile.clean | 3 + tools/docs/kernel-doc | 5 + tools/kapi/.gitignore | 4 + tools/kapi/Cargo.toml | 19 + tools/kapi/src/extractor/debugfs.rs | 581 ++++++ tools/kapi/src/extractor/kerneldoc_parser.rs | 1554 ++++++++++++++++ tools/kapi/src/extractor/mod.rs | 463 +++++ tools/kapi/src/extractor/source_parser.rs | 405 +++++ .../src/extractor/vmlinux/binary_utils.rs | 505 ++++++ .../src/extractor/vmlinux/magic_finder.rs | 112 ++ tools/kapi/src/extractor/vmlinux/mod.rs | 842 +++++++++ tools/kapi/src/formatter/json.rs | 727 ++++++++ tools/kapi/src/formatter/mod.rs | 140 ++ tools/kapi/src/formatter/plain.rs | 708 ++++++++ tools/kapi/src/formatter/rst.rs | 852 +++++++++ tools/kapi/src/main.rs | 119 ++ tools/lib/python/kdoc/kdoc_apispec.py | 887 +++++++++ tools/lib/python/kdoc/kdoc_output.py | 9 +- tools/lib/python/kdoc/kdoc_parser.py | 86 +- tools/testing/selftests/kapi/Makefile | 7 + tools/testing/selftests/kapi/kapi_test_util.h | 31 + tools/testing/selftests/kapi/test_kapi.c | 1021 +++++++++++ 42 files changed, 15294 insertions(+), 9 deletions(-) create mode 100644 Documentation/dev-tools/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/.gitignore create mode 100644 kernel/api/Kconfig create mode 100644 kernel/api/Makefile create mode 100644 kernel/api/kapi_debugfs.c create mode 100644 kernel/api/kapi_kunit.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/kerneldoc_parser.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/magic_finder.rs create mode 100644 tools/kapi/src/extractor/vmlinux/mod.rs create mode 100644 tools/kapi/src/formatter/json.rs create mode 100644 tools/kapi/src/formatter/mod.rs create mode 100644 tools/kapi/src/formatter/plain.rs create mode 100644 tools/kapi/src/formatter/rst.rs create mode 100644 tools/kapi/src/main.rs create mode 100644 tools/lib/python/kdoc/kdoc_apispec.py create mode 100644 tools/testing/selftests/kapi/Makefile create mode 100644 tools/testing/selftests/kapi/kapi_test_util.h create mode 100644 tools/testing/selftests/kapi/test_kapi.c
Signature · 1 line
2.51.0
PATCH 1/9 kernel/api: introduce kernel API specification framework
Add a 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.
--- .gitignore | 1 + Documentation/dev-tools/index.rst | 1 + Documentation/dev-tools/kernel-api-spec.rst | 482 ++++++ MAINTAINERS | 11 + arch/x86/include/asm/syscall_wrapper.h | 40 + include/asm-generic/vmlinux.lds.h | 28 + include/linux/kernel_api_spec.h | 1580 +++++++++++++++++++ include/linux/syscall_api_spec.h | 192 +++ include/linux/syscalls.h | 39 + init/Kconfig | 2 + kernel/Makefile | 3 + kernel/api/.gitignore | 2 + kernel/api/Kconfig | 70 + kernel/api/Makefile | 14 + kernel/api/kapi_kunit.c | 536 +++++++ kernel/api/kernel_api_spec.c | 1277 +++++++++++++++ scripts/generate_api_specs.sh | 18 + 17 files changed, 4296 insertions(+) create mode 100644 Documentation/dev-tools/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/.gitignore create mode 100644 kernel/api/Kconfig create mode 100644 kernel/api/Makefile create mode 100644 kernel/api/kapi_kunit.c create mode 100644 kernel/api/kernel_api_spec.c create mode 100755 scripts/generate_api_specs.sh
.gitignore +1 -0
@@ -12,6 +12,7 @@ # .* *.a +*.apispec.h *.asn1.[ch] *.bin *.bz2
Documentation/dev-tools/index.rst +1 -0
@@ -36,6 +36,7 @@ Documentation/process/debugging/index.rst kunit/index ktap checkuapi + kernel-api-spec gpio-sloppy-logic-analyzer autofdo propeller
Documentation/dev-tools/kernel-api-spec.rst new file +482 -0
482 lines not on this page · raw message
MAINTAINERS +11 -0
@@ -13810,6 +13810,17 @@ 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/dev-tools/kernel-api-spec.rst +F: include/linux/kernel_api_spec.h +F: include/linux/syscall_api_spec.h +F: kernel/api/ +F: tools/kapi/ +F: tools/lib/python/kdoc/kdoc_apispec.py + KERNEL AUTOMOUNTER M: Ian Kent <[email protected]> L: [email protected]
arch/x86/include/asm/syscall_wrapper.h +40 -0
@@ -7,6 +7,14 @@#define _ASM_X86_SYSCALL_WRAPPER_H#include <asm/ptrace.h> +#ifdef CONFIG_KAPI_RUNTIME_CHECKS +struct kernel_api_spec ; +extern const struct kernel_api_spec *kapi_get_spec (const char *name); +extern int kapi_validate_syscall_params (const struct kernel_api_spec *spec, +const s64 *params,int param_count); +extern int kapi_validate_syscall_return (const struct kernel_api_spec *spec, +s64 retval); +#endif extern long __x64_sys_ni_syscall (const struct pt_regs *regs);extern long __ia32_sys_ni_syscall (const struct pt_regs *regs);
@@ -220,6 +228,37 @@ extern long __ia32_sys_ni_syscall(const struct pt_regs *regs);#endif /* CONFIG_COMPAT */ +#ifdef CONFIG_KAPI_RUNTIME_CHECKS +#define __SYSCALL_DEFINEx (x, name, ...) \ + static long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__)); \ + 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__)); \ + __X64_SYS_STUBx(x, name, __VA_ARGS__) \ + __IA32_SYS_STUBx(x, name, __VA_ARGS__) \ + static 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; \ + } \ + 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, ...) \ static long __se_sys##name(__MAP(x,__SC_LONG,__VA_ARGS__)); \ static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__));\
@@ -233,6 +272,7 @@ extern long __ia32_sys_ni_syscall(const struct pt_regs *regs);return ret; \ } \ static inline long __do_sys##name(__MAP(x,__SC_DECL,__VA_ARGS__)) +#endif /* CONFIG_KAPI_RUNTIME_CHECKS */ /* * As the generic SYSCALL_DEFINE0() macro does not decode any parameters for
include/asm-generic/vmlinux.lds.h +28 -0
@@ -296,6 +296,33 @@#define TRACE_SYSCALLS ()#endif +#ifdef CONFIG_KAPI_SPEC +/* +* KAPI_SPECS - Include kernel API specifications in current section +* +* The .kapi_specs input section has 32-byte alignment requirement from +* the compiler, so we must align to 32 bytes before setting the start +* symbol to avoid padding between the symbol and actual data. +*/ +#define KAPI_SPECS () \ + . = ALIGN(32); \ + __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(32); \ + __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)
@@ -485,6 +512,7 @@ . = ALIGN(8); \BOUNDED_SECTION_BY (__tracepoints_ptrs, ___tracepoints_ptrs) \ *(__tracepoints_strings )/* Tracepoints: strings */ \ +KAPI_SPECS () \ } \ \ .rodata1 : AT(ADDR(.rodata1) - LOAD_OFFSET) { \
include/linux/kernel_api_spec.h new file +1580 -0
1,580 lines not on this page · raw message
include/linux/syscall_api_spec.h new file +192 -0
193 lines not on this page · raw message
include/linux/syscalls.h +39 -0
@@ -88,6 +88,7 @@ struct file_attr;#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>
@@ -133,6 +134,7 @@ struct file_attr;#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
@@ -243,6 +245,42 @@ 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", \
@@ -261,6 +299,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
@@ -2223,6 +2223,8 @@ source "kernel/Kconfig.kexec" source "kernel/liveupdate/Kconfig" +source "kernel/api/Kconfig" + endmenu # General setup source "arch/Kconfig"
kernel/Makefile +3 -0
@@ -59,6 +59,9 @@ obj-y += dma/ obj-y += entry/ obj-y += unwind/ obj-$(CONFIG_MODULES) += module/ +obj-$(CONFIG_KAPI_SPEC) += api/ +# Ensure api/ is always cleaned even when CONFIG_KAPI_SPEC is not set +obj- += api/ obj-$(CONFIG_KCMP) += kcmp.o obj-$(CONFIG_FREEZER) += freezer.o
kernel/api/.gitignore new file +2 -0
@@ -0,0 +1,2 @@ +# SPDX-License-Identifier: GPL-2.0-only +/generated_api_specs.c
kernel/api/Kconfig new file +70 -0
70 lines not on this page · raw message
kernel/api/Makefile new file +14 -0
@@ -0,0 +1,14 @@ +# 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 + +# Debugfs interface for kernel API specs +obj-$(CONFIG_KAPI_SPEC_DEBUGFS) += kapi_debugfs.o + +# KUnit tests +obj-$(CONFIG_KAPI_KUNIT_TEST) += kapi_kunit.o +
kernel/api/kapi_kunit.c new file +536 -0
450 lines not on this page · raw message
kernel/api/kernel_api_spec.c new file +1277 -0
1,277 lines not on this page · raw message
scripts/generate_api_specs.sh new file +18 -0
Lines of this file are not shown. View the raw message.
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.51.0
Part of the diff is not shown here. View the raw message.
PATCH 2/9 kernel/api: enable kerneldoc-based API specifications
In reply to Sasha LevinThis patch adds support for extracting API specifications from kernel-doc comments and generating C macro invocations for the kernel API specification framework.
Changes include:
- New kdoc_apispec.py module for generating API spec macros
- Updates to kernel-doc.py to support -apispec output format
- Build system integration in Makefile.build
- Generator script for collecting all API specifications
- Support for API-specific sections in kernel-doc comments
--- scripts/Makefile.build | 31 + scripts/Makefile.clean | 3 + scripts/generate_api_specs.sh | 18 - tools/docs/kernel-doc | 5 + tools/lib/python/kdoc/kdoc_apispec.py | 887 ++++++++++++++++++++++++++ tools/lib/python/kdoc/kdoc_output.py | 9 +- tools/lib/python/kdoc/kdoc_parser.py | 86 ++- 7 files changed, 1016 insertions(+), 23 deletions(-) delete mode 100755 scripts/generate_api_specs.sh create mode 100644 tools/lib/python/kdoc/kdoc_apispec.py
scripts/Makefile.build +31 -0
@@ -174,6 +174,37 @@ ifneq ($(KBUILD_EXTRA_WARN),) endif endif +# Generate API spec headers from kernel-doc comments +ifeq ($(CONFIG_KAPI_SPEC),y) +# Function to check if a file has API specifications +has-apispec = $(shell grep -qE '^\s*\*\s*context-flags:' $(src)/$(1) 2>/dev/null && echo $(1)) + +# Get base names without directory prefix +c-objs-base := $(notdir $(real-obj-y) $(real-obj-m)) +# Filter to only .o files with corresponding .c source files +c-files := $(foreach o,$(c-objs-base),$(if $(wildcard $(src)/$(o:.o=.c)),$(o:.o=.c))) +# Also check for any additional .c files that contain API specs but are included +extra-c-files := $(shell find $(src) -maxdepth 1 -name "*.c" -exec grep -l '^\s*\*\s*\(long-desc\|context-flags\|state-trans\):' {} \; 2>/dev/null | xargs -r basename -a) +# Combine both lists and remove duplicates +all-c-files := $(sort $(c-files) $(extra-c-files)) +# Only include files that actually have API specifications +apispec-files := $(foreach f,$(all-c-files),$(call has-apispec,$(f))) +# Generate apispec targets with proper directory prefix +apispec-y := $(addprefix $(obj)/,$(apispec-files:.c=.apispec.h)) +always-y += $(apispec-y) +targets += $(apispec-y) + +quiet_cmd_apispec = APISPEC $@ + cmd_apispec = PYTHONDONTWRITEBYTECODE=1 $(KERNELDOC) -apispec \ + $(KDOCFLAGS) $< > $@ || rm -f $@ + +$(obj)/%.apispec.h: $(src)/%.c $(KERNELDOC) FORCE + $(call if_changed,apispec) + +# Source files that include their own apispec.h need to depend on it +$(foreach f,$(apispec-files),$(eval $(obj)/$(f:.c=.o): $(obj)/$(f:.c=.apispec.h))) +endif + # Compile C sources (.c) # ---------------------------------------------------------------------------
scripts/Makefile.clean +3 -0
@@ -35,6 +35,9 @@ __clean-files := $(filter-out $(no-clean-files), $(__clean-files)) __clean-files := $(wildcard $(addprefix $(obj)/, $(__clean-files))) +# Also clean generated apispec headers (computed dynamically in Makefile.build) +__clean-files += $(wildcard $(obj)/*.apispec.h) + # ========================================================================== # To make this rule robust against "Argument list too long" error,
scripts/generate_api_specs.sh deleted +0 -18
@@ -1,18 +0,0 @@ -#!/bin/bash -# SPDX-License-Identifier: GPL-2.0 -# -# Stub script for generating API specifications collector -# This is a placeholder until the full implementation is available -# - -cat << 'EOF' -// SPDX-License-Identifier: GPL-2.0 -/* - * Auto-generated API specifications collector (stub) - * Generated by scripts/generate_api_specs.sh - */ - -#include <linux/kernel_api_spec.h> - -/* No API specifications collected yet */ -EOF
tools/docs/kernel-doc +5 -0
@@ -253,6 +253,8 @@ def main(): help="Output reStructuredText format (default).") out_fmt.add_argument("-N", "-none", "--none", action="store_true", help="Do not output documentation, only warnings.") + out_fmt.add_argument("-apispec", "--apispec", action="store_true", + help="Output C macro invocations for kernel API specifications.") # # Output selection mutually-exclusive group
@@ -323,11 +325,14 @@ def main(): # from kdoc.kdoc_files import KernelFiles # pylint: disable=C0415 from kdoc.kdoc_output import RestFormat, ManFormat # pylint: disable=C0415 + from kdoc.kdoc_apispec import ApiSpecFormat # pylint: disable=C0415 if args.man: out_style = ManFormat(modulename=args.modulename) elif args.none: out_style = None + elif args.apispec: + out_style = ApiSpecFormat() else: out_style = RestFormat()
tools/lib/python/kdoc/kdoc_apispec.py new file +887 -0
887 lines not on this page · raw message
tools/lib/python/kdoc/kdoc_output.py +7 -2
@@ -129,8 +129,13 @@ class OutputFormat: Output warnings for identifiers that will be displayed. """ - for log_msg in args.warnings: - self.config.warning(log_msg) + warnings = getattr(args, 'warnings', []) + + for log_msg in warnings: + # Skip numeric warnings (line numbers) which are false positives + # from parameter-specific sections like "param-constraint: name, value" + if not isinstance(log_msg, int): + self.config.warning(log_msg) def check_doc(self, name, args): """Check if DOC should be output."""
tools/lib/python/kdoc/kdoc_parser.py +83 -3
106 lines not on this page · raw message
Signature · 1 line
2.51.0
PATCH 3/9 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.
--- Documentation/dev-tools/kernel-api-spec.rst | 88 ++-- kernel/api/kapi_debugfs.c | 503 ++++++++++++++++++++ 2 files changed, 534 insertions(+), 57 deletions(-) create mode 100644 kernel/api/kapi_debugfs.c
Documentation/dev-tools/kernel-api-spec.rst +31 -57
@@ -56,16 +56,10 @@ The framework consists of several key components: 2. **DebugFS Interface** (``kernel/api/kapi_debugfs.c``) - Runtime introspection via ``/sys/kernel/debug/kapi/`` - - JSON and XML export formats - - Per-API detailed information + - Per-API detailed specification output + - List of all registered API specifications -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``) +3. **Specification Macros** (``include/linux/kernel_api_spec.h``) - Declarative macros for API documentation - Type-safe parameter specifications
@@ -186,8 +180,8 @@ Runtime validation is controlled by kernel configuration: 2. Enable ``CONFIG_KAPI_RUNTIME_CHECKS`` for runtime validation 3. Optionally enable ``CONFIG_KAPI_SPEC_DEBUGFS`` for debugfs interface -Validation Modes ----------------- +Validation Behavior +------------------- When ``CONFIG_KAPI_RUNTIME_CHECKS`` is enabled, all registered API specifications are validated automatically at call time. The framework checks parameter constraints,
@@ -225,55 +219,39 @@ 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 + ├── list # Overview of all registered API specs + └── specs/ # Per-API specification files + ├── sys_open # Human-readable spec for sys_open + ├── sys_close # Human-readable spec for sys_close + ├── sys_read # Human-readable spec for sys_read + └── sys_write # Human-readable spec for sys_write Usage Examples -------------- -Query specific API:: - - $ cat /sys/kernel/debug/kapi/apis/kmalloc/specification - API: kmalloc - Version: 3.0 - Description: Allocate kernel memory +List all available API specifications:: - Parameters: - [0] size (size_t, in): Number of bytes to allocate - Range: 0 - 4194304 - [1] flags (flags, in): Allocation flags (GFP_*) - Mask: 0x1ffffff + $ cat /sys/kernel/debug/kapi/list + Available Kernel API Specifications + =================================== - Returns: pointer - Pointer to allocated memory or NULL + sys_open - Open or create a file + sys_close - Close a file descriptor + sys_read - Read data from a file descriptor + sys_write - Write data to a file descriptor - Errors: - ENOMEM: Out of memory + Total: 4 specifications - 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 +Query specific API:: -Enable validation for specific API:: + $ cat /sys/kernel/debug/kapi/specs/sys_open + Kernel API Specification + ======================== - $ echo 1 > /sys/kernel/debug/kapi/apis/kmalloc/validate + Name: sys_open + Version: 1 + Description: Open or create a file + ... Performance Considerations ==========================
@@ -304,11 +282,8 @@ 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. +2. **Selective enablement**: Enable ``CONFIG_KAPI_RUNTIME_CHECKS`` + only in development/testing kernels, not in production. Documentation Generation ------------------------
@@ -414,10 +389,9 @@ Common Issues Debug Options ------------- -Enable verbose debugging:: +Enable verbose kernel logging to see KAPI validation messages:: echo 8 > /proc/sys/kernel/printk - echo 1 > /sys/kernel/debug/kapi/debug/verbose Future Directions =================
kernel/api/kapi_debugfs.c new file +503 -0
503 lines not on this page · raw message
Signature · 1 line
2.51.0
PATCH 4/9 tools/kapi: Add kernel API specification extraction tool
In reply to Sasha LevinThe kapi tool extracts and displays kernel API specifications.
--- Documentation/dev-tools/kernel-api-spec.rst | 195 ++- tools/kapi/.gitignore | 4 + tools/kapi/Cargo.toml | 19 + tools/kapi/src/extractor/debugfs.rs | 581 ++++++ tools/kapi/src/extractor/kerneldoc_parser.rs | 1554 +++++++++++++++++ tools/kapi/src/extractor/mod.rs | 463 +++++ tools/kapi/src/extractor/source_parser.rs | 405 +++++ .../src/extractor/vmlinux/binary_utils.rs | 505 ++++++ .../src/extractor/vmlinux/magic_finder.rs | 112 ++ tools/kapi/src/extractor/vmlinux/mod.rs | 842 +++++++++ tools/kapi/src/formatter/json.rs | 727 ++++++++ tools/kapi/src/formatter/mod.rs | 140 ++ tools/kapi/src/formatter/plain.rs | 708 ++++++++ tools/kapi/src/formatter/rst.rs | 852 +++++++++ tools/kapi/src/main.rs | 119 ++ 15 files changed, 7215 insertions(+), 11 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/kerneldoc_parser.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/magic_finder.rs create mode 100644 tools/kapi/src/extractor/vmlinux/mod.rs create mode 100644 tools/kapi/src/formatter/json.rs create mode 100644 tools/kapi/src/formatter/mod.rs create mode 100644 tools/kapi/src/formatter/plain.rs create mode 100644 tools/kapi/src/formatter/rst.rs create mode 100644 tools/kapi/src/main.rs
Documentation/dev-tools/kernel-api-spec.rst +184 -11
@@ -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.
@@ -65,6 +67,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 ----------
@@ -289,8 +298,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`` or kerneldoc annotations) +- IOCTLs (kerneldoc annotations with ioctl-specific tags) +- Kernel functions (kerneldoc annotations with KAPI tags) IDE Integration ---------------
@@ -302,15 +480,10 @@ Modern IDEs can use the JSON export for: - Context validation - Error code documentation -Testing Framework ------------------ - -The framework includes test helpers:: +Example IDE integration:: - #ifdef CONFIG_KAPI_TESTING - /* Verify API behaves according to specification */ - kapi_test_api("kmalloc", test_cases); - #endif + # Generate IDE completion data + $ kapi --format json > .vscode/kernel-apis.json 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 = "2021" +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 +581 -0
581 lines not on this page · raw message
tools/kapi/src/extractor/kerneldoc_parser.rs new file +1554 -0
1,554 lines not on this page · raw message
tools/kapi/src/extractor/mod.rs new file +463 -0
463 lines not on this page · raw message
tools/kapi/src/extractor/source_parser.rs new file +405 -0
159 lines not on this page · raw message
tools/kapi/src/extractor/vmlinux/binary_utils.rs new file +505 -0
505 lines not on this page · raw message
tools/kapi/src/extractor/vmlinux/magic_finder.rs new file +112 -0
112 lines not on this page · raw message
tools/kapi/src/extractor/vmlinux/mod.rs new file +842 -0
842 lines not on this page · raw message
tools/kapi/src/formatter/json.rs new file +727 -0
727 lines not on this page · raw message
tools/kapi/src/formatter/mod.rs new file +140 -0
140 lines not on this page · raw message
tools/kapi/src/formatter/plain.rs new file +708 -0
708 lines not on this page · raw message
tools/kapi/src/formatter/rst.rs new file +852 -0
852 lines not on this page · raw message
tools/kapi/src/main.rs new file +119 -0
119 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.51.0
Part of the diff is not shown here. View the raw message.
PATCH 5/9 kernel/api: add API specification for sys_open
In reply to Sasha Levin--- fs/open.c | 329 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 329 insertions(+)
fs/open.c +329 -0
@@ -1373,6 +1373,330 @@ int do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode) } +/** +* sys_open - Open or create a file +* @filename: Pathname of the file to open or create +* @flags: File access mode and behavior flags (O_RDONLY, O_WRONLY, O_RDWR, etc.) +* @mode: File permission bits for newly created files (only with O_CREAT/O_TMPFILE) +* +* long-desc: Opens the file specified by pathname. If O_CREAT or O_TMPFILE is +* specified in flags, the file is created if it does not exist; its mode is +* set according to the mode parameter modified by the process's umask. +* +* The flags argument must include one of the following access modes: O_RDONLY +* (read-only), O_WRONLY (write-only), or O_RDWR (read/write). These are the +* low-order two bits of flags. In addition, zero or more file creation and +* file status flags can be bitwise-ORed in flags. +* +* File creation flags: O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC, O_DIRECTORY, +* O_NOFOLLOW, O_CLOEXEC, O_TMPFILE. These flags affect open behavior. +* +* File status flags: O_APPEND, FASYNC, O_DIRECT, O_DSYNC, O_LARGEFILE, +* O_NOATIME, O_NONBLOCK (O_NDELAY), O_PATH, O_SYNC. These become part of the +* file's open file description and can be retrieved/modified with fcntl(). +* +* The return value is a file descriptor, a small nonnegative integer used in +* subsequent system calls (read, write, lseek, fcntl, etc.) to refer to the +* open file. The file descriptor returned by a successful open is the lowest- +* numbered file descriptor not currently open for the process. +* +* On 64-bit systems, O_LARGEFILE is automatically added to the flags. On 32-bit +* systems, files larger than 2GB require O_LARGEFILE to be explicitly set. +* +* This syscall is a legacy interface. Modern code should prefer openat() for +* relative path operations and openat2() for additional control via resolve +* flags. The open() call is equivalent to openat(AT_FDCWD, pathname, flags). +* +* context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE +* +* param: filename +* type: KAPI_TYPE_PATH +* flags: KAPI_PARAM_IN | KAPI_PARAM_USER +* constraint-type: KAPI_CONSTRAINT_USER_PATH +* cdesc: Must be a valid null-terminated path string in user memory. +* Maximum path length is PATH_MAX (4096 bytes) including null terminator. +* For relative paths, resolution starts from current working directory. +* The path is followed (symlinks resolved) unless O_NOFOLLOW is specified. +* +* param: flags +* type: KAPI_TYPE_INT +* flags: KAPI_PARAM_IN +* constraint-type: KAPI_CONSTRAINT_MASK +* valid-mask: O_RDONLY | O_WRONLY | O_RDWR | O_CREAT | O_EXCL | O_NOCTTY | +* O_TRUNC | O_APPEND | O_NONBLOCK | O_DSYNC | O_SYNC | FASYNC | +* O_DIRECT | O_LARGEFILE | O_DIRECTORY | O_NOFOLLOW | O_NOATIME | +* O_CLOEXEC | O_PATH | O_TMPFILE +* cdesc: Must include exactly one of O_RDONLY (0), O_WRONLY (1), or +* O_RDWR (2) as the access mode. Additional flags may be ORed. Invalid flag +* combinations (e.g., O_PATH with incompatible flags, O_TMPFILE without +* O_DIRECTORY, O_TMPFILE with read-only mode) return EINVAL. Since Linux +* 6.7, O_CREAT is silently ignored when combined with O_DIRECTORY. Unknown +* flags are silently ignored for backward compatibility (unlike openat2 +* which rejects them). +* +* param: mode +* type: KAPI_TYPE_UINT +* flags: KAPI_PARAM_IN +* constraint-type: KAPI_CONSTRAINT_MASK +* valid-mask: S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO +* cdesc: Only meaningful when O_CREAT or O_TMPFILE is specified in +* flags. Specifies the file mode bits (permissions and setuid/setgid/sticky +* bits) for a newly created file. The effective mode is (mode & ~umask). +* When O_CREAT/O_TMPFILE is not set, mode is ignored. Mode values exceeding +* S_IALLUGO (07777) are masked off. +* +* return: +* type: KAPI_TYPE_INT +* check-type: KAPI_RETURN_FD +* success: >= 0 +* desc: On success, returns a new file descriptor (non-negative integer). +* The returned file descriptor is the lowest-numbered descriptor not +* currently open for the process. On error, returns a negative error code. +* +* error: EACCES, Permission denied +* desc: The requested access to the file is not allowed, or search permission +* is denied for one of the directories in the path prefix of pathname, or +* the file did not exist yet and write access to the parent directory is +* not allowed, or O_TRUNC is specified but write permission is denied, or +* the file is on a filesystem mounted with noexec and MAY_EXEC was implied. +* +* error: EAGAIN, Resource temporarily unavailable +* desc: The file is a FIFO or regular file, O_NONBLOCK is specified, and the +* operation would block. Also returned when RESOLVE_CACHED is used with +* openat2() and the lookup cannot be satisfied from the dentry cache. +* +* error: EBUSY, Device or resource busy +* desc: O_EXCL was specified in flags and pathname refers to a block device +* that is in use by the system (e.g., it is mounted). +* +* error: EDQUOT, Disk quota exceeded +* desc: O_CREAT is specified and the file does not exist, and the user's quota +* of disk blocks or inodes on the filesystem has been exhausted. +* +* error: EEXIST, File exists +* desc: O_CREAT and O_EXCL were specified in flags, but pathname already exists. +* This error is atomic with respect to file creation - it prevents race +* conditions (TOCTOU) when creating files. +* +* error: EFAULT, Bad address +* desc: pathname points outside the process's accessible address space. +* +* error: EINTR, Interrupted system call +* desc: The call was interrupted by a signal handler before completing file +* open. This can occur during lock acquisition or when breaking leases. +* +* error: EINVAL, Invalid argument +* desc: Returned for several conditions: (1) Invalid O_* flag combinations +* (O_TMPFILE without O_DIRECTORY, O_TMPFILE with read-only access, O_PATH +* with flags other than O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC). +* (2) mode contains bits outside S_IALLUGO when O_CREAT/O_TMPFILE +* is set (openat2 only). (3) O_DIRECT requested but filesystem doesn't +* support it. (4) The filesystem does not support O_SYNC or O_DSYNC. +* +* error: EISDIR, Is a directory +* desc: pathname refers to a directory and the access requested involved +* writing (O_WRONLY, O_RDWR, or O_TRUNC). Also returned when O_TMPFILE is +* used on a directory that doesn't support tmpfile operations. +* +* error: ELOOP, Too many symbolic links +* desc: Too many symbolic links were encountered in resolving pathname, or +* O_NOFOLLOW was specified but pathname refers to a symbolic link. +* +* error: EMFILE, Too many open files +* desc: The per-process limit on the number of open file descriptors has been +* reached. This limit is RLIMIT_NOFILE (default typically 1024, max set by +* /proc/sys/fs/nr_open). +* +* error: ENAMETOOLONG, File name too long +* desc: pathname was too long, exceeding PATH_MAX (4096) bytes, or a single +* path component exceeded NAME_MAX (usually 255) bytes. +* +* error: ENFILE, Too many open files in system +* desc: The system-wide limit on the total number of open files has been +* reached (/proc/sys/fs/file-max). Processes with CAP_SYS_ADMIN can exceed +* this limit. +* +* error: ENODEV, No such device +* desc: pathname refers to a special file that has no corresponding device, or +* the file's inode has no file operations assigned. +* +* error: ENOENT, No such file or directory +* desc: A directory component in pathname does not exist or is a dangling +* symbolic link, or O_CREAT is not set and the named file does not exist, +* or pathname is an empty string (unless AT_EMPTY_PATH is used with openat2). +* +* error: ENOMEM, Out of memory +* desc: The kernel could not allocate sufficient memory for the file structure, +* path lookup structures, or the filename buffer. +* +* error: ENOSPC, No space left on device +* desc: O_CREAT was specified and the file does not exist, and the directory +* or filesystem containing the file has no room for a new file entry. +* +* error: ENOTDIR, Not a directory +* desc: A component used as a directory in pathname is not actually a directory, +* or O_DIRECTORY was specified and pathname was not a directory. +* +* error: ENXIO, No such device or address +* desc: O_NONBLOCK | O_WRONLY is set and the named file is a FIFO and no +* process has the FIFO open for reading. Also returned when opening a device +* special file that does not exist. +* +* error: EOPNOTSUPP, Operation not supported +* desc: The filesystem containing pathname does not support O_TMPFILE. +* +* error: EOVERFLOW, Value too large for defined data type +* desc: pathname refers to a regular file that is too large to be opened. +* This occurs on 32-bit systems without O_LARGEFILE when the file size +* exceeds 2GB (2^31 - 1 bytes). +* +* error: EPERM, Operation not permitted +* desc: O_NOATIME flag was specified but the effective UID of the caller did +* not match the owner of the file and the caller is not privileged, or the +* file is append-only and O_TRUNC was specified or write mode without +* O_APPEND, or the file is immutable, or a seal prevents the operation. +* +* error: EROFS, Read-only file system +* desc: pathname refers to a file on a read-only filesystem and write access +* was requested. +* +* error: ETXTBSY, Text file busy +* desc: pathname refers to an executable image which is currently being +* executed, or to a swap file, and write access or truncation was requested. +* +* error: EWOULDBLOCK, Resource temporarily unavailable +* desc: O_NONBLOCK was specified and an incompatible lease is held on the file. +* +* lock: files->file_lock +* type: KAPI_LOCK_SPINLOCK +* acquired: true +* released: true +* desc: Acquired when allocating a file descriptor slot. Held briefly during +* fd allocation via alloc_fd() and released before the syscall returns. +* +* lock: inode->i_rwsem (parent directory) +* type: KAPI_LOCK_RWLOCK +* acquired: conditional +* released: true +* desc: Write lock acquired on parent directory inode when creating a new file +* (O_CREAT). Acquired via inode_lock_nested() in lookup path. May use +* killable variant which can return EINTR on fatal signal. +* +* lock: RCU read-side +* type: KAPI_LOCK_RCU +* acquired: true +* released: true +* desc: Path lookup uses RCU mode initially for performance. If RCU lookup +* fails (returns -ECHILD), falls back to reference-based lookup. +* +* signal: Any signal +* direction: KAPI_SIGNAL_RECEIVE +* action: KAPI_SIGNAL_ACTION_RETURN +* condition: When blocked on interruptible or killable operations +* desc: The syscall may be interrupted during path lookup, lock acquisition, +* or lease breaking. Fatal signals (SIGKILL, etc.) will interrupt killable +* operations. Non-fatal signals may interrupt interruptible operations. +* error: -EINTR +* timing: KAPI_SIGNAL_TIME_DURING +* restartable: yes +* +* side-effect: KAPI_EFFECT_RESOURCE_CREATE | KAPI_EFFECT_ALLOC_MEMORY +* target: file descriptor, file structure, dentry cache +* desc: Allocates a new file descriptor in the process's fd table. Allocates +* a struct file from the filp slab cache. May allocate dentries and inodes +* during path lookup. System-wide file count (nr_files) is incremented. +* reversible: yes +* +* side-effect: KAPI_EFFECT_FILESYSTEM +* target: filesystem, inode +* condition: When O_CREAT is specified and file doesn't exist +* desc: Creates a new file on the filesystem. Creates new inode, allocates +* data blocks as needed, and creates directory entry. Updates parent +* directory mtime and ctime. +* reversible: no +* +* side-effect: KAPI_EFFECT_FILESYSTEM +* target: file content +* condition: When O_TRUNC is specified for existing file +* desc: Truncates the file to zero length, releasing data blocks. Updates +* file mtime and ctime. May trigger notifications to lease holders. +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: inode timestamps +* condition: Unless O_NOATIME is specified +* desc: Opens for reading may update inode access time (atime) unless mounted +* with noatime/relatime or O_NOATIME is specified. Opens for writing that +* truncate or create update mtime and ctime. +* +* capability: CAP_DAC_OVERRIDE +* type: KAPI_CAP_BYPASS_CHECK +* allows: Bypass file read, write, and execute permission checks +* without: Standard DAC (discretionary access control) checks are applied +* condition: Checked when file permission would otherwise deny access +* +* capability: CAP_DAC_READ_SEARCH +* type: KAPI_CAP_BYPASS_CHECK +* allows: Bypass read permission on files and search permission on directories +* without: Must have read permission on file or search permission on directory +* condition: Checked during path traversal and file open +* +* capability: CAP_FOWNER +* type: KAPI_CAP_BYPASS_CHECK +* allows: Use O_NOATIME on files not owned by caller +* without: O_NOATIME returns EPERM if caller is not file owner +* condition: Checked when O_NOATIME is specified and caller is not owner +* +* capability: CAP_SYS_ADMIN +* type: KAPI_CAP_INCREASE_LIMIT +* allows: Exceed the system-wide file limit (file-max) +* without: Returns ENFILE when system limit is reached +* condition: Checked in alloc_empty_file() when nr_files >= max_files +* +* constraint: RLIMIT_NOFILE (per-process fd limit) +* desc: The returned file descriptor must be less than the process's +* RLIMIT_NOFILE limit. Default is typically 1024, maximum is controlled +* by /proc/sys/fs/nr_open (default 1048576). Exceeding returns EMFILE. +* expr: fd < rlimit(RLIMIT_NOFILE) +* +* constraint: file-max (system-wide limit) +* desc: System-wide limit on open files in /proc/sys/fs/file-max. Processes +* without CAP_SYS_ADMIN receive ENFILE when this limit is reached. The +* limit is computed based on system memory at boot time. +* expr: nr_files < files_stat.max_files || capable(CAP_SYS_ADMIN) +* +* constraint: PATH_MAX +* desc: Maximum length of pathname including null terminator is PATH_MAX +* (4096 bytes). Individual path components must not exceed NAME_MAX (255). +* +* examples: fd = open("/etc/passwd", O_RDONLY); // Read existing file +* fd = open("/tmp/newfile", O_WRONLY | O_CREAT | O_TRUNC, 0644); // Create/truncate +* fd = open("/tmp/lockfile", O_WRONLY | O_CREAT | O_EXCL, 0600); // Exclusive create +* fd = open("/dev/null", O_RDWR); // Open device +* fd = open("/tmp", O_RDONLY | O_DIRECTORY); // Open directory +* fd = open("/tmp", O_TMPFILE | O_RDWR, 0600); // Anonymous temp file +* +* notes: The distinction between O_RDONLY, O_WRONLY, and O_RDWR is critical. +* O_RDONLY is defined as 0, so (flags & O_RDONLY) will be true for all flags. +* Test access mode using (flags & O_ACCMODE) == O_RDONLY. +* +* When O_CREAT is specified without O_EXCL, there is a race condition between +* testing for file existence and creating it. Use O_CREAT | O_EXCL for atomic +* exclusive file creation. +* +* O_CLOEXEC should be used in multithreaded programs to prevent file descriptor +* leaks to child processes between fork() and execve(). +* +* O_DIRECT has alignment requirements that vary by filesystem. Use statx() +* with STATX_DIOALIGN (Linux 6.1+) to query requirements. Unaligned I/O may +* fail with EINVAL or fall back to buffered I/O. +* +* O_PATH opens a file descriptor that can be used only for certain operations +* (fstat, dup, fcntl, close, fchdir on directories, as dirfd for *at() calls). +* I/O operations will fail with EBADF. +* +* since-version: 1.0 +*/ SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode) {if (force_o_largefile ())
@@ -1581,3 +1905,8 @@ int stream_open(struct inode *inode, struct file *filp) }EXPORT_SYMBOL (stream_open); + +/* Include auto-generated API specifications from kerneldoc annotations */ +#if IS_ENABLED (CONFIG_KAPI_SPEC ) +#include "open.apispec.h" +#endif
Signature · 1 line
2.51.0
PATCH 6/9 kernel/api: add API specification for sys_close
In reply to Sasha Levin--- fs/open.c | 247 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 243 insertions(+), 4 deletions(-)
fs/open.c +243 -4
@@ -1810,10 +1810,249 @@ int filp_close(struct file *filp, fl_owner_t id) }EXPORT_SYMBOL (filp_close); -/* -* Careful here! We test whether the file pointer is NULL before -* releasing the fd. This ensures that one clone task can't release -* an fd while another clone is opening it. +/** +* sys_close - Close a file descriptor +* @fd: The file descriptor to close +* +* long-desc: Terminates access to an open file descriptor, releasing the file +* descriptor for reuse by subsequent open(), dup(), or similar syscalls. Any +* advisory record locks (POSIX locks, OFD locks, and flock locks) held on the +* associated file are released. When this is the last file descriptor +* referring to the underlying open file description, associated resources are +* freed. If the file was previously unlinked, the file itself is deleted when +* the last reference is closed. +* +* CRITICAL: The file descriptor is ALWAYS closed, even when close() returns +* an error. This differs from POSIX semantics where the state of the file +* descriptor is unspecified after EINTR. On Linux, the fd is released early +* in close() processing before flush operations that may fail. Therefore, +* retrying close() after an error return is DANGEROUS and may close an +* unrelated file descriptor that was assigned to another thread. +* +* Errors returned from close() (EIO, ENOSPC, EDQUOT) indicate that the final +* flush of buffered data failed. These errors commonly occur on network +* filesystems like NFS when write errors are deferred to close time. A +* successful return from close() does NOT guarantee that data has been +* successfully written to disk; the kernel uses buffer cache to defer writes. +* To ensure data persistence, call fsync() before close(). +* +* On close, the following cleanup operations are performed: POSIX advisory +* locks are removed, dnotify registrations are cleaned up, the file is +* flushed if the file operations define a flush callback, and the file +* reference is released. If this was the last reference, additional cleanup +* includes: fsnotify close notification, epoll cleanup, flock and lease +* removal, FASYNC cleanup, the file's release callback invocation, and +* the file structure deallocation. +* +* context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE +* +* param: fd +* type: KAPI_TYPE_FD +* flags: KAPI_PARAM_IN +* constraint-type: KAPI_CONSTRAINT_RANGE +* range: 0, INT_MAX +* cdesc: Must be a valid, open file descriptor for the current process. +* The value 0, 1, or 2 (stdin, stdout, stderr) may be closed like any other +* fd, though this is unusual and may cause issues with libraries that assume +* these descriptors are valid. The parameter is unsigned int to match kernel +* file descriptor table indexing, but values exceeding INT_MAX are effectively +* invalid due to internal checks. +* +* return: +* type: KAPI_TYPE_INT +* check-type: KAPI_RETURN_EXACT +* success: 0 +* desc: Returns 0 on success. On error, returns a negative error code. +* IMPORTANT: Even when an error is returned, the file descriptor is still +* closed and must not be used again. The error indicates a problem with +* the final flush operation, not that the fd remains open. +* +* error: EBADF, Bad file descriptor +* desc: The file descriptor fd is not a valid open file descriptor, or was +* already closed. This is the only error that indicates the fd was NOT +* closed (because it was never open to begin with). Occurs when fd is out +* of range, has no file assigned, or was already closed. +* +* error: EINTR, Interrupted system call +* desc: The flush operation was interrupted by a signal before completion. +* This occurs when a file's flush callback (e.g., NFS) performs an +* interruptible wait that receives a signal. IMPORTANT: Despite this error, +* the file descriptor IS closed and must not be used again. This error +* is generated by converting kernel-internal restart codes (ERESTARTSYS, +* ERESTARTNOINTR, ERESTARTNOHAND, ERESTART_RESTARTBLOCK) to EINTR because +* restarting the syscall would be incorrect once the fd is freed. +* +* error: EIO, I/O error +* desc: An I/O error occurred during the flush of buffered data to the +* underlying storage. This typically indicates a hardware error, network +* failure on NFS, or other storage system error. The file descriptor is +* still closed. Previously buffered write data may have been lost. +* +* error: ENOSPC, No space left on device +* desc: There was insufficient space on the storage device to flush buffered +* writes. This is common on NFS when the server runs out of space between +* write() and close(). The file descriptor is still closed. +* +* error: EDQUOT, Disk quota exceeded +* desc: The user's disk quota was exceeded while attempting to flush buffered +* writes. Common on NFS when quota is exceeded between write() and close(). +* The file descriptor is still closed. +* +* lock: files->file_lock +* type: KAPI_LOCK_SPINLOCK +* acquired: true +* released: true +* desc: Acquired via file_close_fd() to atomically lookup and remove the fd +* from the file descriptor table. Held only during the table manipulation; +* released before flush and final cleanup operations. This ensures that +* another thread cannot allocate the same fd number while close is in +* progress. +* +* lock: file->f_lock +* type: KAPI_LOCK_SPINLOCK +* acquired: true +* released: true +* desc: Acquired during epoll cleanup (eventpoll_release_file) and dnotify +* cleanup to safely unlink the file from monitoring structures. May also +* be acquired during lock context operations. +* +* lock: ep->mtx +* type: KAPI_LOCK_MUTEX +* acquired: true +* released: true +* desc: Acquired during epoll cleanup if the file was monitored by epoll. +* Used to safely remove the file from epoll interest lists. +* +* lock: flc_lock +* type: KAPI_LOCK_SPINLOCK +* acquired: true +* released: true +* desc: File lock context spinlock, acquired during locks_remove_file() to +* safely remove POSIX, flock, and lease locks associated with the file. +* +* signal: pending_signals +* direction: KAPI_SIGNAL_RECEIVE +* action: KAPI_SIGNAL_ACTION_RETURN +* condition: When flush callback performs interruptible wait +* desc: If the file's flush callback (e.g., nfs_file_flush) performs an +* interruptible wait and a signal is pending, the wait is interrupted. +* Any kernel restart codes are converted to EINTR since close cannot be +* restarted after the fd is freed. +* error: -EINTR +* timing: KAPI_SIGNAL_TIME_DURING +* restartable: no +* +* side-effect: KAPI_EFFECT_RESOURCE_DESTROY | KAPI_EFFECT_IRREVERSIBLE +* target: File descriptor table entry +* desc: The file descriptor is removed from the process's file descriptor +* table, making the fd number available for reuse by subsequent open(), +* dup(), or similar calls. This occurs BEFORE any flush or cleanup that +* might fail, making the operation irreversible regardless of return value. +* condition: Always (when fd is valid) +* reversible: no +* +* side-effect: KAPI_EFFECT_LOCK_RELEASE +* target: POSIX advisory locks, OFD locks, flock locks +* desc: All advisory locks held on the file by this process are removed. +* POSIX locks are removed via locks_remove_posix() during filp_flush(). +* All lock types (POSIX, OFD, flock) are removed via locks_remove_file() +* during __fput() when this is the last reference. +* condition: File has FMODE_OPENED and !(FMODE_PATH) +* reversible: no +* +* side-effect: KAPI_EFFECT_RESOURCE_DESTROY +* target: File leases +* desc: Any file leases held on the file are removed during locks_remove_file() +* when this is the last reference to the open file description. +* condition: File had leases and this is the last close +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: dnotify registrations +* desc: Directory notification (dnotify) registrations associated with this +* file are cleaned up via dnotify_flush(). This only applies to directories. +* condition: File is a directory with dnotify registrations +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: epoll interest lists +* desc: If the file was being monitored by epoll instances, it is removed +* from those interest lists via eventpoll_release(). +* condition: File was added to epoll instances +* reversible: no +* +* side-effect: KAPI_EFFECT_FILESYSTEM +* target: Buffered data +* desc: The file's flush callback is invoked if defined (e.g., NFS calls +* nfs_file_flush). This attempts to write any buffered data to storage +* and may return errors (EIO, ENOSPC, EDQUOT) if the flush fails. The +* success of this flush is NOT guaranteed even with a 0 return; use +* fsync() before close() to ensure data persistence. +* condition: File has a flush callback and was opened for writing +* reversible: no +* +* side-effect: KAPI_EFFECT_FREE_MEMORY +* target: struct file and related structures +* desc: When this is the last reference to the file, __fput() is called +* synchronously (fput_close_sync), which frees the file structure, releases +* the dentry and mount references, and invokes the file's release callback. +* condition: This is the last reference to the file +* reversible: no +* +* side-effect: KAPI_EFFECT_FILESYSTEM +* target: Unlinked file deletion +* desc: If the file was previously unlinked (deleted) but kept open, closing +* the last reference causes the actual file data to be removed from the +* filesystem and the inode to be freed. +* condition: File was unlinked and this is the last reference +* reversible: no +* +* state-trans: file_descriptor +* from: open +* to: closed/free +* condition: Valid fd passed to close +* desc: The file descriptor transitions from open (usable) to closed (invalid). +* The fd number becomes available for reuse. This transition occurs early +* in close() processing, before any operations that might fail. +* +* state-trans: file_reference_count +* from: n +* to: n-1 (or freed if n was 1) +* condition: Always on successful fd lookup +* desc: The file's reference count is decremented. If this was the last +* reference, the file is fully cleaned up and freed. +* +* constraint: File Descriptor Reuse Race +* desc: Because the fd is freed early in close() processing, another thread +* may receive the same fd number from a concurrent open() before close() +* returns. Applications must not retry close() after an error return, as +* this could close an unrelated file opened by another thread. +* expr: After close(fd) returns (even with error), fd is invalid +* +* examples: close(fd); // Basic usage - ignore errors (common but not ideal) +* if (close(fd) == -1) perror("close"); // Log errors for debugging +* fsync(fd); close(fd); // Ensure data persistence before closing +* +* notes: This syscall has subtle non-POSIX semantics: the fd is ALWAYS closed +* regardless of the return value. POSIX specifies that on EINTR, the state +* of the fd is unspecified, but Linux always closes it. HP-UX requires +* retrying close() on EINTR, but doing so on Linux may close an unrelated +* fd that was reassigned by another thread. For portable code, the safest +* approach is to check for errors but never retry close(). +* +* Error codes from the flush callback (EIO, ENOSPC, EDQUOT) indicate that +* previously written data may have been lost. These errors are particularly +* common on NFS where write errors are often deferred to close time. +* +* The driver's release() callback errors are explicitly ignored by the +* kernel, so device driver cleanup errors are not propagated to userspace. +* +* Calling close() on a file descriptor while another thread is using it +* (e.g., in a blocking read() or write()) has implementation-defined +* behavior. On Linux, the blocked operation continues on the underlying +* file and may complete even after close() returns. +* +* since-version: 1.0 */ SYSCALL_DEFINE1(close, unsigned int, fd) {
Signature · 1 line
2.51.0
PATCH 7/9 kernel/api: add API specification for sys_read
In reply to Sasha Levin--- fs/read_write.c | 305 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 305 insertions(+)
fs/read_write.c +305 -0
@@ -721,6 +721,306 @@ ssize_t ksys_read(unsigned int fd, char __user *buf, size_t count)return ret; } +/** +* sys_read - Read data from a file descriptor +* @fd: File descriptor to read from +* @buf: User-space buffer to read data into +* @count: Maximum number of bytes to read +* +* long-desc: Attempts to read up to count bytes from file descriptor fd into +* the buffer starting at buf. For seekable files (regular files, block +* devices), the read begins at the current file offset, and the file offset +* is advanced by the number of bytes read. For non-seekable files (pipes, +* FIFOs, sockets, character devices), the file offset is not used. +* +* If count is zero and fd refers to a regular file, read() may detect errors +* as described below. In the absence of errors, or if read() does not check +* for errors, a read() with a count of 0 returns zero and has no other effects. +* +* On success, the number of bytes read is returned (zero indicates end of +* file for regular files). It is not an error if this number is smaller than +* the number of bytes requested; this may happen because fewer bytes are +* actually available right now (maybe because we were close to end-of-file, +* or because we are reading from a pipe, socket, or terminal), or because +* read() was interrupted by a signal. +* +* On Linux, read() transfers at most MAX_RW_COUNT (0x7ffff000, approximately +* 2GB) bytes per call, regardless of whether the filesystem would allow more. +* This is to avoid issues with signed arithmetic overflow on 32-bit systems. +* +* POSIX allows reads that are interrupted after reading some data to either +* return -1 (with errno set to EINTR) or return the number of bytes already +* read. Linux follows the latter behavior: if data has been read before a +* signal arrives, the call returns the bytes read rather than failing. +* +* context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE +* +* param: fd +* type: KAPI_TYPE_FD +* flags: KAPI_PARAM_IN +* constraint-type: KAPI_CONSTRAINT_RANGE +* range: 0, INT_MAX +* cdesc: Must be a valid, open file descriptor with read permission. +* The file must have been opened with O_RDONLY or O_RDWR. Special values +* like AT_FDCWD are not valid. File descriptors for directories return +* EISDIR. Standard file descriptors 0 (stdin), 1 (stdout), 2 (stderr) are +* valid if open and readable. +* +* param: buf +* type: KAPI_TYPE_USER_PTR +* flags: KAPI_PARAM_OUT | KAPI_PARAM_USER +* constraint-type: KAPI_CONSTRAINT_BUFFER +* size-param: 2 +* cdesc: Must point to a valid, writable user-space memory region of at +* least count bytes. The buffer is validated via access_ok() before any +* read operation. NULL is invalid and will return EFAULT. The buffer may +* be partially written if an error occurs mid-read. For O_DIRECT reads, +* the buffer may need to be aligned to the filesystem's block size (varies +* by filesystem, check via statx() with STATX_DIOALIGN). +* +* param: count +* type: KAPI_TYPE_UINT +* flags: KAPI_PARAM_IN +* constraint-type: KAPI_CONSTRAINT_RANGE +* range: 0, SIZE_MAX +* cdesc: Maximum number of bytes to read. Clamped internally to +* MAX_RW_COUNT (INT_MAX & PAGE_MASK, approximately 0x7ffff000 bytes) to +* prevent signed overflow issues. A count of 0 returns immediately with 0 +* without accessing the file (but may still detect errors). Large values +* are not errors but will be clamped. Cast to ssize_t must not be negative. +* +* return: +* type: KAPI_TYPE_INT +* check-type: KAPI_RETURN_RANGE +* success: >= 0 +* desc: On success, returns the number of bytes read (non-negative). Zero +* indicates end-of-file (EOF) for regular files, or no data available +* from a device that does not block. The return value may be less than +* count if fewer bytes were available (short read). Partial reads are +* not errors. On error, returns a negative error code. +* +* error: EBADF, Bad file descriptor +* desc: fd is not a valid file descriptor, or fd was not opened for reading. +* This includes file descriptors opened with O_WRONLY, O_PATH, or file +* descriptors that have been closed. Also returned if the file structure +* does not have FMODE_READ set. +* +* error: EFAULT, Bad address +* desc: buf points outside the accessible address space. The buffer address +* failed access_ok() validation. Can also occur if a fault happens during +* copy_to_user() when transferring data to user space after the read +* completes in kernel space. +* +* error: EINVAL, Invalid argument +* desc: Returned in several cases: (1) The file descriptor refers to an +* object that is not suitable for reading (no read or read_iter method). +* (2) The file was opened with O_DIRECT and the buffer alignment, offset, +* or count does not meet the filesystem's alignment requirements. (3) For +* timerfd file descriptors, the buffer is smaller than 8 bytes. (4) The +* count argument, when cast to ssize_t, is negative. +* +* error: EISDIR, Is a directory +* desc: fd refers to a directory. Directories cannot be read using read(); +* use getdents64() instead. This error is returned by the generic_read_dir() +* handler installed for directory file operations. +* +* error: EAGAIN, Resource temporarily unavailable +* desc: fd refers to a file (pipe, socket, device) that is marked non-blocking +* (O_NONBLOCK) and the read would block. Also returned with IOCB_NOWAIT +* when data is not immediately available. Equivalent to EWOULDBLOCK. +* The application should retry the read later or use select/poll/epoll. +* +* error: EINTR, Interrupted system call +* desc: The call was interrupted by a signal before any data was read. This +* only occurs if no data has been transferred; if some data was read before +* the signal, the call returns the number of bytes read. The caller should +* typically restart the read. +* +* error: EIO, Input/output error +* desc: A low-level I/O error occurred. For regular files, this typically +* indicates a hardware error on the storage device, a filesystem error, +* or a network filesystem timeout. For terminals, this may indicate the +* controlling terminal has been closed for a background process. +* +* error: EOVERFLOW, Value too large for defined data type +* desc: The file position plus count would exceed LLONG_MAX. Also returned +* when reading from certain files (e.g., some /proc files) where the file +* position would overflow. For files without FOP_UNSIGNED_OFFSET flag, +* negative file positions are not allowed. +* +* error: ENOBUFS, No buffer space available +* desc: Returned when reading from pipe-based watch queues (CONFIG_WATCH_QUEUE) +* when the buffer is too small to hold a complete notification, or when +* reading packets from pipes with PIPE_BUF_FLAG_WHOLE set. +* +* error: ERESTARTSYS, Restart system call (internal) +* desc: Internal error code indicating the syscall should be restarted. This +* is typically translated to EINTR if SA_RESTART is not set on the signal +* handler, or the syscall is transparently restarted if SA_RESTART is set. +* User space should not see this error code directly. +* +* error: EACCES, Permission denied +* desc: The security subsystem (LSM such as SELinux or AppArmor) denied +* the read operation via security_file_permission(). This can occur even +* if the file was successfully opened, as LSM policies may enforce per- +* operation checks. +* +* error: EPERM, Operation not permitted +* desc: Returned by fanotify permission events (CONFIG_FANOTIFY_ACCESS_PERMISSIONS) +* when a user-space fanotify listener denies the read operation via +* fsnotify_file_area_perm(). +* +* error: ENODATA, No data available +* desc: Returned when reading from files backed by fscache/cachefiles +* and the requested data range is not available in the cache +* (e.g., beyond EOF or in an uncached region). Also returned by +* some filesystem-specific read handlers (e.g., xattr reads). +* +* error: EOPNOTSUPP, Operation not supported +* desc: Returned when the file descriptor does not support the read +* operation, such as reading from certain special files or when the +* filesystem does not implement read for this file type. +* +* lock: file->f_pos_lock +* type: KAPI_LOCK_MUTEX +* acquired: conditional +* released: true +* desc: For regular files that require atomic position updates (FMODE_ATOMIC_POS), +* the f_pos_lock mutex is acquired by fdget_pos() at syscall entry and released +* by fdput_pos() at syscall exit. This serializes concurrent reads that share +* the same file description. Not acquired for files opened with FMODE_STREAM +* (pipes, sockets) or when the file is not shared. +* +* lock: Filesystem-specific locks +* type: KAPI_LOCK_CUSTOM +* acquired: conditional +* released: true +* desc: The filesystem's read_iter or read method may acquire additional locks. +* For regular files, this typically includes the inode's i_rwsem for certain +* operations. For pipes, the pipe->mutex is acquired. For sockets, socket +* lock is acquired. These are internal to the file operation and released +* before return. +* +* lock: RCU read-side +* type: KAPI_LOCK_RCU +* acquired: conditional +* released: true +* desc: Used during file descriptor lookup via fdget(). RCU read lock protects +* access to the file descriptor table. Released by fdput() at syscall exit. +* +* signal: Any signal +* direction: KAPI_SIGNAL_RECEIVE +* action: KAPI_SIGNAL_ACTION_RETURN +* condition: When blocked waiting for data on interruptible operations +* desc: The syscall may be interrupted by signals while waiting for data to +* become available (pipes, sockets, terminals) or waiting for locks. If +* interrupted before any data is read, returns -EINTR or -ERESTARTSYS. +* If data has already been read, returns the number of bytes read. +* error: -EINTR +* timing: KAPI_SIGNAL_TIME_DURING +* restartable: yes +* +* side-effect: KAPI_EFFECT_FILE_POSITION +* target: file->f_pos +* condition: For seekable files when read succeeds (returns > 0) +* desc: The file offset (f_pos) is advanced by the number of bytes read. +* For stream files (FMODE_STREAM such as pipes and sockets), the offset +* is not used or modified. The offset update is protected by f_pos_lock +* when the file is shared between threads/processes. +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: inode access time (atime) +* condition: When read succeeds and O_NOATIME is not set +* desc: Updates the file's access time (atime) via touch_atime(). The update +* may be suppressed by mount options (noatime, relatime), the O_NOATIME +* flag, or if the filesystem does not support atime. Relatime only updates +* atime if it is older than mtime or ctime, or more than a day old. +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: task I/O accounting +* condition: Always +* desc: Updates the current task's I/O accounting statistics. The rchar field +* (read characters) is incremented by bytes read via add_rchar() only on +* successful reads (ret > 0). The syscr field (syscall read count) is +* incremented unconditionally via inc_syscr(). These statistics are visible +* in /proc/[pid]/io. +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: fsnotify events +* condition: When read returns > 0 +* desc: Generates an FS_ACCESS fsnotify event via fsnotify_access() allowing +* inotify, fanotify, and dnotify watchers to be notified of the read. This +* occurs after data transfer completes successfully. +* reversible: no +* +* capability: CAP_DAC_OVERRIDE +* type: KAPI_CAP_BYPASS_CHECK +* allows: Bypass discretionary access control on read permission +* without: Standard DAC checks are enforced +* condition: Checked via security_file_permission() during rw_verify_area() +* +* capability: CAP_DAC_READ_SEARCH +* type: KAPI_CAP_BYPASS_CHECK +* allows: Bypass read permission checks on regular files +* without: Must have read permission on file +* condition: Checked by LSM hooks during the read operation +* +* constraint: MAX_RW_COUNT +* desc: The count parameter is silently clamped to MAX_RW_COUNT (INT_MAX & +* PAGE_MASK, approximately 2GB minus one page) to prevent integer overflow +* in internal calculations. This is transparent to the caller; the syscall +* succeeds but reads at most MAX_RW_COUNT bytes. +* expr: actual_count = min(count, MAX_RW_COUNT) +* +* constraint: File must be open for reading +* desc: The file descriptor must have been opened with O_RDONLY or O_RDWR. +* Files opened with O_WRONLY or O_PATH cannot be read and return EBADF. +* The file must have both FMODE_READ and FMODE_CAN_READ flags set. +* expr: (file->f_mode & FMODE_READ) && (file->f_mode & FMODE_CAN_READ) +* +* examples: n = read(fd, buf, sizeof(buf)); // Basic read +* n = read(STDIN_FILENO, buf, 1024); // Read from stdin +* while ((n = read(fd, buf, 4096)) > 0) { process(buf, n); } // Read loop +* if (read(fd, buf, count) == 0) { handle_eof(); } // Check for EOF +* +* notes: The behavior of read() varies significantly depending on the type of +* file descriptor: +* +* - Regular files: Reads from current position, advances position, returns 0 +* at EOF. Short reads are rare but possible near EOF or on signal. +* +* - Pipes and FIFOs: Blocking by default. Returns available data (up to count) +* or blocks until data is available. Returns 0 when all writers have closed. +* O_NONBLOCK returns EAGAIN when empty instead of blocking. +* +* - Sockets: Similar to pipes. Specific behavior depends on socket type and +* protocol. MSG_* flags can be specified via recv() for more control. +* +* - Terminals: Line-buffered in canonical mode; read returns when newline is +* entered or buffer is full. Raw mode returns immediately when data available. +* Special handling for signals (SIGINT on Ctrl+C, etc.). +* +* - Device special files: Behavior is device-specific. Some devices support +* seeking, others do not. Read size may be constrained by device. +* +* Race condition: Concurrent reads from the same file description (not just +* file descriptor) can race on the file position. Linux 3.14+ provides atomic +* position updates for regular files via f_pos_lock, but applications should +* use pread() for concurrent positioned reads. +* +* O_DIRECT reads bypass the page cache and typically require aligned buffers +* and positions. Alignment requirements are filesystem-specific; use statx() +* with STATX_DIOALIGN (Linux 6.1+) to query. Unaligned O_DIRECT reads fail +* with EINVAL on most filesystems. +* +* For splice(2)-like zero-copy reads, consider using splice(), sendfile(), +* or copy_file_range() instead of read() + write(). +* +* since-version: 1.0 +*/ SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count) {return ksys_read (fd, buf, count);
@@ -1821,3 +2121,8 @@ int generic_atomic_write_valid(struct kiocb *iocb, struct iov_iter *iter)return 0 ; }EXPORT_SYMBOL_GPL (generic_atomic_write_valid); + +/* Include auto-generated API specifications from kerneldoc annotations */ +#if IS_ENABLED (CONFIG_KAPI_SPEC ) +#include "read_write.apispec.h" +#endif
Signature · 1 line
2.51.0
PATCH 8/9 kernel/api: add API specification for sys_write
In reply to Sasha Levin--- fs/read_write.c | 382 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 382 insertions(+)
fs/read_write.c +382 -0
@@ -1045,6 +1045,388 @@ ssize_t ksys_write(unsigned int fd, const char __user *buf, size_t count)return ret; } +/** +* sys_write - Write data to a file descriptor +* @fd: File descriptor to write to +* @buf: User-space buffer containing data to write +* @count: Maximum number of bytes to write +* +* long-desc: Attempts to write up to count bytes from the buffer starting at +* buf to the file referred to by the file descriptor fd. For seekable files +* (regular files, block devices), the write begins at the current file offset, +* and the file offset is advanced by the number of bytes written. If the file +* was opened with O_APPEND, the file offset is first set to the end of the +* file before writing. For non-seekable files (pipes, FIFOs, sockets, character +* devices), the file offset is not used and writing occurs at the current +* position as defined by the device. +* +* The number of bytes written may be less than count if, for example, there is +* insufficient space on the underlying physical medium, or the RLIMIT_FSIZE +* resource limit is encountered, or the call was interrupted by a signal +* handler after having written less than count bytes. In the event of a +* successful partial write, the caller should make another write() call to +* transfer the remaining bytes. This behavior is called a "short write." +* +* On Linux, write() transfers at most MAX_RW_COUNT (0x7ffff000, approximately +* 2GB minus one page) bytes per call, regardless of whether the file or +* filesystem would allow more. This prevents signed arithmetic overflow. +* +* For regular files, a successful write() does not guarantee that data has been +* committed to disk. Use fsync(2) or fdatasync(2) if durability is required. +* For O_SYNC or O_DSYNC files, the kernel automatically syncs data on write. +* +* POSIX permits writes that are interrupted after partial writes to either +* return -1 with errno=EINTR, or to return the count of bytes already written. +* Linux implements the latter behavior: if some data has been written before +* a signal arrives, write() returns the number of bytes written rather than +* failing with EINTR. +* +* context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE +* +* param: fd +* type: KAPI_TYPE_FD +* flags: KAPI_PARAM_IN +* constraint-type: KAPI_CONSTRAINT_RANGE +* range: 0, INT_MAX +* cdesc: Must be a valid, open file descriptor with write permission. +* The file must have been opened with O_WRONLY or O_RDWR. File descriptors +* opened with O_RDONLY, O_PATH, or that have been closed return EBADF. +* Standard file descriptors 0 (stdin), 1 (stdout), 2 (stderr) are valid if +* open and writable. AT_FDCWD and other special values are not valid. +* +* param: buf +* type: KAPI_TYPE_USER_PTR +* flags: KAPI_PARAM_IN | KAPI_PARAM_USER +* constraint-type: KAPI_CONSTRAINT_BUFFER +* size-param: 2 +* cdesc: Must point to a valid, readable user-space memory region of at +* least count bytes. The buffer is validated via access_ok() before any +* write operation. NULL is invalid and returns EFAULT. For O_DIRECT writes, +* the buffer may need to be aligned to the filesystem's block size (varies +* by filesystem; query with statx() using STATX_DIOALIGN on Linux 6.1+). +* +* param: count +* type: KAPI_TYPE_UINT +* flags: KAPI_PARAM_IN +* constraint-type: KAPI_CONSTRAINT_RANGE +* range: 0, SIZE_MAX +* cdesc: Maximum number of bytes to write. Clamped internally to +* MAX_RW_COUNT (INT_MAX & PAGE_MASK, approximately 0x7ffff000 bytes) to +* prevent signed overflow. A count of 0 returns 0 immediately without any +* file operations. Cast to ssize_t must not be negative. +* +* return: +* type: KAPI_TYPE_INT +* check-type: KAPI_RETURN_RANGE +* success: >= 0 +* desc: On success, returns the number of bytes written (non-negative). Zero +* indicates that nothing was written (count was 0, or no space available +* for non-blocking writes). The return value may be less than count due to +* resource limits, signal interruption, or device constraints (short write). +* On error, returns a negative error code. +* +* error: EBADF, Bad file descriptor +* desc: fd is not a valid file descriptor, or fd was not opened for writing. +* This includes file descriptors opened with O_RDONLY, O_PATH, or file +* descriptors that have been closed. Also returned if the file structure +* does not have FMODE_WRITE or FMODE_CAN_WRITE set. +* +* error: EFAULT, Bad address +* desc: buf points outside the accessible address space. The buffer address +* failed access_ok() validation. Can also occur if a fault happens during +* copy_from_user() when reading data from user space. +* +* error: EINVAL, Invalid argument +* desc: Returned in several cases: (1) The file descriptor refers to an +* object that is not suitable for writing (no write or write_iter method). +* (2) The file was opened with O_DIRECT and the buffer alignment, offset, +* or count does not meet the filesystem's alignment requirements. (3) The +* count argument, when cast to ssize_t, is negative. (4) For IOCB_NOWAIT +* operations on non-O_DIRECT files that don't support WASYNC. +* +* error: EAGAIN, Resource temporarily unavailable +* desc: fd refers to a file (pipe, socket, device) that is marked non-blocking +* (O_NONBLOCK) and the write would block because the buffer is full. Also +* returned with IOCB_NOWAIT when data cannot be written immediately. +* Equivalent to EWOULDBLOCK. The application should retry later or use +* select/poll/epoll to wait for writability. +* +* error: EINTR, Interrupted system call +* desc: The call was interrupted by a signal before any data was written. This +* only occurs if no data has been transferred; if some data was written +* before the signal, the call returns the number of bytes written. The +* caller should typically restart the write. +* +* error: EPIPE, Broken pipe +* desc: fd refers to a pipe or socket whose reading end has been closed. +* When this condition occurs, the calling process also receives a SIGPIPE +* signal. If the signal is caught or ignored, EPIPE is still returned. +* For sockets, MSG_NOSIGNAL (via send()) suppresses the signal. For +* pwritev2(), the RWF_NOSIGNAL flag suppresses it. +* +* error: EFBIG, File too large +* desc: An attempt was made to write a file that exceeds the implementation- +* defined maximum file size or the file size limit (RLIMIT_FSIZE) of the +* process. When RLIMIT_FSIZE is exceeded, the process also receives SIGXFSZ. +* For files not opened with O_LARGEFILE on 32-bit systems, the limit is 2GB. +* +* error: ENOSPC, No space left on device +* desc: The device containing the file has no room for the data. This can +* occur mid-write resulting in a short write followed by ENOSPC on retry. +* +* error: EDQUOT, Disk quota exceeded +* desc: The user's quota of disk blocks on the filesystem has been exhausted. +* Like ENOSPC, this can result in a short write. +* +* error: EIO, Input/output error +* desc: A low-level I/O error occurred while modifying the inode or writing +* data. This typically indicates hardware failure, filesystem corruption, +* or network filesystem timeout. Some data may have been written. +* +* error: EPERM, Operation not permitted +* desc: The operation was prevented: (1) by a file seal (F_SEAL_WRITE or +* F_SEAL_FUTURE_WRITE on memfd/shmem), (2) writing to an immutable inode +* (IS_IMMUTABLE), (3) by an LSM hook denying the operation, or (4) by a +* fanotify permission event denying the write. +* +* error: EOVERFLOW, Value too large for defined data type +* desc: The file position plus count would exceed LLONG_MAX. Also returned +* when the offset would exceed filesystem limits after the write. +* +* error: EDESTADDRREQ, Destination address required +* desc: fd is a datagram socket for which no peer address has been set using +* connect(2). Use sendto(2) to specify the destination address. +* +* error: ETXTBSY, Text file busy +* desc: The file is being used as a swap file (IS_SWAPFILE). Note: unlike +* the traditional Unix meaning, Linux does not return ETXTBSY when writing +* to an executing binary; that only blocks open() with O_WRONLY/O_RDWR. +* +* error: EXDEV, Cross-device link +* desc: When writing to a pipe that has been configured as a watch queue +* (CONFIG_WATCH_QUEUE), direct write() calls are not supported. +* +* error: ENOMEM, Out of memory +* desc: Insufficient kernel memory was available for the write operation. +* For pipes, this occurs when allocating pages for the pipe buffer. +* +* error: ERESTARTSYS, Restart system call (internal) +* desc: Internal error code indicating the syscall should be restarted. This +* is converted to EINTR if SA_RESTART is not set on the signal handler, or +* the syscall is transparently restarted if SA_RESTART is set. User space +* should not see this error code directly. +* +* error: EACCES, Permission denied +* desc: The security subsystem (LSM such as SELinux or AppArmor) denied the +* write operation via security_file_permission(). This can occur even if +* the file was successfully opened. +* +* lock: file->f_pos_lock +* type: KAPI_LOCK_MUTEX +* acquired: conditional +* released: true +* desc: For regular files that require atomic position updates (FMODE_ATOMIC_POS), +* the f_pos_lock mutex is acquired by fdget_pos() at syscall entry and released +* by fdput_pos() at syscall exit. This serializes concurrent writes sharing +* the same file description. Not acquired for stream files (FMODE_STREAM like +* pipes and sockets) or when the file is not shared. +* +* lock: sb->s_writers (freeze protection) +* type: KAPI_LOCK_CUSTOM +* acquired: conditional +* released: true +* desc: For regular files, file_start_write() acquires freeze protection on +* the superblock via sb_start_write() before the write, and file_end_write() +* releases it after. This prevents writes during filesystem freeze. Not +* acquired for non-regular files (pipes, sockets, devices). +* +* lock: inode->i_rwsem +* type: KAPI_LOCK_RWLOCK +* acquired: conditional +* released: true +* desc: For regular files using generic_file_write_iter(), the inode's i_rwsem +* is acquired in write mode before modifying file data. This is internal to +* the filesystem and released before return. Not all filesystems use this +* pattern. +* +* lock: pipe->mutex +* type: KAPI_LOCK_MUTEX +* acquired: conditional +* released: true +* desc: For pipes and FIFOs, the pipe's mutex is held while modifying pipe +* buffers. Released temporarily while waiting for space, then reacquired. +* +* lock: RCU read-side +* type: KAPI_LOCK_RCU +* acquired: conditional +* released: true +* desc: Used during file descriptor lookup via fdget(). RCU read lock protects +* access to the file descriptor table. Released by fdput() at syscall exit. +* +* signal: SIGPIPE +* direction: KAPI_SIGNAL_SEND +* action: KAPI_SIGNAL_ACTION_TERMINATE +* condition: Writing to a pipe or socket with no readers +* desc: When writing to a pipe whose read end is closed, or a socket whose +* peer has closed, SIGPIPE is sent to the calling process. The default +* action terminates the process. Use signal(SIGPIPE, SIG_IGN) to suppress +* for write(). EPIPE is returned regardless of signal disposition. +* timing: KAPI_SIGNAL_TIME_DURING +* +* signal: SIGXFSZ +* direction: KAPI_SIGNAL_SEND +* action: KAPI_SIGNAL_ACTION_COREDUMP +* condition: Writing exceeds RLIMIT_FSIZE +* desc: When a write would exceed the soft file size limit (RLIMIT_FSIZE), +* SIGXFSZ is sent. The default action terminates with a core dump. The +* write returns EFBIG. If RLIMIT_FSIZE is RLIM_INFINITY, no signal is sent. +* timing: KAPI_SIGNAL_TIME_DURING +* +* signal: Any signal +* direction: KAPI_SIGNAL_RECEIVE +* action: KAPI_SIGNAL_ACTION_RETURN +* condition: While blocked waiting for space (pipes, sockets) +* desc: The syscall may be interrupted by signals while waiting for buffer +* space to become available. If interrupted before any data is written, +* returns -EINTR or -ERESTARTSYS. If data was already written, returns the +* byte count. Restartable if SA_RESTART is set and no data was written. +* error: -EINTR +* timing: KAPI_SIGNAL_TIME_DURING +* restartable: yes +* +* side-effect: KAPI_EFFECT_FILE_POSITION +* target: file->f_pos +* condition: For seekable files when write succeeds (returns > 0) +* desc: The file offset (f_pos) is advanced by the number of bytes written. +* For files opened with O_APPEND, f_pos is first set to file size. For +* stream files (FMODE_STREAM such as pipes and sockets), the offset is not +* used or modified. Position updates are protected by f_pos_lock when +* shared. +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: inode timestamps (mtime, ctime) +* condition: When write succeeds (returns > 0) +* desc: Updates the file's modification time (mtime) and change time (ctime) +* via file_update_time(). The update precision depends on filesystem mount +* options (fine-grained timestamps for multigrain inodes). +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: SUID/SGID bits (mode) +* condition: When writing to a setuid/setgid file +* desc: The SUID bit is cleared when a non-root user writes to a file with +* the bit set. The SGID bit may also be cleared. This is a security feature +* to prevent privilege escalation via modified setuid binaries. Done via +* file_remove_privs(). +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: file data +* condition: When write succeeds (returns > 0) +* desc: Modifies the file's data content. For regular files, data is written +* to the page cache (buffered I/O) or directly to storage (O_DIRECT). +* Data may not be persistent until fsync() is called or the file is closed. +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: task I/O accounting +* condition: Always +* desc: Updates the current task's I/O accounting statistics. The wchar field +* (write characters) is incremented by bytes written via add_wchar() only on +* successful writes (ret > 0). The syscw field (syscall write count) is +* incremented unconditionally via inc_syscw(). These statistics are visible +* in /proc/[pid]/io. +* reversible: no +* +* side-effect: KAPI_EFFECT_MODIFY_STATE +* target: fsnotify events +* condition: When write returns > 0 +* desc: Generates an FS_MODIFY fsnotify event via fsnotify_modify(), allowing +* inotify, fanotify, and dnotify watchers to be notified of the write. +* +* capability: CAP_DAC_OVERRIDE +* type: KAPI_CAP_BYPASS_CHECK +* allows: Bypass discretionary access control on write permission +* without: Standard DAC checks are enforced +* condition: Checked via security_file_permission() during rw_verify_area() +* +* capability: CAP_FOWNER +* type: KAPI_CAP_BYPASS_CHECK +* allows: Bypass ownership checks for SUID/SGID clearing +* without: SUID/SGID bits are cleared on write by non-owner +* condition: Checked during file_remove_privs() +* +* constraint: MAX_RW_COUNT +* desc: The count parameter is silently clamped to MAX_RW_COUNT (INT_MAX & +* PAGE_MASK, approximately 2GB minus one page) to prevent integer overflow +* in internal calculations. This is transparent to the caller. +* expr: actual_count = min(count, MAX_RW_COUNT) +* +* constraint: File must be open for writing +* desc: The file descriptor must have been opened with O_WRONLY or O_RDWR. +* Files opened with O_RDONLY or O_PATH cannot be written and return EBADF. +* The file must have both FMODE_WRITE and FMODE_CAN_WRITE flags set. +* expr: (file->f_mode & FMODE_WRITE) && (file->f_mode & FMODE_CAN_WRITE) +* +* constraint: RLIMIT_FSIZE +* desc: The size of data written is constrained by the RLIMIT_FSIZE resource +* limit. If writing would exceed this limit, SIGXFSZ is sent and EFBIG is +* returned. The limit does not apply to files beyond the limit - only to +* writes that would cross it. +* expr: pos + count <= rlimit(RLIMIT_FSIZE) || rlimit(RLIMIT_FSIZE) == RLIM_INFINITY +* +* constraint: File seals +* desc: For memfd or shmem files with F_SEAL_WRITE or F_SEAL_FUTURE_WRITE +* seals applied, all write operations fail with EPERM. With F_SEAL_GROW, +* writes that would extend file size fail with EPERM. +* +* examples: n = write(fd, buf, sizeof(buf)); // Basic write +* n = write(STDOUT_FILENO, msg, strlen(msg)); // Write to stdout +* while (total < len) { n = write(fd, buf+total, len-total); if (n<0) break; total += n; } // Handle short writes +* if (write(pipefd[1], &byte, 1) < 0 && errno == EPIPE) { handle_broken_pipe(); } // Pipe error handling +* +* notes: The behavior of write() varies significantly depending on the type of +* file descriptor: +* +* - Regular files: Writes to the page cache (buffered) or directly to storage +* (O_DIRECT). Short writes are rare except near RLIMIT_FSIZE or disk full. +* O_APPEND is atomic for determining write position. +* +* - Pipes and FIFOs: Blocking by default. Writes up to PIPE_BUF (4096 bytes +* on Linux) are guaranteed atomic. Larger writes may be interleaved with +* writes from other processes. Blocks if pipe is full; returns EAGAIN with +* O_NONBLOCK. SIGPIPE/EPIPE if no readers. +* +* - Sockets: Behavior depends on socket type and protocol. Stream sockets +* (TCP) may return partial writes. Datagram sockets (UDP) typically write +* complete messages or fail. SIGPIPE/EPIPE for broken connections (unless +* MSG_NOSIGNAL). EDESTADDRREQ for unconnected datagram sockets. +* +* - Terminals: May block on flow control. Canonical vs raw mode affects +* behavior. Special characters may be interpreted. +* +* - Device special files: Behavior is device-specific. Block devices behave +* similarly to regular files. Character device behavior varies. +* +* Race condition considerations: Concurrent writes from threads sharing a +* file description race on the file position. Linux 3.14+ provides atomic +* position updates via f_pos_lock for regular files (FMODE_ATOMIC_POS), but +* for maximum safety, use pwrite() for concurrent positioned writes. +* +* O_DIRECT writes bypass the page cache and typically require buffer and +* offset alignment to filesystem block size. Query requirements via statx() +* with STATX_DIOALIGN (Linux 6.1+). Unaligned O_DIRECT writes return EINVAL +* on most filesystems. +* +* For zero-copy writes, consider using splice(2), sendfile(2), or vmsplice(2) +* instead of copying data through user-space buffers with write(). +* +* Partial writes (short writes) must be handled by application code. +* Applications should loop until all data is written or an error occurs. +* +* since-version: 1.0 +*/ SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf, size_t, count) {
Signature · 1 line
2.51.0
PATCH 9/9 kernel/api: add runtime verification selftest
In reply to Sasha LevinAdd a selftest for CONFIG_KAPI_RUNTIME_CHECKS that exercises sys_open/sys_read/sys_write/sys_close through raw syscall() and verifies KAPI pre-validation catches invalid parameters while allowing valid operations through.
Test cases (TAP output):
1-4: Valid open/read/write/close succeed
5-7: Invalid flags, mode bits, NULL path rejected with EINVAL
8: dmesg contains expected KAPI warning strings
--- MAINTAINERS | 1 + tools/testing/selftests/kapi/Makefile | 7 + tools/testing/selftests/kapi/kapi_test_util.h | 31 + tools/testing/selftests/kapi/test_kapi.c | 1021 +++++++++++++++++ 4 files changed, 1060 insertions(+) create mode 100644 tools/testing/selftests/kapi/Makefile create mode 100644 tools/testing/selftests/kapi/kapi_test_util.h create mode 100644 tools/testing/selftests/kapi/test_kapi.c
MAINTAINERS +1 -0
@@ -13820,6 +13820,7 @@ F: include/linux/syscall_api_spec.h F: kernel/api/ F: tools/kapi/ F: tools/lib/python/kdoc/kdoc_apispec.py +F: tools/testing/selftests/kapi/ KERNEL AUTOMOUNTER M: Ian Kent <[email protected]>
tools/testing/selftests/kapi/Makefile new file +7 -0
@@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-2.0 + +TEST_GEN_PROGS := test_kapi + +CFLAGS += -static -Wall -O2 $(KHDR_INCLUDES) + +include ../lib.mk
tools/testing/selftests/kapi/kapi_test_util.h new file +31 -0
@@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Compatibility helpers for KAPI selftests. +* +* __NR_open is not defined on aarch64 and riscv64 (only __NR_openat exists). +* Provide a wrapper that uses __NR_openat with AT_FDCWD to achieve the same +* behavior as __NR_open on architectures that lack it. +*/ +#ifndef KAPI_TEST_UTIL_H +#define KAPI_TEST_UTIL_H + +#include <fcntl.h> +#include <sys/syscall.h> + +#ifndef __NR_open +/* +* On architectures without __NR_open (e.g., aarch64, riscv64), +* use openat(AT_FDCWD, ...) which is equivalent. +*/ +static inline long kapi_sys_open (const char *pathname,int flags,int mode) +{ +return syscall (__NR_openat,AT_FDCWD , pathname, flags, mode); +} +#else +static inline long kapi_sys_open (const char *pathname,int flags,int mode) +{ +return syscall (__NR_open, pathname, flags, mode); +} +#endif + +#endif /* KAPI_TEST_UTIL_H */
tools/testing/selftests/kapi/test_kapi.c new file +1021 -0
1,021 lines not on this page · raw message
Signature · 1 line
2.51.0
Re: [PATCH 3/9] kernel/api: add debugfs interface for kernel API specifications
In reply to Sasha LevinQuoted 18 lines · Sasha Levin
Add a debugfs interface to expose kernel API specifications at runtime. This allows tools and users to query the complete API specifications through the debugfs filesystem.
The interface provides:
-/sys/kernel/debug/kapi/list- lists all available API specifications
- /sys/kernel/debug/kapi/specs/<name> - detailed info for each APIEach 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
Quoted 6 lines
This enables runtime introspection of kernel APIs for documentation tools, static analyzers, and debugging purposes.
Signed-off-by Sasha Levin <[email protected]>--- Documentation/dev-tools/kernel-api-spec.rst | 88 ++--
You are removing stuff from the file you created earlier in this patch series, is that ok?
kernel/api/kapi_debugfs.c line 7
Quoted 10 lines
kernel/api/kapi_debugfs.c new file +7
-0@@ -0,0 +1,503 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Kernel API specification debugfs interface +* +* This provides a debugfs interface to expose kernel API specifications +* at runtime, allowing tools and users to query the complete API specs. +*/
No copyright line? :)
And this is, a totally and crazy interface with debugfs, I love it!
Two minor minor nits:
Quoted 8 lines
kernel/api/kapi_debugfs.c new file +8
-0+static int __init kapi_debugfs_init (void ) +{ +struct kernel_api_spec *spec; +struct dentry *spec_dir; + +/* Create main directory */ + kapi_debugfs_root =debugfs_create_dir ("kapi" ,NULL ); +
kernel/api/kapi_debugfs.c line 496
Quoted 10 lines
kernel/api/kapi_debugfs.c new file +10
-0+/* Create list file */ +debugfs_create_file ("list" ,0444 , kapi_debugfs_root,NULL , &kapi_list_fops); + +/* Create specs subdirectory */ + spec_dir =debugfs_create_dir ("specs" , kapi_debugfs_root); + +/* Create a file for each API spec */ +for (spec = __start_kapi_specs; spec < __stop_kapi_specs; spec++) { +debugfs_create_file (spec->name,0444 , spec_dir, spec, &kapi_spec_fops); + }
No need for { }
kernel/api/kapi_debugfs.c line 27
Quoted 2 lines
kernel/api/kapi_debugfs.c new file +2
-0+ +pr_info ("Kernel API debugfs interface initialized\n" );
When code is working properly, it should be quiet, no need for this as initializing this can not fail.
thanks,
greg k-h
Re: [PATCH 5/9] kernel/api: add API specification for sys_open
In reply to Sasha LevinQuoted 1 line · Sasha Levin
Signed-off-by Sasha Levin <[email protected]>
No changelog?
Quoted 1 line
+ * since-version: 1.0
I think since older versions :)
Anyway, very nice documentation, will be good to have this as part of the kerneldocs no matter what the result of this patch series is.
thanks,
greg k-h
Re: [PATCH 6/9] kernel/api: add API specification for sys_close
In reply to Sasha LevinQuoted 4 lines · Sasha Levin
+ * Calling close() on a file descriptor while another thread is using it + * (e.g., in a blocking read() or write()) has implementation-defined + * behavior. On Linux, the blocked operation continues on the underlying + * file and may complete even after close() returns.
I'm guessing this came from the man pages? This is Linux, so we are the "implementation" here :)
thanks,
greg k-h
Re: [PATCH 6/9] kernel/api: add API specification for sys_close
In reply to Sasha LevinQuoted 6 lines · Sasha Levin
+ * notes: This syscall has subtle non-POSIX semantics: the fd is ALWAYS closed
+ * regardless of the return value. POSIX specifies that on EINTR, the state + * of the fd is unspecified, but Linux always closes it. HP-UX requires + * retrying close() on EINTR, but doing so on Linux may close an unrelated + * fd that was reassigned by another thread. For portable code, the safest + * approach is to check for errors but never retry close().
We don't care about HP-UX :)
Quoted 3 lines
+ * Error codes from the flush callback (EIO, ENOSPC, EDQUOT) indicate that + * previously written data may have been lost. These errors are particularly + * common on NFS where write errors are often deferred to close time.
What flush callback?
Quoted 3 lines
+ *
+ * The driver'srelease()callback errors are explicitly ignored by the
+ * kernel, so device driver cleanup errors are not propagated to userspace.
What "The driver" here? release() callbacks aren't really relevant here.
thanks,
greg k-h
Re: [PATCH 3/9] kernel/api: add debugfs interface for kernel API specifications
In reply to Greg Kroah-HartmanQuoted 22 lines · Greg Kroah-Hartman
Quoted 21 lines · Sasha Levin
Add a debugfs interface to expose kernel API specifications at runtime. This allows tools and users to query the complete API specifications through the debugfs filesystem.
The interface provides:
-/sys/kernel/debug/kapi/list- lists all available API specifications
- /sys/kernel/debug/kapi/specs/<name> - detailed info for each APIEach 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 statusThis enables runtime introspection of kernel APIs for documentation tools, static analyzers, and debugging purposes.
Quoted 6 lines
Quoted 3 lines
Signed-off-by Sasha Levin <[email protected]>--- Documentation/dev-tools/kernel-api-spec.rst | 88 ++--You are removing stuff from the file you created earlier in this patch series, is that ok?
Sorry, just a rebasing artifact from shuffling patches around. I'll fix it.
Quoted 4 lines
Quoted 4 lines
kernel/api/kapi_debugfs.c new file +1
-0@@ -0,0 +1,503 @@ +// SPDX-License-Identifier: GPL-2.0
Quoted 8 lines
kernel/api/kapi_debugfs.c line 7
Quoted 6 lines
kernel/api/kapi_debugfs.c new file +6
-0+/* +* Kernel API specification debugfs interface +* +* This provides a debugfs interface to expose kernel API specifications +* at runtime, allowing tools and users to query the complete API specs. +*/ No copyright line? :)
I'll add one.
Quoted 1 line
And this is, a totally and crazy interface with debugfs, I love it!
Thanks :)
Quoted 14 lines
Two minor minor nits:
Quoted 12 lines
kernel/api/kapi_debugfs.c new file +12
-0+static int __init kapi_debugfs_init (void ) +{ +struct kernel_api_spec *spec; +struct dentry *spec_dir; + +/* Create main directory */ + kapi_debugfs_root =debugfs_create_dir ("kapi" ,NULL ); + +/* Create list file */ +debugfs_create_file ("list" ,0444 , kapi_debugfs_root,NULL , &kapi_list_fops); + +/* Create specs subdirectory */
Quoted 8 lines
kernel/api/kapi_debugfs.c line 496
Quoted 6 lines
kernel/api/kapi_debugfs.c new file +6
-0+ spec_dir =debugfs_create_dir ("specs" , kapi_debugfs_root); + +/* Create a file for each API spec */ +for (spec = __start_kapi_specs; spec < __stop_kapi_specs; spec++) { +debugfs_create_file (spec->name,0444 , spec_dir, spec, &kapi_spec_fops); + }No need for { }
ack
Quoted 5 lines
kernel/api/kapi_debugfs.c line 27
Quoted 2 lines
kernel/api/kapi_debugfs.c new file +2
-0+ +pr_info ("Kernel API debugfs interface initialized\n" );When code is working properly, it should be quiet, no need for this as initializing this can not fail.
ack
Signature · 2 lines
Thanks, Sasha
Re: [PATCH 5/9] kernel/api: add API specification for sys_open
In reply to Greg Kroah-HartmanQuoted 4 lines · Greg Kroah-Hartman
Quoted 1 line · Sasha Levin
Signed-off-by Sasha Levin <[email protected]>No changelog?
I'll add something to all patches.
Quoted 3 lines
Quoted 1 line
+ * since-version: 1.0
I think since older versions :)
Right. I guess that in my mind 1.0 was the first official "release". I'll update it to 0.01.
Quoted 2 lines
Anyway, very nice documentation, will be good to have this as part of the kerneldocs no matter what the result of this patch series is.
Thanks!
Signature · 2 lines
Thanks, Sasha
Re: [PATCH 6/9] kernel/api: add API specification for sys_close
In reply to Greg Kroah-HartmanQuoted 8 lines · Greg Kroah-Hartman
Quoted 4 lines · Sasha Levin
+ * Calling close() on a file descriptor while another thread is using it + * (e.g., in a blocking read() or write()) has implementation-defined + * behavior. On Linux, the blocked operation continues on the underlying + * file and may complete even after close() returns.I'm guessing this came from the man pages? This is Linux, so we are the "implementation" here :)
Right :)
I was just trying to make it a comparison to posix. I'll clarify the docs here.
Signature · 2 lines
Thanks, Sasha
Re: [PATCH 6/9] kernel/api: add API specification for sys_close
In reply to Greg Kroah-HartmanQuoted 9 lines · Greg Kroah-Hartman
Quoted 6 lines · Sasha Levin
+ * notes: This syscall has subtle non-POSIX semantics: the fd is ALWAYS closed
+ * regardless of the return value. POSIX specifies that on EINTR, the state + * of the fd is unspecified, but Linux always closes it. HP-UX requires + * retrying close() on EINTR, but doing so on Linux may close an unrelated + * fd that was reassigned by another thread. For portable code, the safest + * approach is to check for errors but never retry close().We don't care about HP-UX :)
Fair :) The original text was contrasting Linux's "always closed" behavior with HP-UX. I'll just drop that reference.
Quoted 5 lines
Quoted 3 lines
+ * Error codes from the flush callback (EIO, ENOSPC, EDQUOT) indicate that + * previously written data may have been lost. These errors are particularly + * common on NFS where write errors are often deferred to close time.What flush callback?
This was referring to f_op->flush, which filp_flush() calls during close.
But you're right, that's internal plumbing. I'll reworded to describe the behavior without referencing internal callbacks:
Error codes like EIO, ENOSPC, and EDQUOT indicate that previously buffered writes may have failed to reach storage.
Quoted 6 lines
Quoted 3 lines
+ *
+ * The driver'srelease()callback errors are explicitly ignored by the
+ * kernel, so device driver cleanup errors are not propagated to userspace.What "The driver" here?
release()callbacks aren't really relevant here.
The original text was noting that __fput() ignores the return value of f_op->release(), so even if a driver's cleanup fails, userspace never sees it via close(). But agreed, that's an internal implementation detail not relevant to the syscall specification. Removed.
Thanks for the review!
Signature · 2 lines
Thanks, Sasha
Quoted 4 lines · On Fri, 13 Mar 2026 11:09:10 -0400 Sasha Levin wrote:
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
Could you give some examples? We have machine readable descriptions for Netlink interfaces, we approached syzbot folks and they did not really seem to care for those.
Quoted 9 lines · On Sat, 14 Mar 2026 11:18:22 -0700 Jakub Kicinski <[email protected]> wrote:
Quoted 4 lines · On Fri, 13 Mar 2026 11:09:10 -0400 Sasha Levin wrote:
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
Could you give some examples? We have machine readable descriptions for Netlink interfaces, we approached syzbot folks and they did not really seem to care for those.
The whole thing reminds me of doxygen comment blocks. They tend to make it hard to read the source files, hard to search the source files (due to all the extra matches) and are pretty much always out of date.
The kerndoc comment blocks for trivial helper functions are hard enough to keep up to date.
The only way even parameter descriptions are going to stay correct is if the compiler is using the definition and only the comment part is extra. For error returns you'll need the documentation to be at the return site.
David
Quoted 9 lines · Jakub Kicinski
Quoted 4 lines · On Fri, 13 Mar 2026 11:09:10 -0400 Sasha Levin wrote:
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
Could you give some examples? We have machine readable descriptions for Netlink interfaces, we approached syzbot folks and they did not really seem to care for those.
Once the API is in a machine-readable format, we can write formatters to output whatever downstream tools need. The kapi tool in the series already ships with plain text, JSON, and RST formatters, and adding new output formats is straightforward. We don't need to convince the syzkaller folks to consume our specs, we can just output them in a format that syzkaller already understands.
For example, I have a syzlang formatter that produces the following from the sys_read spec in this series:
# --- read ---
# Read data from a file descriptor
#
# @context process, sleepable
#
# @capability CAP_DAC_OVERRIDE: Bypass discretionary access control on read permission
# @capability CAP_DAC_READ_SEARCH: Bypass read permission checks on regular files
#
# @error EPERM (-1): Returned by fanotify permission events...
# @error EINTR (-4): The call was interrupted by a signal before any data was read.
# @error EIO (-5): A low-level I/O error occurred.
# @error EBADF (-9): fd is not a valid file descriptor, or fd was not opened for reading. # @error EAGAIN (-11): O_NONBLOCK set and read would block.
# @error EACCES (-13): LSM denied the read operation via security_file_permission().
# @error EFAULT (-14): buf points outside the accessible address space.
# @error EISDIR (-21): fd refers to a directory.
# @error EINVAL (-22): fd not suitable for reading, O_DIRECT misaligned, count negative... # @error ENODATA (-61): Data not available in cache...
# @error EOVERFLOW (-75): File position plus count would exceed LLONG_MAX.
# @error EOPNOTSUPP (-95): Read not supported for this file type...
# @error ENOBUFS (-105): Buffer too small for complete notification...
#
# @constraint MAX_RW_COUNT: actual_count = min(count, MAX_RW_COUNT)
# @constraint File must be open for reading: (file->f_mode & FMODE_READ) && (file->f_mode & FMODE_CAN_READ) #
# @signal Any signal: restartable, error=-4
#
# @lock file->f_pos_lock (mutex, internal): For seekable files with FMODE_ATOMIC_POS
# @lock Filesystem-specific locks (rwlock, internal)
# @lock RCU read-side (rwlock, internal): File descriptor lookup protection
#
# @side-effect file->f_pos: f_pos advanced by bytes read [conditional, irreversible]
# @side-effect inode access time: atime updated unless O_NOATIME [conditional, irreversible] # @side-effect task I/O accounting: rchar and syscr updated [conditional, irreversible]
# @side-effect fsnotify events: FS_ACCESS event generated [conditional, irreversible]
#
# @return ssize_t: bytes read on success, negative errno on error
#
read(fd fd, buf ptr[out, buffer[out]], count len[buf]) intptr
That said, I don't have a strong end-to-end example with the 4 syscalls proposed here, as open/close/read/write don't take complex structures, and the subsystems underneath them aren't specced yet. The value becomes clearer with richer interfaces where the gap between "we know the type signature" and "we know the full behavioral contract" is much wider.
Signature · 2 lines
Thanks, Sasha
Quoted 18 lines · David Laight
Quoted 9 lines · On Sat, 14 Mar 2026 11:18:22 -0700 Jakub Kicinski <[email protected]> wrote:
Quoted 4 lines · On Fri, 13 Mar 2026 11:09:10 -0400 Sasha Levin wrote:
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
Could you give some examples? We have machine readable descriptions for Netlink interfaces, we approached syzbot folks and they did not really seem to care for those.
The whole thing reminds me of doxygen comment blocks. They tend to make it hard to read the source files, hard to search the source files (due to all the extra matches) and are pretty much always out of date.
Quoted 6 lines
The kerndoc comment blocks for trivial helper functions are hard enough to keep up to date.
The only way even parameter descriptions are going to stay correct is if the compiler is using the definition and only the comment part is extra. For error returns you'll need the documentation to be at the return site.
When CONFIG_KAPI_RUNTIME_CHECKS is enabled, the specs are enforced at the syscall boundary. The SYSCALL_DEFINEx macro grows a wrapper that calls kapi_validate_syscall_params() before the real implementation and kapi_validate_syscall_return() after it. Parameter constraints (ranges, valid flag masks, alignment) are checked on every syscall entry, and return values are validated against the documented success/error ranges on every exit.
If a spec goes stale, it has runtime consequences. A new flag bit added without updating the spec's valid_mask means callers using that flag get EINVAL, which any test exercising that path catches immediately. An implementation returning an undocumented error code triggers a warning from the return validation.
The selftest in the series (tools/testing/selftests/kapi/test_kapi.c) exercises this with real syscalls, both valid and invalid inputs, verifying the validation layer catches violations.
Signature · 2 lines
Thanks, Sasha
Quoted 10 lines · Jakub Kicinski
Quoted 4 lines · On Fri, 13 Mar 2026 11:09:10 -0400 Sasha Levin wrote:
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
Could you give some examples? We have machine readable descriptions for Netlink interfaces, we approached syzbot folks and they did not really seem to care for those.
I think our reasoning wrt syzkaller was that not all interfaces in all relevant kernels are described with netlink yml descriptions, so we need to continue using the extraction of interfaces from the source code. And if we have that code, then using yml as an additional data source only adds code/complexity. Additionally, we may extract some extra constraints/info from code that are not present in yml.
Realistically system call descriptions may have the same problem for us at this point, since we extract lots of info from the source code already:
https://raw.githubusercontent.com/google/syzkaller/refs/heads/master/sys/linux/auto.txt
(and LLMs obviously can allow us to extract more)
Quoted 18 lines · On Mon, 16 Mar 2026 08:05:53 +0100 Dmitry Vyukov wrote:
Quoted 9 lines · Jakub Kicinski
Quoted 4 lines · On Fri, 13 Mar 2026 11:09:10 -0400 Sasha Levin wrote:
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
Could you give some examples? We have machine readable descriptions for Netlink interfaces, we approached syzbot folks and they did not really seem to care for those.
I think our reasoning wrt syzkaller was that not all interfaces in all relevant kernels are described with netlink yml descriptions, so we need to continue using the extraction of interfaces from the source code. And if we have that code, then using yml as an additional data source only adds code/complexity. Additionally, we may extract some extra constraints/info from code that are not present in yml.
Quoted 4 lines
Realistically system call descriptions may have the same problem for us at this point, since we extract lots of info from the source code already:
https://raw.githubusercontent.com/google/syzkaller/refs/heads/master/sys/linux/auto.txt
yup! we haven't tried to make the yml spec super useful to syzbot to be fair. I'm just flagging that example because in our case we quickly went from "this will obviously be useful to syzbot" to "although we could, it may not be super practical"
Quoted 1 line
(and LLMs obviously can allow us to extract more)
Didn't even think of that. LLMs should make short work of this sort of extraction of information from source code..
Quoted 2 lines · Jakub Kicinski
Didn't even think of that. LLMs should make short work of this sort of extraction of information from source code..
This is the primary reason that this proposal resurfaced :)
I've originally proposed[1] something like this almost a decade ago, but when I started trying to write the actual specs I hit a brick wall: it was simply not tractable.
With LLMs, writing the specs is something we can actually pull off, and we can verify their correctness so LLMs don't get to hallucinate.
The specs you see in the following patches are all LLM generated.
Signature · 2 lines
Thanks, Sasha
Jonathan Corbet
maintainerRe: [PATCH 1/9] kernel/api: introduce kernel API specification framework
In reply to Sasha LevinQuoted 8 lines · Sasha Levin
Add a 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
So I'll confess I have only scanned over the implementation, but I have some thoughts on the earlier stuff.
[...]
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +0
-0
Documentation/dev-tools/kernel-api-spec.rst line 8
Quoted 8 lines
Documentation/dev-tools/kernel-api-spec.rst new file +8
-0@@ -0,0 +1,482 @@ +.. SPDX-License-Identifier: GPL-2.0 + +====================================== +Kernel API Specification Framework +====================================== + +:Author: Sasha Levin <[email protected]> +:Date: June 2025
Has it not changed since then?
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+.. contents:: Table of Contents + :depth: 3 + :local: + +Introduction +============
[...]
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+Usage Guide +=========== + +Basic API Specification +----------------------- +
Documentation/dev-tools/kernel-api-spec.rst line 131
Quoted 10 lines
Documentation/dev-tools/kernel-api-spec.rst new file +10
-0+API specifications are written as KAPI-annotated kerneldoc comments directly in +the source file, immediately preceding the function implementation. The ``kapi`` +tool extracts these annotations to produce structured specifications. + +.. code-block:: c + + /** + * kmalloc - allocate kernel memory + * @size: Number of bytes to allocate + * @flags: Allocation flags (GFP_*)
Given that the text thus far has talked about user-space API validation, it's a bit surprising to see an internal function used as an example.
Also, maybe it should be kmalloc_obj()? <runs away>
Documentation/dev-tools/kernel-api-spec.rst line 134
Quoted 2 lines
Documentation/dev-tools/kernel-api-spec.rst new file +2
-0+ * context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SOFTIRQ | KAPI_CTX_HARDIRQ + * param-count: 2
param-count is two, but you only document one of them?
Documentation/dev-tools/kernel-api-spec.rst line 144
Quoted 9 lines
Documentation/dev-tools/kernel-api-spec.rst new file +9
-0+ * param: size + * type: KAPI_TYPE_UINT + * flags: KAPI_PARAM_IN + * constraint-type: KAPI_CONSTRAINT_RANGE + * range: 0, KMALLOC_MAX_SIZE + * + * error: ENOMEM, Out of memory + * desc: Insufficient memory available for the requested allocation. + */
Honest question: can this be made a bit easier for people to create, with less shift-key wear? My biggest worry with a system like this is that people won't take the time to create and maintain the entries, so anything that would ease the task would help. Is there an impediment to something like:
contexts: process, softirq, hardirq
param: size
type: uint, input
constraint: range(0, KMALLOC_MAX_SIZE)
See what I'm getting at? ISTM that your DSL could be made a bit less verbose and shouty while being just as well defined, but perhaps I'm missing something?
Even better, of course, would be to add a "description" field for each parameter, and allow that rather than the @param description that kerneldoc currently uses. That would keep all the information together, at the minor cost of adding another significant complication to the kernel-doc script. Mauro won't mind :)
Quoted 7 lines
Documentation/dev-tools/kernel-api-spec.rst new file +7
-0+ void *kmalloc(size_t size, gfp_t flags) + { + /* Implementation */ + } + +Alternatively, specifications can be defined using the ``DEFINE_KERNEL_API_SPEC`` +macro for compiled-in specs that are stored in the ``.kapi_specs`` ELF section:
Documentation/dev-tools/kernel-api-spec.rst line 161
Quoted 10 lines
Documentation/dev-tools/kernel-api-spec.rst new file +10
-0+ +.. code-block:: c + + #include <linux/kernel_api_spec.h> + + DEFINE_KERNEL_API_SPEC(sys_open) + KAPI_DESCRIPTION("Open or create a file") + KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) + /* ... parameter, error, constraint definitions ... */ + KAPI_END_SPEC
So the reason for two completely separate mechanisms is not entirely clear to me. The kerneldoc variant is essentially documentation, while the macro stuff is to be built into the executable? What if you want both?
It would be nice to only have one way if at all possible; I'm sure that crossed your mind at some point :) If there have to be two, having both examples describe the same function would make the parallels more clear.
Documentation/dev-tools/kernel-api-spec.rst line 175
Quoted 13 lines
Documentation/dev-tools/kernel-api-spec.rst new file +13
-0+System Call Specification +------------------------- + +System calls are documented inline in the implementation file (e.g., ``fs/open.c``) +using KAPI-annotated kerneldoc comments. When ``CONFIG_KAPI_RUNTIME_CHECKS`` is +enabled, the ``SYSCALL_DEFINEx`` macros automatically look up the specification +and validate parameters before and after the syscall executes. + +IOCTL Specification +------------------- + +IOCTLs use the same annotation approach with additional structure field +specifications
This might be a really good place for an example
[...]
Quoted 5 lines
Documentation/dev-tools/kernel-api-spec.rst new file +5
-0+Usage Examples +-------------- + +Query specific API:: +
Documentation/dev-tools/kernel-api-spec.rst line 258
Quoted 10 lines
Documentation/dev-tools/kernel-api-spec.rst new file +10
-0+ $ 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
Ah, you do document that second parameter somewhere :)
Documentation/dev-tools/kernel-api-spec.rst line 268
Quoted 9 lines
Documentation/dev-tools/kernel-api-spec.rst new file +9
-0+ Returns: pointer - Pointer to allocated memory or NULL + + Errors: + ENOMEM: Out of memory + + Context: process, softirq, hardirq + + Side Effects: + - Allocates memory from kernel heap
That part wasn't in your example
Quoted 7 lines
Documentation/dev-tools/kernel-api-spec.rst new file +7
-0+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
Documentation/dev-tools/kernel-api-spec.rst line 286
Quoted 10 lines
Documentation/dev-tools/kernel-api-spec.rst new file +10
-0+ +Performance Considerations +========================== + +Memory Overhead +--------------- + +Each API specification consumes approximately 400-450KB of memory due to the +fixed-size arrays in ``struct kernel_api_spec``. With the current 4 syscall +specifications, total memory usage is approximately 1.7MB. Consider:
Ouch.
Documentation/dev-tools/kernel-api-spec.rst line 318
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+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.
Documentation always comes last :)
Interesting stuff.
jon
Jonathan Corbet
maintainerRe: [PATCH 5/9] kernel/api: add API specification for sys_open
In reply to Sasha LevinQuoted 9 lines · Sasha Levin
Quoted 5 lines · Greg Kroah-Hartman
Quoted 1 line · Sasha Levin
+ * since-version: 1.0
I think since older versions :)
Right. I guess that in my mind 1.0 was the first official "release". I'll update it to 0.01.
That kind of raises the question of just what since-version means. The version-0.01 (or 1.0) version of open() surely didn't do everything described in this specification. So it's saying that some version of the system call has existed since then?
Thanks,
jon
Re: [PATCH 1/9] kernel/api: introduce kernel API specification framework
In reply to Jonathan CorbetQuoted 95 lines · On Tue, 17 Mar 2026 11:49:27 -0600 Jonathan Corbet <[email protected]> wrote:
Quoted 8 lines · Sasha Levin
Add a 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 callsSo I'll confess I have only scanned over the implementation, but I have some thoughts on the earlier stuff.
[...]
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +0
-0Documentation/dev-tools/kernel-api-spec.rst line 8
Quoted 8 lines
Documentation/dev-tools/kernel-api-spec.rst new file +8
-0@@ -0,0 +1,482 @@ +.. SPDX-License-Identifier: GPL-2.0 + +====================================== +Kernel API Specification Framework +====================================== + +:Author: Sasha Levin <[email protected]> +:Date: June 2025Has it not changed since then?
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+.. contents:: Table of Contents + :depth: 3 + :local: + +Introduction +============[...]
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+Usage Guide +=========== + +Basic API Specification +----------------------- +Documentation/dev-tools/kernel-api-spec.rst line 131
Quoted 10 lines
Documentation/dev-tools/kernel-api-spec.rst new file +10
-0+API specifications are written as KAPI-annotated kerneldoc comments directly in +the source file, immediately preceding the function implementation. The ``kapi`` +tool extracts these annotations to produce structured specifications. + +.. code-block:: c + + /** + * kmalloc - allocate kernel memory + * @size: Number of bytes to allocate + * @flags: Allocation flags (GFP_*)Given that the text thus far has talked about user-space API validation, it's a bit surprising to see an internal function used as an example.
Also, maybe it should be
kmalloc_obj()? <runs away>Documentation/dev-tools/kernel-api-spec.rst line 134
Quoted 2 lines
Documentation/dev-tools/kernel-api-spec.rst new file +2
-0+ * context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SOFTIRQ | KAPI_CTX_HARDIRQ + * param-count: 2param-count is two, but you only document one of them?
Documentation/dev-tools/kernel-api-spec.rst line 144
Quoted 9 lines
Documentation/dev-tools/kernel-api-spec.rst new file +9
-0+ * param: size + * type: KAPI_TYPE_UINT + * flags: KAPI_PARAM_IN + * constraint-type: KAPI_CONSTRAINT_RANGE + * range: 0, KMALLOC_MAX_SIZE + * + * error: ENOMEM, Out of memory + * desc: Insufficient memory available for the requested allocation. + */Honest question: can this be made a bit easier for people to create, with less shift-key wear? My biggest worry with a system like this is that people won't take the time to create and maintain the entries, so anything that would ease the task would help. Is there an impediment to something like:
contexts: process, softirq, hardirq
param: size
type: uint, input
constraint:range(0, KMALLOC_MAX_SIZE)See what I'm getting at? ISTM that your DSL could be made a bit less verbose and shouty while being just as well defined, but perhaps I'm missing something?
Quoted 5 lines
Even better, of course, would be to add a "description" field for each parameter, and allow that rather than the @param description that kerneldoc currently uses. That would keep all the information together, at the minor cost of adding another significant complication to the kernel-doc script. Mauro won't mind :)
No, I won't ;-)
It sounds a lot better to use kernel-doc also for kAPI than to have an independent tool.
It is also very confusing if we end with a kernel-doc-like format that it is not parsed by kernel-doc.
Quoted 15 lines
Quoted 15 lines
Documentation/dev-tools/kernel-api-spec.rst new file +14
-0+ void *kmalloc(size_t size, gfp_t flags) + { + /* Implementation */ + } + +Alternatively, specifications can be defined using the ``DEFINE_KERNEL_API_SPEC`` +macro for compiled-in specs that are stored in the ``.kapi_specs`` ELF section: + +.. code-block:: c + + #include <linux/kernel_api_spec.h> + + DEFINE_KERNEL_API_SPEC(sys_open) + KAPI_DESCRIPTION("Open or create a file")
Quoted 8 lines
Documentation/dev-tools/kernel-api-spec.rst line 161
Quoted 3 lines
Documentation/dev-tools/kernel-api-spec.rst new file +3
-0+ KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) + /* ... parameter, error, constraint definitions ... */ + KAPI_END_SPECSo the reason for two completely separate mechanisms is not entirely clear to me. The kerneldoc variant is essentially documentation, while the macro stuff is to be built into the executable? What if you want both?
You can easily add support at kernel-doc to output such macros.
All you need is to create a new class derived from OutputFormat and make it produce any different output format, including:
#include <linux/kernel_api_spec.h>
DEFINE_KERNEL_API_SPEC(sys_open) KAPI_DESCRIPTION("Open or create a file") KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) /* ... parameter, error, constraint definitions ... */ KAPI_END_SPEC
I'd say that converting from such output to `.kapi_specs`` ELF section itself and/or to sysfs/debugfs - e.g. something that would require to compile or be linked with Kernel's compiled binaries should be done by a separate tool, but we should aim to have a singe tool to process kernel documentation markups.
It is hard enough to maintain just one tool - and to have people actually writing documentation. Having a second one to handle it, with a different format will likely increase a lot the documentation burden.
Quoted 81 lines
It would be nice to only have one way if at all possible; I'm sure that crossed your mind at some point :) If there have to be two, having both examples describe the same function would make the parallels more clear.
Documentation/dev-tools/kernel-api-spec.rst line 175
Quoted 13 lines
Documentation/dev-tools/kernel-api-spec.rst new file +13
-0+System Call Specification +------------------------- + +System calls are documented inline in the implementation file (e.g., ``fs/open.c``) +using KAPI-annotated kerneldoc comments. When ``CONFIG_KAPI_RUNTIME_CHECKS`` is +enabled, the ``SYSCALL_DEFINEx`` macros automatically look up the specification +and validate parameters before and after the syscall executes. + +IOCTL Specification +------------------- + +IOCTLs use the same annotation approach with additional structure field +specificationsThis might be a really good place for an example
[...]
Quoted 5 lines
Documentation/dev-tools/kernel-api-spec.rst new file +5
-0+Usage Examples +-------------- + +Query specific API:: +Documentation/dev-tools/kernel-api-spec.rst line 258
Quoted 10 lines
Documentation/dev-tools/kernel-api-spec.rst new file +10
-0+ $ 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: 0x1ffffffAh, you do document that second parameter somewhere :)
Documentation/dev-tools/kernel-api-spec.rst line 268
Quoted 9 lines
Documentation/dev-tools/kernel-api-spec.rst new file +9
-0+ Returns: pointer - Pointer to allocated memory or NULL + + Errors: + ENOMEM: Out of memory + + Context: process, softirq, hardirq + + Side Effects: + - Allocates memory from kernel heapThat part wasn't in your example
Quoted 7 lines
Documentation/dev-tools/kernel-api-spec.rst new file +7
-0+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/validateDocumentation/dev-tools/kernel-api-spec.rst line 286
Quoted 10 lines
Documentation/dev-tools/kernel-api-spec.rst new file +10
-0+ +Performance Considerations +========================== + +Memory Overhead +--------------- + +Each API specification consumes approximately 400-450KB of memory due to the +fixed-size arrays in ``struct kernel_api_spec``. With the current 4 syscall +specifications, total memory usage is approximately 1.7MB. Consider:Ouch.
Documentation/dev-tools/kernel-api-spec.rst line 318
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+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.Documentation always comes last :)
Quoted 3 lines
Interesting stuff.
jon
Thanks,
Mauro
Quoted 7 lines · On Sun, 15 Mar 2026 02:36:51 -0400 Sasha Levin <[email protected]> wrote:
Quoted 6 lines · Jakub Kicinski
Quoted 4 lines · On Fri, 13 Mar 2026 11:09:10 -0400 Sasha Levin wrote:
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
Quoted 6 lines
Quoted 3 lines
Could you give some examples? We have machine readable descriptions for Netlink interfaces, we approached syzbot folks and they did not really seem to care for those.
Once the API is in a machine-readable format, we can write formatters to output whatever downstream tools need.
Kernel-doc already does that. The way it works is that it handles kernel-doc markups on two steps:
- first step: parse kernel-doc markups, function prototypes and data types for variables, typedefs, structs, unions, enums.
This is done inside tools/lib/python/kdoc/kdoc_parser.py.
The documentation is stored in memory as a list of documentation entries. Each element there belongs to class KdocItem.
It is trivial to output its content in JSON or YAML format. I submitted a path series a while ago doing exactly that, aiming to help writing unittests for first step:
https://lore.kernel.org/linux-doc/7648cb5f5a1b501d9ae9a57b4d8dbeb7273d9097.1770128540.git.mchehab+huawei@kernel.org/
I'm planing to rebase such patch series on the top of my latest kernel-doc patch series.
- second step: output generation. There is an abstract class named OutputFormat which contains the following output methods:
def out_doc(self, fname, name, args):
"""Outputs a DOC block."""
def out_function(self, fname, name, args):
"""Outputs a function."""
def out_enum(self, fname, name, args):
"""Outputs an enum."""
def out_var(self, fname, name, args):
"""Outputs a variable."""
def out_typedef(self, fname, name, args):
"""Outputs a typedef."""
def out_struct(self, fname, name, args):
"""Outputs a struct."""
Producing a different output is as easy as doing:
class MyFormat(OutputFormat):
...
def out_var(self, fname, name, args):
self.data =+ f"whatever {name}"
...Thanks,
Mauro
Re: [PATCH 5/9] kernel/api: add API specification for sys_open
In reply to Jonathan CorbetQuoted 9 lines · Jonathan Corbet
Quoted 7 lines · Sasha Levin
Quoted 5 lines · Greg Kroah-Hartman
Quoted 1 line · Sasha Levin
+ * since-version: 1.0
I think since older versions :)
Quoted 7 lines
Quoted 2 lines
Right. I guess that in my mind 1.0 was the first official "release". I'll update it to 0.01.
That kind of raises the question of just what since-version means. The version-0.01 (or 1.0) version of
open()surely didn't do everything described in this specification. So it's saying that some version of the system call has existed since then?
You know, I'm not entierly sure what the definition should be here.
I stole this from man pages where they indicate at which version the API was introduced in. I'm not sure if it really adds any value.
Any objections to just dropping it?
Signature · 2 lines
Thanks, Sasha
Quoted 14 lines · Mauro Carvalho Chehab
Quoted 11 lines · On Sun, 15 Mar 2026 02:36:51 -0400 Sasha Levin <[email protected]> wrote:
Quoted 9 lines · Jakub Kicinski
Quoted 4 lines · On Fri, 13 Mar 2026 11:09:10 -0400 Sasha Levin wrote:
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
Could you give some examples? We have machine readable descriptions for Netlink interfaces, we approached syzbot folks and they did not really seem to care for those.
Quoted 5 lines
Quoted 2 lines
Once the API is in a machine-readable format, we can write formatters to output whatever downstream tools need.
Kernel-doc already does that. The way it works is that it handles kernel-doc markups on two steps:
Cool, I'll take a look. We could throw away the source parser in the kapi tool and just use the kerneldoc parse.
Signature · 2 lines
Thanks, Sasha
Jonathan Corbet
maintainerRe: [PATCH 5/9] kernel/api: add API specification for sys_open
In reply to Sasha LevinQuoted 18 lines · Sasha Levin
Quoted 9 lines · Jonathan Corbet
Quoted 7 lines · Sasha Levin
Quoted 5 lines · Greg Kroah-Hartman
Quoted 1 line · Sasha Levin
+ * since-version: 1.0
I think since older versions :)
Quoted 7 lines
Quoted 2 lines
Right. I guess that in my mind 1.0 was the first official "release". I'll update it to 0.01.
That kind of raises the question of just what since-version means. The version-0.01 (or 1.0) version of
open()surely didn't do everything described in this specification. So it's saying that some version of the system call has existed since then?
Quoted 6 lines
You know, I'm not entierly sure what the definition should be here.
I stole this from man pages where they indicate at which version the API was introduced in. I'm not sure if it really adds any value.
Any objections to just dropping it?
Not here. My general objective with the docs is to describe the kernel as it is now, without that sort of history unless there's something specific it can tell current users.
Thanks,
jon
Re: [PATCH 1/9] kernel/api: introduce kernel API specification framework
In reply to Jonathan CorbetQuoted 53 lines · Jonathan Corbet
Quoted 8 lines · Sasha Levin
Add a 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 callsSo I'll confess I have only scanned over the implementation, but I have some thoughts on the earlier stuff.
[...]
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +0
-0Documentation/dev-tools/kernel-api-spec.rst line 8
Quoted 8 lines
Documentation/dev-tools/kernel-api-spec.rst new file +8
-0@@ -0,0 +1,482 @@ +.. SPDX-License-Identifier: GPL-2.0 + +====================================== +Kernel API Specification Framework +====================================== + +:Author: Sasha Levin <[email protected]> +:Date: June 2025Has it not changed since then?
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+.. contents:: Table of Contents + :depth: 3 + :local: + +Introduction +============[...]
Quoted 11 lines
Documentation/dev-tools/kernel-api-spec.rst new file +11
-0+Usage Guide +=========== + +Basic API Specification +----------------------- + +API specifications are written as KAPI-annotated kerneldoc comments directly in +the source file, immediately preceding the function implementation. The ``kapi`` +tool extracts these annotations to produce structured specifications. + +.. code-block:: c
Quoted 8 lines
Documentation/dev-tools/kernel-api-spec.rst line 131
Quoted 5 lines
Documentation/dev-tools/kernel-api-spec.rst new file +5
-0+ + /** + * kmalloc - allocate kernel memory + * @size: Number of bytes to allocate + * @flags: Allocation flags (GFP_*)Given that the text thus far has talked about user-space API validation, it's a bit surprising to see an internal function used as an example.
Indeed :)
I was playing with adding specs to lower level functions as a way to both simplify the higher level spec blocks, but also to help validate the correctness of those upper level specs ("you said that this syscall doesn't allocate memory, but it's calling kmalloc()!").
Quoted 17 lines
Also, maybe it should be
kmalloc_obj()? <runs away>Documentation/dev-tools/kernel-api-spec.rst line 134
Quoted 2 lines
Documentation/dev-tools/kernel-api-spec.rst new file +2
-0+ * context-flags: KAPI_CTX_PROCESS | KAPI_CTX_SOFTIRQ | KAPI_CTX_HARDIRQ + * param-count: 2param-count is two, but you only document one of them?
Documentation/dev-tools/kernel-api-spec.rst line 144
Quoted 9 lines
Documentation/dev-tools/kernel-api-spec.rst new file +9
-0+ * param: size + * type: KAPI_TYPE_UINT + * flags: KAPI_PARAM_IN + * constraint-type: KAPI_CONSTRAINT_RANGE + * range: 0, KMALLOC_MAX_SIZE + * + * error: ENOMEM, Out of memory + * desc: Insufficient memory available for the requested allocation. + */
Quoted 5 lines
Honest question: can this be made a bit easier for people to create, with less shift-key wear? My biggest worry with a system like this is that people won't take the time to create and maintain the entries, so anything that would ease the task would help. Is there an impediment to something like:
Before answering your actual question, I honestly think that most of these will be LLM generated, so at least the skeleton of the kernel-doc will be there and humans will only end up modifying the proposed spec.
Quoted 9 lines
contexts: process, softirq, hardirq
param: size
type: uint, input
constraint:range(0, KMALLOC_MAX_SIZE)See what I'm getting at? ISTM that your DSL could be made a bit less verbose and shouty while being just as well defined, but perhaps I'm missing something?
Yup, let me look into that.
Quoted 29 lines
Even better, of course, would be to add a "description" field for each parameter, and allow that rather than the @param description that kerneldoc currently uses. That would keep all the information together, at the minor cost of adding another significant complication to the kernel-doc script. Mauro won't mind :)
Quoted 7 lines
Documentation/dev-tools/kernel-api-spec.rst new file +7
-0+ void *kmalloc(size_t size, gfp_t flags) + { + /* Implementation */ + } + +Alternatively, specifications can be defined using the ``DEFINE_KERNEL_API_SPEC`` +macro for compiled-in specs that are stored in the ``.kapi_specs`` ELF section:Documentation/dev-tools/kernel-api-spec.rst line 161
Quoted 10 lines
Documentation/dev-tools/kernel-api-spec.rst new file +10
-0+ +.. code-block:: c + + #include <linux/kernel_api_spec.h> + + DEFINE_KERNEL_API_SPEC(sys_open) + KAPI_DESCRIPTION("Open or create a file") + KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE) + /* ... parameter, error, constraint definitions ... */ + KAPI_END_SPECSo the reason for two completely separate mechanisms is not entirely clear to me. The kerneldoc variant is essentially documentation, while the macro stuff is to be built into the executable? What if you want both?
Quoted 3 lines
It would be nice to only have one way if at all possible; I'm sure that crossed your mind at some point :) If there have to be two, having both examples describe the same function would make the parallels more clear.
Under the hood, the
Quoted 7 lines
Quoted 7 lines
Documentation/dev-tools/kernel-api-spec.rst new file +7
-0+System Call Specification +------------------------- + +System calls are documented inline in the implementation file (e.g., ``fs/open.c``) +using KAPI-annotated kerneldoc comments. When ``CONFIG_KAPI_RUNTIME_CHECKS`` is +enabled, the ``SYSCALL_DEFINEx`` macros automatically look up the specification +and validate parameters before and after the syscall executes.
Quoted 8 lines
Documentation/dev-tools/kernel-api-spec.rst line 175
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+ +IOCTL Specification +------------------- + +IOCTLs use the same annotation approach with additional structure field +specificationsThis might be a really good place for an example
I think I'll just drop the IOCTL code for now. I used it in the RFCs to demonstrate how a similar mechanism could be used throughout different userspace API, but since I'm not using it in this series it probably makes sense not to even talk about it.
Quoted 11 lines
[...]
Quoted 9 lines
Documentation/dev-tools/kernel-api-spec.rst new file +9
-0+Usage Examples +-------------- + +Query specific API:: + + $ cat /sys/kernel/debug/kapi/apis/kmalloc/specification + API: kmalloc + Version: 3.0 + Description: Allocate kernel memory
Quoted 8 lines
Documentation/dev-tools/kernel-api-spec.rst line 258
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+ + Parameters: + [0] size (size_t, in): Number of bytes to allocate + Range: 0 - 4194304 + [1] flags (flags, in): Allocation flags (GFP_*) + Mask: 0x1ffffffAh, you do document that second parameter somewhere :)
Apparently. I'll update the prior example. Not sure why it's missing :)
Quoted 23 lines
Documentation/dev-tools/kernel-api-spec.rst line 268
Quoted 9 lines
Documentation/dev-tools/kernel-api-spec.rst new file +9
-0+ Returns: pointer - Pointer to allocated memory or NULL + + Errors: + ENOMEM: Out of memory + + Context: process, softirq, hardirq + + Side Effects: + - Allocates memory from kernel heapThat part wasn't in your example
Quoted 11 lines
Documentation/dev-tools/kernel-api-spec.rst new file +11
-0+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 +========================== +
Quoted 8 lines
Documentation/dev-tools/kernel-api-spec.rst line 286
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+Memory Overhead +--------------- + +Each API specification consumes approximately 400-450KB of memory due to the +fixed-size arrays in ``struct kernel_api_spec``. With the current 4 syscall +specifications, total memory usage is approximately 1.7MB. Consider:Ouch.
It's pretty "dumb" at this point: large static arrays and such, mostly to keep the code simple to read. If this is a concern for accepting this series, I'm happy to shrink it down (by a lot).
Quoted 8 lines
Documentation/dev-tools/kernel-api-spec.rst line 318
Quoted 6 lines
Documentation/dev-tools/kernel-api-spec.rst new file +6
-0+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.Documentation always comes last :)
So this is one thing I wanted to run by the doc maintainers: the kapi tool already has the capability to export these specs in .rst format. Would it be interesting to have a manual for kenrel APIs in Documentation/? It can be automatically generated and updated and would always match the kernel code at that point.
Quoted 1 line
Interesting stuff.
Thanks!
Signature · 2 lines
Thanks, Sasha
Re: [PATCH 1/9] kernel/api: introduce kernel API specification framework
In reply to Jonathan CorbetQuoted 8 lines · Jonathan Corbet
So the reason for two completely separate mechanisms is not entirely clear to me. The kerneldoc variant is essentially documentation, while the macro stuff is to be built into the executable? What if you want both?
It would be nice to only have one way if at all possible; I'm sure that crossed your mind at some point :) If there have to be two, having both examples describe the same function would make the parallels more clear.
Woops, I forgot to finish writing my reply to this :)
Under the hood, kerneldoc specs are translated into those macros so they could be part of the build process and embedded into the resulting binary (both for documentation as well as the runtime validation).
I don't think anyone would use the macro format directly, but as it's there anyway I figured I'd offer it as an option. Would it make sense to just hide it behind the scenes?
Signature · 2 lines
Thanks, Sasha
Re: [PATCH 1/9] kernel/api: introduce kernel API specification framework
In reply to Mauro Carvalho ChehabQuoted 26 lines · Mauro Carvalho Chehab
Quoted 4 lines · On Tue, 17 Mar 2026 11:49:27 -0600 Jonathan Corbet <[email protected]> wrote:
So the reason for two completely separate mechanisms is not entirely clear to me. The kerneldoc variant is essentially documentation, while the macro stuff is to be built into the executable? What if you want both?
You can easily add support at kernel-doc to output such macros.
All you need is to create a new class derived from OutputFormat and make it produce any different output format, including:
#include <linux/kernel_api_spec.h>
DEFINE_KERNEL_API_SPEC(sys_open)KAPI_DESCRIPTION("Open or create a file")KAPI_CONTEXT(KAPI_CTX_PROCESS | KAPI_CTX_SLEEPABLE)/* ... parameter, error, constraint definitions ... */KAPI_END_SPECI'd say that converting from such output to `.kapi_specs`` ELF section itself and/or to sysfs/debugfs - e.g. something that would require to compile or be linked with Kernel's compiled binaries should be done by a separate tool, but we should aim to have a singe tool to process kernel documentation markups.
Quoted 3 lines
It is hard enough to maintain just one tool - and to have people actually writing documentation. Having a second one to handle it, with a different format will likely increase a lot the documentation burden.
So this is exactly what happens under the hood :) kerneldoc outputs these macros and they get compiled ito the binary.
I exposed the macros as an option since they're there anyway, but I'm happy to hide them as internal plumbing too.
Signature · 2 lines
Thanks, Sasha
Jonathan Corbet
maintainerRe: [PATCH 1/9] kernel/api: introduce kernel API specification framework
In reply to Sasha LevinQuoted 11 lines · Sasha Levin
Quoted 5 lines
Documentation/dev-tools/kernel-api-spec.rst line 318
Quoted 3 lines
Documentation/dev-tools/kernel-api-spec.rst new file +3
-0+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.Documentation always comes last :)
So this is one thing I wanted to run by the doc maintainers: the kapi tool already has the capability to export these specs in .rst format. Would it be interesting to have a manual for kenrel APIs in
Documentation/? It can be automatically generated and updated and would always match the kernel code at that point.
I suspect we could certainly find a place for it. Maybe as a subsection of the user-space API manual, at least for the system-call portion of it.
Thanks,
jon
Jonathan Corbet
maintainerRe: [PATCH 1/9] kernel/api: introduce kernel API specification framework
In reply to Sasha LevinQuoted 12 lines · Sasha Levin
Quoted 8 lines · Jonathan Corbet
So the reason for two completely separate mechanisms is not entirely clear to me. The kerneldoc variant is essentially documentation, while the macro stuff is to be built into the executable? What if you want both?
It would be nice to only have one way if at all possible; I'm sure that crossed your mind at some point :) If there have to be two, having both examples describe the same function would make the parallels more clear.
Woops, I forgot to finish writing my reply to this :)
Quoted 7 lines
Under the hood, kerneldoc specs are translated into those macros so they could be part of the build process and embedded into the resulting binary (both for documentation as well as the runtime validation).
I don't think anyone would use the macro format directly, but as it's there anyway I figured I'd offer it as an option. Would it make sense to just hide it behind the scenes?
If there are two ways of doing it, people will use both ways. My kneejerk reaction would be to hide the macros as an implementation detail, but perhaps that's just me.
Thanks,
jon
Hi Sasha,
Quoted 34 lines · Sasha Levin
Quoted 9 lines · Jakub Kicinski
Quoted 4 lines · On Fri, 13 Mar 2026 11:09:10 -0400 Sasha Levin wrote:
This enables static analysis tools to verify userspace API usage at compile time, test generation based on formal specifications, consistent error handling validation, automated documentation generation, and formal verification of kernel interfaces.
Could you give some examples? We have machine readable descriptions for Netlink interfaces, we approached syzbot folks and they did not really seem to care for those.
Once the API is in a machine-readable format, we can write formatters to output whatever downstream tools need. The kapi tool in the series already ships with plain text, JSON, and RST formatters, and adding new output formats is straightforward. We don't need to convince the syzkaller folks to consume our specs, we can just output them in a format that syzkaller already understands.
For example, I have a syzlang formatter that produces the following from the
sys_readspec in this series:# --- read ---
# Read data from a file descriptor
#
# @context process, sleepable
#
# @capabilityCAP_DAC_OVERRIDE: Bypass discretionary access control on read permission # @capabilityCAP_DAC_READ_SEARCH: Bypass read permission checks on regular files #
# @error EPERM (-1): Returned by fanotify permission events...
# @error EINTR (-4): The call was interrupted by a signal before any data was read. # @error EIO (-5): A low-level I/O error occurred.
# @error EBADF (-9): fd is not a valid file descriptor, or fd was not opened for reading. # @error EAGAIN (-11):O_NONBLOCKset and read would block.
Quoted 8 lines
# @error EACCES (-13): LSM denied the read operation via
security_file_permission(). # @error EFAULT (-14): buf points outside the accessible address space.
# @error EISDIR (-21): fd refers to a directory.
# @error EINVAL (-22): fd not suitable for reading,O_DIRECTmisaligned, count negative... # @error ENODATA (-61): Data not available in cache...
# @error EOVERFLOW (-75): File position plus count would exceedLLONG_MAX. # @error EOPNOTSUPP (-95): Read not supported for this file type...
# @error ENOBUFS (-105): Buffer too small for complete notification...
The actual E-values are positive, so I guess you want e.g. -EPERM?
Note that the actual errno values are architecture-specific. E.g. EOPNOTSUPP can be 45, 95, 122, or 223.
Gr{oetje,eeting}s,
Geert
Signature · 5 lines
Geert Uytterhoeven -- There's lots of Linux beyond ia32 -- [email protected] In personal conversations with technical people, I call myself a hacker. But when I'm talking to journalists I just say "programmer" or something like that. -- Linus Torvalds