Skip to contentSkip to conversation

Kernel API Specification Framework

PATCH In review Sasha Levin 4 participants 21 messages Oct 8

Subsystems (12)
lore
Share & tools
lore
#0 lore raw

v5 cover Kernel API Specification Framework

This series adds machinery for documenting kernel APIs in a machine-readable form. The kernel promises not to break user space, but the contract of each interface is written down only as prose in man pages and comments, which tools cannot check.

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.

The intent is for static analyzers, test generators and documentation tools to consume these specifications. This series adds the framework, the extraction tool, and specifications for five syscalls.

The implementation includes a core framework with ELF section storage, kerneldoc integration for inline specification, a debugfs interface for runtime querying, ftrace tracepoints that report each spec'd syscall's parameters and return value, 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) and for sys_madvise. The series also includes a KUnit test suite with 33 tests and a runtime verification selftest with 31 TAP tests.

The series is also available in the "spec" branch of:

https://git.kernel.org/pub/scm/linux/kernel/git/sashal/kapi.git

Changes since v4:

- Rebase onto v7.3-rc6: the sys_open spec accepts O_EMPTYPATH, the madvise spec follows the zap_vma_range() rename, and tools/kapi declares Rust 1.85 to match the kernel minimum.

- CONFIG_KAPI_RUNTIME_CHECKS builds on 32-bit and on architectures without a syscall wrapper, and depends on X86 || !ARCH_HAS_SYSCALL_WRAPPER since other architectures never reach the hook. __SYSCALL_DEFINEx gains small hooks instead of a duplicated copy, with the prototypes in <linux/kapi_syscall.h>.

- Correct the syscall specs against the implementation (O_CREAT|O_DIRECTORY, O_PATH flag masking, EOVERFLOW and RLIMIT_FSIZE handling, SUID/SGID clearing, close() error sources, lock descriptions, madvise locking).

- kdoc_apispec.py: keep paragraph and line structure in long-desc, notes and examples, stop truncating fields at colons or 512 characters, and emit state-transition conditions and exact success values.

- debugfs exports the complete spec as JSON without a fixed-size buffer. tools/kapi gives the same result from --vmlinux and --debugfs, and from --source wherever no preprocessor evaluation is needed.

- kernel-doc recognises the KAPI sections only in -apispec mode, so its other output is unchanged. Kbuild generates headers only for sources with a contexts: line plus another KAPI section, regenerates them when the generator changes, and no longer reads stdin when a directory has no such sources.

- Fix KAPI_CAP_ALTERNATIVE and add KAPI_SIGNAL_MASK_COUNT.

Changes since v3:

- Fix the build with CONFIG_KAPI_SPEC=y: scripts/Makefile.build now derives the list of instrumented sources from $(real-obj-y)/$(real-obj-m) instead of a recursive find, and the detection regex matches "contexts:" (the token the syscalls actually use). The previous "context-flags:"-only match found no files, so no *.apispec.h was generated and the guarded includes failed to compile.

- Force-include the generated *.apispec.h via a per-object -include cflag in scripts/Makefile.build rather than a manual "#include" at the end of each instrumented source; the include blocks are dropped from fs/open.c and fs/read_write.c.

- kernel/Makefile: drop the redundant "obj- += api/"; the obj-$(CONFIG_KAPI_SPEC) gate already covers 'make clean'.

- kernel/api/Makefile: build kernel_api_spec.o with obj-y now that the subdir gate lives in kernel/Makefile.

- kernel/api/Kconfig: drop the tautological "default n" from KAPI_SPEC, KAPI_RUNTIME_CHECKS and KAPI_SPEC_DEBUGFS.

- Add an API specification for sys_madvise.

- Add ftrace tracepoints on the runtime-check path: kapi_syscall_enter (spec name and named parameter values) and kapi_syscall_exit (return value and spec match).

Changes since v2:

- Replace statically sized arrays in the spec structs with const char * pointers to reduce memory footprint and remove string truncation.

- Simplify the kerneldoc DSL to short tokens (e.g. type: uint, input, contexts: process, softirq, constraint-type: range(0, KMAX), side-effect: alloc_memory) in place of raw KAPI_* enum names.

- tools/kapi: commit Cargo.lock for reproducible offline builds, add a Makefile and README, expand the kerneldoc parser to cover the full DSL, and refactor the vmlinux extractor for the const-pointer layout.

- tools/lib/python/kdoc/kdoc_apispec.py expanded to match the DSL so scripts/kernel-doc --apispec emits the structure the extractor consumes.

References:

v4: https://lore.kernel.org/all/[email protected]/
v3: https://lore.kernel.org/all/[email protected]/
v2: https://lore.kernel.org/all/[email protected]/
v1: https://lore.kernel.org/all/[email protected]/
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 (11):
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 kernel/api: add API specification for sys_madvise kernel/api: add syscall enter/exit tracepoints

 .gitignore                                    |    1 +
 Documentation/dev-tools/index.rst             |    1 +
 Documentation/dev-tools/kernel-api-spec.rst   |  648 ++++
 MAINTAINERS                                   |   13 +
 Makefile                                      |    1 +
 arch/x86/include/asm/syscall_wrapper.h        |    3 +-
 fs/open.c                                     |  557 +++
 fs/read_write.c                               |  710 ++++
 include/asm-generic/vmlinux.lds.h             |   14 +
 include/linux/kapi_syscall.h                  |   35 +
 include/linux/kernel_api_spec.h               | 1226 ++++++
 include/linux/syscalls.h                      |   42 +-
 include/trace/events/kapi.h                   |   74 +
 init/Kconfig                                  |    2 +
 kernel/Makefile                               |    1 +
 kernel/api/Kconfig                            |   74 +
 kernel/api/Makefile                           |   13 +
 kernel/api/internal.h                         |   25 +
 kernel/api/kapi_debugfs.c                     |  553 +++
 kernel/api/kapi_kunit.c                       |  720 ++++
 kernel/api/kernel_api_spec.c                  | 1470 ++++++++
 mm/madvise.c                                  |  549 +++
 scripts/Makefile.build                        |   26 +
 tools/docs/kernel-doc                         |   12 +-
 tools/kapi/.gitignore                         |    3 +
 tools/kapi/Cargo.lock                         |  679 ++++
 tools/kapi/Cargo.toml                         |   20 +
 tools/kapi/Makefile                           |   33 +
 tools/kapi/README.md                          |   33 +
 tools/kapi/src/extractor/debugfs.rs           | 1704 +++++++++
 tools/kapi/src/extractor/kerneldoc_parser.rs  | 3335 +++++++++++++++++
 tools/kapi/src/extractor/mod.rs               |  442 +++
 tools/kapi/src/extractor/source_parser.rs     |  531 +++
 .../src/extractor/vmlinux/binary_utils.rs     |  461 +++
 tools/kapi/src/extractor/vmlinux/mod.rs       | 1160 ++++++
 tools/kapi/src/formatter/json.rs              |  659 ++++
 tools/kapi/src/formatter/mod.rs               |  220 ++
 tools/kapi/src/formatter/plain.rs             |  679 ++++
 tools/kapi/src/formatter/rst.rs               |  802 ++++
 tools/kapi/src/main.rs                        |  123 +
 tools/lib/python/kdoc/kdoc_apispec.py         | 1391 +++++++
 tools/lib/python/kdoc/kdoc_files.py           |   12 +-
 tools/lib/python/kdoc/kdoc_parser.py          |  101 +-
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/kapi/.gitignore       |    2 +
 tools/testing/selftests/kapi/Makefile         |    7 +
 tools/testing/selftests/kapi/kapi_test_util.h |   31 +
 tools/testing/selftests/kapi/test_kapi.c      | 1163 ++++++
 48 files changed, 20350 insertions(+), 12 deletions(-)
 create mode 100644 Documentation/dev-tools/kernel-api-spec.rst
 create mode 100644 include/linux/kapi_syscall.h
 create mode 100644 include/linux/kernel_api_spec.h
 create mode 100644 include/trace/events/kapi.h
 create mode 100644 kernel/api/Kconfig
 create mode 100644 kernel/api/Makefile
 create mode 100644 kernel/api/internal.h
 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.lock
 create mode 100644 tools/kapi/Cargo.toml
 create mode 100644 tools/kapi/Makefile
 create mode 100644 tools/kapi/README.md
 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/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/.gitignore
 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.53.0
#1 lore raw

PATCH v5 1/11 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)
- Support for both internal kernel APIs and system calls

The framework stores specifications in a dedicated ELF section and provides infrastructure for:
- Runtime querying of API documentation
- Integration with existing SYSCALL_DEFINE macros

A KUnit suite (CONFIG_KAPI_KUNIT_TEST) covers registration, lookup, parameter and return value validation, and JSON export.

No specifications are added here; subsequent patches add them for individual syscalls. With CONFIG_KAPI_SPEC=n the SYSCALL_DEFINEx() expansion is unchanged. CONFIG_KAPI_RUNTIME_CHECKS is a debug option:
a syscall whose arguments violate its specification returns -EINVAL without running.

Assisted-by LLM
---
 Documentation/dev-tools/index.rst           |    1 +
 Documentation/dev-tools/kernel-api-spec.rst |  615 ++++++++
 MAINTAINERS                                 |   11 +
 arch/x86/include/asm/syscall_wrapper.h      |    3 +-
 include/asm-generic/vmlinux.lds.h           |   14 +
 include/linux/kapi_syscall.h                |   35 +
 include/linux/kernel_api_spec.h             | 1226 ++++++++++++++++
 include/linux/syscalls.h                    |   42 +-
 init/Kconfig                                |    2 +
 kernel/Makefile                             |    1 +
 kernel/api/Kconfig                          |   54 +
 kernel/api/Makefile                         |   10 +
 kernel/api/internal.h                       |   25 +
 kernel/api/kapi_kunit.c                     |  720 ++++++++++
 kernel/api/kernel_api_spec.c                | 1415 +++++++++++++++++++
 15 files changed, 4172 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/dev-tools/kernel-api-spec.rst
 create mode 100644 include/linux/kapi_syscall.h
 create mode 100644 include/linux/kernel_api_spec.h
 create mode 100644 kernel/api/Kconfig
 create mode 100644 kernel/api/Makefile
 create mode 100644 kernel/api/internal.h
 create mode 100644 kernel/api/kapi_kunit.c
 create mode 100644 kernel/api/kernel_api_spec.c
Documentation/dev-tools/index.rst +1 -0
index 59cbb77b33ff4..8d3768645d96c 100644
@@ -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 +615 -0

615 lines not on this page · raw message

MAINTAINERS +11 -0
index 65e8a4b5c90b1..cd15c6a776ae3 100644
@@ -14118,6 +14118,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/kapi_syscall.h
+F:	include/linux/kernel_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 +2 -1
index 7e88705e907f4..54b70c2cac8ac 100644
@@ -223,11 +223,12 @@ extern long __ia32_sys_ni_syscall(const struct pt_regs *regs);
 #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__));\
+	__KAPI_SYSCALL_DEFINEx(x, name, __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_sys##name(__MAP(x,__SC_CAST,__VA_ARGS__));\
+		long ret = __KAPI_DO_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;						\
include/asm-generic/vmlinux.lds.h +14 -0
index b2988aa12f664..b754fa182a6a3 100644
@@ -296,6 +296,19 @@
 #define TRACE_SYSCALLS()
 #endif
 
+#ifdef CONFIG_KAPI_SPEC
+/*
+ * .kapi_specs is an array of pointers (see DEFINE_KERNEL_API_SPEC()). Align
+ * __start_kapi_specs to at least pointer alignment so that no padding
+ * separates it from the first entry.
+ */
+#define KAPI_SPECS()							\
+	. = ALIGN(8);							\
+	BOUNDED_SECTION_BY(.kapi_specs, _kapi_specs)
+#else
+#define KAPI_SPECS()
+#endif
+
 #ifdef CONFIG_BPF_EVENTS
 #define BPF_RAW_TP() STRUCT_ALIGN();				\
 	BOUNDED_SECTION_BY(__bpf_raw_tp_map, __bpf_raw_tp)
@@ -485,6 +498,7 @@
 		. = ALIGN(8);						\
 		BOUNDED_SECTION_BY(__tracepoints_ptrs, ___tracepoints_ptrs) \
 		*(__tracepoints_strings)/* Tracepoints: strings */	\
+		KAPI_SPECS()						\
 	}								\
 									\
 	.rodata1          : AT(ADDR(.rodata1) - LOAD_OFFSET) {		\
include/linux/kapi_syscall.h new file +35 -0
new file mode 100644
index 0000000000000..bc9387e0e052c
@@ -0,0 +1,35 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) 2026 Sasha Levin <[email protected]>
+ *
+ * Spec lookup and syscall validation entry points of the kernel API
+ * specification framework, kept apart from <linux/kernel_api_spec.h> so that
+ * <linux/syscalls.h> can declare them cheaply.
+ */
+
+#ifndef _LINUX_KAPI_SYSCALL_H
+#define _LINUX_KAPI_SYSCALL_H
+
+#include <linux/types.h>
+
+struct kernel_api_spec;
+
+const struct kernel_api_spec *kapi_get_spec(const char *name);
+
+#ifdef CONFIG_KAPI_RUNTIME_CHECKS
+int kapi_validate_syscall_params(const struct kernel_api_spec *spec,
+				 const s64 *params, int param_count);
+int kapi_validate_syscall_return(const struct kernel_api_spec *spec, s64 retval);
+#else
+static inline int kapi_validate_syscall_params(const struct kernel_api_spec *spec,
+					       const s64 *params, int param_count)
+{
+	return 0;
+}
+static inline int kapi_validate_syscall_return(const struct kernel_api_spec *spec, s64 retval)
+{
+	return 0;
+}
+#endif
+
+#endif /* _LINUX_KAPI_SYSCALL_H */
include/linux/kernel_api_spec.h new file +1226 -0

1,226 lines not on this page · raw message

include/linux/syscalls.h +41 -1

63 lines not on this page · raw message

init/Kconfig +2 -0
index ad592fdf29af4..66c23c4147498 100644
@@ -2306,6 +2306,8 @@ source "kernel/Kconfig.kexec"
 
 source "kernel/liveupdate/Kconfig"
 
+source "kernel/api/Kconfig"
+
 endmenu		# General setup
 
 source "arch/Kconfig"
kernel/Makefile +1 -0
index 1e1a31673577d..7fd43127d5eee 100644
@@ -59,6 +59,7 @@ obj-y += dma/
 obj-y += entry/
 obj-y += unwind/
 obj-$(CONFIG_MODULES) += module/
+obj-$(CONFIG_KAPI_SPEC) += api/
 
 obj-$(CONFIG_KCMP) += kcmp.o
 obj-$(CONFIG_FREEZER) += freezer.o
kernel/api/Kconfig new file +54 -0

54 lines not on this page · raw message

kernel/api/Makefile new file +10 -0
new file mode 100644
index 0000000000000..6e14ca243980c
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for the Kernel API Specification Framework
+#
+
+# Core API specification framework
+obj-y				+= kernel_api_spec.o
+
+# KUnit tests
+obj-$(CONFIG_KAPI_KUNIT_TEST) += kapi_kunit.o
kernel/api/internal.h new file +25 -0
new file mode 100644
index 0000000000000..b6112bcc2e8d0
@@ -0,0 +1,25 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) 2026 Sasha Levin <[email protected]>
+ *
+ * Internal declarations shared by the KAPI core and its debugfs
+ * interface. Not part of the public kernel API.
+ */
+
+#ifndef _KERNEL_API_INTERNAL_H
+#define _KERNEL_API_INTERNAL_H
+
+#include <linux/kernel_api_spec.h>
+
+/*
+ * Section boundaries for the `.kapi_specs` array. Defined by the
+ * linker script in include/asm-generic/vmlinux.lds.h.
+ */
+extern const struct kernel_api_spec * const __start_kapi_specs[];
+extern const struct kernel_api_spec * const __stop_kapi_specs[];
+
+const char *kapi_param_type_to_string(enum kapi_param_type type);
+const char *kapi_lock_type_to_string(enum kapi_lock_type type);
+const char *kapi_lock_scope_to_string(enum kapi_lock_scope scope);
+
+#endif /* _KERNEL_API_INTERNAL_H */
kernel/api/kapi_kunit.c new file +720 -0

720 lines not on this page · raw message

kernel/api/kernel_api_spec.c new file +1415 -0

174 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.53.0

Part of the diff is not shown here. View the raw message.

#2 lore raw

PATCH v5 2/11 kernel/api: enable kerneldoc-based API specifications

In reply to Sasha Levin

Add 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 tools/docs/kernel-doc to support the -apispec output format
- Build system integration in Makefile.build
- Support for API-specific sections in kernel-doc comments

kernel-doc recognises the KAPI sections only in -apispec mode, so its other output formats are unchanged. With CONFIG_KAPI_SPEC=y, Kbuild generates <file>.apispec.h for each built source that has a contexts:
or context-flags: line plus another KAPI section, and force-includes it when compiling that source.

Assisted-by LLM
---
 .gitignore                                  |    1 +
 Documentation/dev-tools/kernel-api-spec.rst |   24 +
 Makefile                                    |    1 +
 scripts/Makefile.build                      |   26 +
 tools/docs/kernel-doc                       |   12 +-
 tools/lib/python/kdoc/kdoc_apispec.py       | 1391 +++++++++++++++++++
 tools/lib/python/kdoc/kdoc_files.py         |   12 +-
 tools/lib/python/kdoc/kdoc_parser.py        |  101 +-
 8 files changed, 1558 insertions(+), 10 deletions(-)
 create mode 100644 tools/lib/python/kdoc/kdoc_apispec.py
.gitignore +1 -0
index 9875120ea7bde..37e6cd1d83fc9 100644
@@ -12,6 +12,7 @@
 #
 .*
 *.a
+*.apispec.h
 *.asn1.[ch]
 *.bc
 *.bin
Documentation/dev-tools/kernel-api-spec.rst +24 -0
index 4fb412b2720d3..03b32d3718c8e 100644
@@ -180,6 +180,19 @@ DSL reference:
   from ``range:``.  The function-call
   form populates the matching aux fields
   (``range:`` / ``valid-mask:`` / ``size-param:``).
+* ``arch-mask:`` — extends a ``mask(...)`` constraint with bits that
+  are valid only on a named architecture.  The form is
+  ``arch-mask: <arch> = <bits-expr>`` and may appear multiple times.
+  The named arch must be one of the known short names
+  (``alpha``, ``arc``, ``arm``, ``arm64``, ``csky``, ``hexagon``,
+  ``loongarch``, ``m68k``, ``microblaze``, ``mips``, ``nios2``,
+  ``openrisc``, ``parisc``, ``powerpc``, ``riscv``, ``s390``, ``sh``,
+  ``sparc``, ``um``, ``x86``, ``xtensa``); the generator translates it
+  to the matching ``CONFIG_*`` symbol and emits the bits inside an
+  ``#ifdef`` so a single generated apispec.h compiles on every
+  architecture and folds in the arch-specific bits at compile time.
+  Use this for PROT/MAP bits whose UAPI symbols are defined only on
+  the matching arch.
 * ``lock: … type:`` accepts ``mutex``, ``spinlock``, ``rwlock``,
   ``seqlock``, ``rcu``, ``semaphore``, ``custom`` or ``KAPI_LOCK_*``.
 * ``signal: … direction:`` accepts ``receive``, ``send``, ``handle``,
@@ -266,6 +279,17 @@ The execution context recorded in a specification is not checked at runtime.
 The option is available on x86 and on architectures that use the generic
 ``__SYSCALL_DEFINEx()``.
 
+.. warning::
+
+   Userspace errno is affected when this option is on. For syscalls that
+   violate their parameter specification, KAPI short-circuits the call and
+   returns ``-EINVAL`` from the validator **before** the real handler runs.
+   That errno can differ from what the real handler would have produced for
+   the same condition (for example, ``-ENOMEM`` from an allocation path or
+   ``-EFAULT`` from a deeper copy-in). ``CONFIG_KAPI_RUNTIME_CHECKS`` is a
+   debug-only option; do not enable it on production kernels or in
+   userspace-visible test environments where error-code fidelity matters.
+
 Custom Validators
 -----------------
 
Makefile +1 -0
index 7c855e6fe5448..fd7917f78fa45 100644
@@ -2251,6 +2251,7 @@ clean: $(clean-dirs)
 		-o -name '*.ll' \
 		-o -name '*.gcno' \
 		-o -name '*.long-type-*.txt' \
+		-o -name '*.apispec.h' \
 		\) -type f -print \
 		-o -name '.tmp_*' -print \
 		| xargs rm -rf
scripts/Makefile.build +26 -0
index 4349108e75e1f..6fa9ae47fb2c8 100644
@@ -175,6 +175,32 @@ ifneq ($(KBUILD_EXTRA_WARN),)
 endif
 endif
 
+ifeq ($(CONFIG_KAPI_SPEC),y)
+# kernel-doc -apispec emits a spec only for comments with two or more KAPI
+# sections; pick files with a contexts: (or context-flags:) line and one more
+# KAPI section.
+has-apispec = $(if $(strip $(1)),$(shell \
+	grep -lE '^[[:space:]]*\*[[:space:]]*(contexts|context-flags):' $(1) 2>/dev/null | \
+	xargs -r grep -lE '^[[:space:]]*\*[[:space:]]*(api-type|param|error|capability|signal|lock|state-trans|constraint|side-effect|long-desc):'))
+apispec-c-files := $(call has-apispec, \
+	$(patsubst $(obj)/%.o,$(src)/%.c, \
+		$(filter-out %/built-in.a,$(real-obj-y))))
+apispec-y := $(patsubst $(src)/%.c,$(obj)/%.apispec.h,$(apispec-c-files))
+always-y += $(apispec-y)
+targets += $(apispec-y)
+
+quiet_cmd_apispec = APISPEC $@
+      cmd_apispec = PYTHONDONTWRITEBYTECODE=1 $(PYTHON3) $(KERNELDOC) -apispec \
+                    $(KDOCFLAGS) $< > $@
+
+$(obj)/%.apispec.h: $(src)/%.c $(KERNELDOC) \
+		$(wildcard $(srctree)/tools/lib/python/kdoc/*.py) FORCE
+	$(call if_changed,apispec)
+
+$(apispec-y:.apispec.h=.o): $(obj)/%.o: $(obj)/%.apispec.h
+$(apispec-y:.apispec.h=.o): private c_flags += -include $(obj)/$*.apispec.h
+endif
+
 # Compile C sources (.c)
 # ---------------------------------------------------------------------------
 
tools/docs/kernel-doc +10 -2
index d9192c3f1645e..4c45c0d6cfa94 100755
@@ -250,6 +250,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.")
 
     out_fmt.add_argument("-y", "--yaml-file", "--yaml",
                          help="Stores kernel-doc output on a yaml file.")
@@ -326,6 +328,7 @@ 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
 
     yaml_content = set()
     if args.yaml_file:
@@ -351,12 +354,16 @@ def main():
             out_style = None
             n_outputs += 1
 
+        if args.apispec:
+            out_style = ApiSpecFormat()
+            n_outputs += 1
+
         if  args.rst or n_outputs == 0:
             n_outputs += 1
             out_style = RestFormat()
 
         if n_outputs > 1:
-             parser.error("Those arguments are muttually exclusive: --man, --rst, --none, except when generating a YAML file.")
+             parser.error("Those arguments are muttually exclusive: --man, --rst, --none, --apispec, except when generating a YAML file.")
 
         elif not n_outputs:
             out_style = RestFormat()
@@ -365,7 +372,8 @@ def main():
                          yaml_file=args.yaml_file, yaml_content=yaml_content,
                          out_style=out_style, werror=args.werror,
                          wreturn=args.wreturn, wshort_desc=args.wshort_desc,
-                         wcontents_before_sections=args.wcontents_before_sections)
+                         wcontents_before_sections=args.wcontents_before_sections,
+                         apispec=args.apispec)
 
     kfiles.parse(args.files, export_file=args.export_file)
 
tools/lib/python/kdoc/kdoc_apispec.py new file +1391 -0

1,391 lines not on this page · raw message

tools/lib/python/kdoc/kdoc_files.py +9 -3
index ed82b6e6ab25b..5b81a1e4cc9e9 100644
@@ -94,13 +94,14 @@ class KdocConfig():
     """
     def __init__(self, verbose=False, werror=False, wreturn=False,
                  wshort_desc=False, wcontents_before_sections=False,
-                 logger=None):
+                 logger=None, apispec=False):
 
         self.verbose = verbose
         self.werror = werror
         self.wreturn = wreturn
         self.wshort_desc =  wshort_desc
         self.wcontents_before_sections = wcontents_before_sections
+        self.apispec = apispec
 
         if logger:
             self.log = logger
@@ -159,6 +160,10 @@ class KernelFiles():
     ``yaml_content``
         Defines what will be inside the YAML file.
 
+    ``apispec``
+        If True, also parse the kernel API specification sections used
+        by the ``-apispec`` output. Default: False.
+
     Note:
         There are two type of parsers defined here:
 
@@ -232,7 +237,8 @@ class KernelFiles():
     def __init__(self, verbose=False, out_style=None, xforms=None,
                  werror=False, wreturn=False, wshort_desc=False,
                  wcontents_before_sections=False,
-                 yaml_file=None, yaml_content=None, logger=None):
+                 yaml_file=None, yaml_content=None, logger=None,
+                 apispec=False):
         """
         Initialize startup variables and parse all files.
         """
@@ -271,7 +277,7 @@ class KernelFiles():
         # used to send control configuration to KernelDoc class. As such,
         # those variables are read-only inside the KernelDoc.
         self.config = KdocConfig(verbose, werror, wreturn, wshort_desc,
-                                 wcontents_before_sections, logger)
+                                 wcontents_before_sections, logger, apispec)
 
         # Override log warning, as we want to count errors
         self.config.warning = self.warning
tools/lib/python/kdoc/kdoc_parser.py +96 -5

147 lines not on this page · raw message

Signature · 1 line
2.53.0
#3 lore raw

PATCH v5 3/11 kernel/api: add debugfs interface for kernel API specifications

In reply to Sasha Levin

Add a debugfs interface, enabled by CONFIG_KAPI_SPEC_DEBUGFS, 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
- /sys/kernel/debug/kapi/specs-json/<name> - the same spec as JSON

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 and notes

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

Assisted-by LLM
---
 Documentation/dev-tools/kernel-api-spec.rst |  82 ++-
 kernel/api/Kconfig                          |  20 +
 kernel/api/Makefile                         |   3 +
 kernel/api/kapi_debugfs.c                   | 553 ++++++++++++++++++++
 4 files changed, 641 insertions(+), 17 deletions(-)
 create mode 100644 kernel/api/kapi_debugfs.c
Documentation/dev-tools/kernel-api-spec.rst +65 -17
index 03b32d3718c8e..fa8aabb92a503 100644
@@ -262,6 +262,7 @@ Runtime validation is controlled by kernel configuration:
 
 1. Enable ``CONFIG_KAPI_SPEC`` to build the framework
 2. Enable ``CONFIG_KAPI_RUNTIME_CHECKS`` for runtime validation
+3. Optionally enable ``CONFIG_KAPI_SPEC_DEBUGFS`` for debugfs interface
 
 Validation Behavior
 -------------------
@@ -310,6 +311,68 @@ specification. Kerneldoc annotations cannot set it, so it is only available to a
     .constraint_type = KAPI_CONSTRAINT_CUSTOM,
     .validate = validate_buffer_size,
 
+DebugFS Interface
+=================
+
+The debugfs interface provides runtime access to API specifications:
+
+Directory Structure
+-------------------
+
+::
+
+    /sys/kernel/debug/kapi/
+    ├── 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
+    │   └── sys_madvise          # Human-readable spec for sys_madvise
+    └── specs-json/              # Machine-readable counterpart of specs/
+        ├── sys_open             # JSON spec for sys_open
+        └── ...
+
+Usage Examples
+--------------
+
+List all available API specifications::
+
+    $ cat /sys/kernel/debug/kapi/list
+    Available Kernel API Specifications
+    ===================================
+
+    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
+    sys_madvise - Give advice about use of memory
+
+    Total: 5 specifications
+
+Query specific API::
+
+    $ cat /sys/kernel/debug/kapi/specs/sys_open
+    Kernel API Specification
+    ========================
+
+    Name: sys_open
+    Version: 1
+    Description: Open or create a file
+    ...
+
+The ``specs-json/`` files carry the complete specification: for each
+parameter the type class, flags and the constraint (type, range, valid
+mask, enumerated values, alignment, size and the index of the parameter
+holding a buffer's size), the return check, errors, locks, signals,
+signal masks, side effects, state transitions, capabilities, additional
+constraints and structure specifications. Masks and flag words are
+hex strings, enumerations are lower-case tokens such as
+``"constraint_type": "buffer"``, and ``size_param_idx`` is a 0-based
+index into ``parameters`` (``null`` when unused). The ``kapi`` tool
+reads these files with ``--debugfs`` and reports the same data as
+``--vmlinux``.
+
 Performance Considerations
 ==========================
 
@@ -620,20 +683,5 @@ Submitting Specifications
 1. Add specifications to the same file as the API implementation
 2. Follow existing patterns and naming conventions
 3. Test with CONFIG_KAPI_RUNTIME_CHECKS enabled
-4. Run scripts/checkpatch.pl on your changes
-
-Review Criteria
----------------
-
-Specifications will be reviewed for:
-
-1. **Completeness**: All parameters and errors documented
-2. **Accuracy**: Specification matches implementation
-3. **Clarity**: Descriptions are clear and helpful
-4. **Consistency**: Follows framework conventions
-5. **Performance**: No unnecessary runtime overhead
-
-Contact
--------
-
-- Maintainer: Sasha Levin <[email protected]>
+4. Verify debugfs output is correct
+5. Run scripts/checkpatch.pl on your changes
kernel/api/Kconfig +20 -0
index 1cd55b252f0d5..6075ab82bd231 100644
@@ -41,6 +41,26 @@ config KAPI_RUNTIME_CHECKS
 
 	  If unsure, say N.
 
+config KAPI_SPEC_DEBUGFS
+	bool "Export kernel API specifications via debugfs"
+	depends on KAPI_SPEC
+	depends on DEBUG_FS
+	help
+	  This option enables exporting kernel API specifications through
+	  the debugfs filesystem. When enabled, specifications can be
+	  accessed at /sys/kernel/debug/kapi/.
+
+	  The debugfs interface provides:
+	  - A list of all available API specifications
+	  - Detailed information for each API including parameters,
+	    return values, errors, locking requirements, and constraints
+	  - Complete machine-readable representation of the specs
+
+	  This is useful for documentation tools, static analyzers, and
+	  runtime introspection of kernel APIs.
+
+	  If unsure, say N.
+
 config KAPI_KUNIT_TEST
 	tristate "KUnit tests for KAPI framework" if !KUNIT_ALL_TESTS
 	depends on KAPI_SPEC
kernel/api/Makefile +3 -0
index 6e14ca243980c..2e1c3555d5aa5 100644
@@ -6,5 +6,8 @@
 # Core API specification framework
 obj-y				+= 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_debugfs.c new file +553 -0

553 lines not on this page · raw message

Signature · 1 line
2.53.0
#4 lore raw

PATCH v5 4/11 tools/kapi: add kernel API specification extraction tool

In reply to Sasha Levin

The kapi tool extracts and renders kernel API specifications from three input sources and emits them in one of three output formats:

Input modes:
--source PATH parse kerneldoc blocks from a C source file or
directory
--vmlinux PATH decode the .kapi_specs ELF section from a
compiled kernel binary
--debugfs PATH read the spec dumps exposed under
/sys/kernel/debug/kapi/ on a running kernel

Output formats: plain, json, rst

The tool is written in Rust and builds with cargo from the crates pinned in Cargo.lock; the resulting binary has no runtime dependencies. It ships alongside the kernel to give documentation tools, static analyzers, and IDE integrations a single entry point for querying the spec data produced by the framework.

Assisted-by LLM
---
 Documentation/dev-tools/kernel-api-spec.rst   |   74 +-
 tools/kapi/.gitignore                         |    3 +
 tools/kapi/Cargo.lock                         |  679 ++++
 tools/kapi/Cargo.toml                         |   20 +
 tools/kapi/Makefile                           |   33 +
 tools/kapi/README.md                          |   33 +
 tools/kapi/src/extractor/debugfs.rs           | 1704 +++++++++
 tools/kapi/src/extractor/kerneldoc_parser.rs  | 3335 +++++++++++++++++
 tools/kapi/src/extractor/mod.rs               |  442 +++
 tools/kapi/src/extractor/source_parser.rs     |  531 +++
 .../src/extractor/vmlinux/binary_utils.rs     |  461 +++
 tools/kapi/src/extractor/vmlinux/mod.rs       | 1160 ++++++
 tools/kapi/src/formatter/json.rs              |  659 ++++
 tools/kapi/src/formatter/mod.rs               |  220 ++
 tools/kapi/src/formatter/plain.rs             |  679 ++++
 tools/kapi/src/formatter/rst.rs               |  802 ++++
 tools/kapi/src/main.rs                        |  123 +
 17 files changed, 10886 insertions(+), 72 deletions(-)
 create mode 100644 tools/kapi/.gitignore
 create mode 100644 tools/kapi/Cargo.lock
 create mode 100644 tools/kapi/Cargo.toml
 create mode 100644 tools/kapi/Makefile
 create mode 100644 tools/kapi/README.md
 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/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 +2 -72
index fa8aabb92a503..95b72060f8ef8 100644
@@ -31,7 +31,8 @@ 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. See
+   `The kapi Tool`_.
 
 4. **Formalize Contracts**: Explicitly document API contracts including parameter
    constraints, execution contexts, locking requirements, and side effects.
@@ -573,77 +574,6 @@ The tool supports all KAPI specification types:
 - System calls (kerneldoc annotations)
 - Kernel functions (kerneldoc annotations with KAPI tags)
 
-IDE Integration
----------------
-
-Modern IDEs can use the specification data for:
-
-- Parameter hints
-- Type checking
-- Context validation
-- Error code documentation
-
-Best Practices
-==============
-
-Writing Specifications
-----------------------
-
-1. **Be Comprehensive**: Document all parameters, errors, and side effects
-2. **Keep Updated**: Update specs when API behavior changes
-3. **Use Examples**: Include usage examples in descriptions
-4. **Validate Constraints**: Define realistic constraints for parameters
-5. **Document Context**: Clearly specify allowed execution contexts
-
-Maintenance
------------
-
-1. **Version Specifications**: Increment version when API changes
-2. **Deprecation**: Mark deprecated APIs and suggest replacements
-3. **Cross-reference**: Link related APIs in descriptions
-4. **Test Specifications**: Verify specs match implementation
-
-Common Patterns
----------------
-
-**Optional Parameters**:
-
-.. code-block:: c
-
-    /**
-     * @optional_arg: Optional argument (may be NULL)
-     *
-     * param: optional_arg
-     *   type: KAPI_TYPE_PTR
-     *   flags: KAPI_PARAM_IN | KAPI_PARAM_OPTIONAL
-     */
-
-**Buffer with Size Parameter**:
-
-.. code-block:: c
-
-    /**
-     * @buf: User-space buffer
-     *
-     * param: buf
-     *   type: KAPI_TYPE_USER_PTR
-     *   flags: KAPI_PARAM_OUT | KAPI_PARAM_USER
-     *   constraint-type: KAPI_CONSTRAINT_BUFFER
-     *   size-param: 2
-     */
-
-**Callback Functions**:
-
-.. code-block:: c
-
-    /**
-     * @callback: Callback function
-     *
-     * param: callback
-     *   type: KAPI_TYPE_FUNC_PTR
-     *   flags: KAPI_PARAM_IN
-     */
-
 Troubleshooting
 ===============
 
tools/kapi/.gitignore new file +3 -0
new file mode 100644
index 0000000000000..fa95032ed6c2a
@@ -0,0 +1,3 @@
+# Rust build artifacts
+/target/
+**/*.rs.bk
tools/kapi/Cargo.lock new file +679 -0

679 lines not on this page · raw message

tools/kapi/Cargo.toml new file +20 -0
new file mode 100644
index 0000000000000..159e65d324468
@@ -0,0 +1,20 @@
+[package]
+name = "kapi"
+version = "0.1.0"
+edition = "2021"
+rust-version = "1.85"
+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/Makefile new file +33 -0
new file mode 100644
index 0000000000000..d4234538e4eee
@@ -0,0 +1,33 @@
+# SPDX-License-Identifier: GPL-2.0
+# Makefile wrapper for the kapi tool (Rust userspace binary).
+#
+# See Documentation/dev-tools/kernel-api-spec.rst for details.
+
+PREFIX ?= /usr/local
+
+.PHONY: all build release debug clean install test fmt clippy
+
+all: release
+
+release:
+	cargo build --release
+
+build: release
+
+debug:
+	cargo build
+
+test:
+	cargo test
+
+fmt:
+	cargo fmt --all -- --check
+
+clippy:
+	cargo clippy --all-targets --all-features -- -D warnings
+
+clean:
+	cargo clean
+
+install: release
+	install -D -m 0755 target/release/kapi $(DESTDIR)$(PREFIX)/bin/kapi
tools/kapi/README.md new file +33 -0
new file mode 100644
index 0000000000000..3839f3ff2964a
@@ -0,0 +1,33 @@
+# kapi — Kernel API Specification Extractor
+
+Userspace utility that extracts and displays kernel API specifications from
+three sources:
+
+- `--source PATH` — parse kerneldoc blocks in a C source file or tree
+- `--vmlinux PATH` — decode the `.kapi_specs` ELF section of a compiled vmlinux
+- `--debugfs PATH` — read the live specs from `/sys/kernel/debug/kapi/` on a
+  running kernel (this is also the mode used when no input option is given, in
+  which case PATH is `/sys/kernel/debug`)
+
+Output formats: `plain` (default), `json`, `rst`.
+
+See `Documentation/dev-tools/kernel-api-spec.rst` for the full user guide,
+including the kerneldoc DSL reference and the surrounding framework design.
+
+## Build
+
+```
+make -C tools/kapi
+```
+
+(wraps `cargo build --release`; the binary is produced at
+`tools/kapi/target/release/kapi`).
+
+## Usage
+
+```
+tools/kapi/target/release/kapi --help
+tools/kapi/target/release/kapi --source fs/open.c sys_open
+tools/kapi/target/release/kapi --vmlinux vmlinux -f json
+tools/kapi/target/release/kapi --debugfs /sys/kernel/debug
+```
tools/kapi/src/extractor/debugfs.rs new file +1704 -0

1,704 lines not on this page · raw message

tools/kapi/src/extractor/kerneldoc_parser.rs new file +3335 -0

442 lines not on this page · raw message

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

442 lines not on this page · raw message

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

531 lines not on this page · raw message

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

461 lines not on this page · raw message

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

1,160 lines not on this page · raw message

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

659 lines not on this page · raw message

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

220 lines not on this page · raw message

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

679 lines not on this page · raw message

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

802 lines not on this page · raw message

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

123 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.53.0

Part of the diff is not shown here. View the raw message.

#5 lore raw

PATCH v5 5/11 kernel/api: add API specification for sys_open

In reply to Sasha Levin

Add KAPI-annotated kerneldoc for the sys_open system call in fs/open.c.

The specification documents parameter constraints (pathname, flags bitmask, permission mode), 24 error conditions, locking requirements, side effects, required capabilities, and usage examples.

Assisted-by LLM
---
 fs/open.c | 324 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 324 insertions(+)
fs/open.c +324 -0
index 6b1c14e684a93..92808ab20d52a 100644
@@ -1424,6 +1424,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 named by filename, relative to the current
+ *   working directory if the path is relative. With O_CREAT, the file is
+ *   created if it does not exist. With O_TMPFILE, filename must name an
+ *   existing directory, in which an unnamed file is created. A new file gets
+ *   mode & ~umask as its permission bits.
+ *
+ *   The low two bits of flags (O_ACCMODE) select the access mode: O_RDONLY,
+ *   O_WRONLY or O_RDWR. File creation and file status flags are ORed in.
+ *
+ *   File creation flags: O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC, O_DIRECTORY,
+ *   O_NOFOLLOW, O_CLOEXEC, O_TMPFILE, O_EMPTYPATH. O_EMPTYPATH permits an
+ *   empty filename, which for open() refers to the current working directory.
+ *
+ *   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 with fcntl(F_GETFL). Only
+ *   O_APPEND, O_NONBLOCK, O_DIRECT, O_NOATIME and FASYNC can be changed later
+ *   with fcntl(F_SETFL).
+ *
+ *   On success the lowest-numbered file descriptor not currently open in the
+ *   process is returned.
+ *
+ *   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.
+ *
+ *   open() is equivalent to openat(AT_FDCWD, filename, flags, mode).
+ *
+ * contexts: process, sleepable
+ *
+ * param: filename
+ *   type: path, input
+ *   constraint-type: 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: int, input
+ *   constraint-type: mask(O_RDONLY | O_WRONLY | O_RDWR | O_CREAT | O_EXCL | O_NOCTTY |
+ *                         O_TRUNC | O_APPEND | O_NONBLOCK | O_NDELAY | O_DSYNC | O_SYNC |
+ *                         FASYNC | O_DIRECT | O_LARGEFILE | O_DIRECTORY | O_NOFOLLOW |
+ *                         O_NOATIME | O_CLOEXEC | O_PATH | O_TMPFILE | O_EMPTYPATH)
+ *   cdesc: Should be one of O_RDONLY (0), O_WRONLY (1), or O_RDWR (2) as the
+ *     access mode. Additional flags may be ORed. O_CREAT combined with
+ *     O_DIRECTORY or O_TMPFILE, O_TMPFILE without O_DIRECTORY, and O_TMPFILE
+ *     with read-only mode return EINVAL. With O_PATH, open() silently drops
+ *     every other flag except O_DIRECTORY, O_NOFOLLOW, O_CLOEXEC and
+ *     O_EMPTYPATH (only openat2() rejects them with EINVAL). Unknown flags are
+ *     silently ignored for backward compatibility (unlike openat2 which
+ *     rejects them).
+ *
+ * param: mode
+ *   type: uint, input
+ *   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: int
+ *   check-type: 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
+ *     pathname is a device special file on a nodev mount, or O_CREAT on an
+ *     existing FIFO or regular file in a sticky directory is refused by
+ *     protected_fifos or protected_regular, or a security module denies the
+ *     open.
+ *
+ * error: EAGAIN, Resource temporarily unavailable
+ *   desc: O_NONBLOCK was specified and a conflicting lease is held on the file,
+ *     so the open would have to wait for the lease to break. break_lease()
+ *     returns -EWOULDBLOCK, which has the same value as EAGAIN.
+ *
+ * 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: A signal arrived while the open was blocked waiting for the partner
+ *     of a FIFO open (fifo_open), waiting for a conflicting lease to break
+ *     (__break_lease), or inside a driver's open method. The kernel-internal
+ *     -ERESTARTSYS is reported as EINTR unless the handler uses SA_RESTART.
+ *
+ * error: EINVAL, Invalid argument
+ *   desc: Returned for several conditions: (1) Invalid O_* flag combinations
+ *     (O_CREAT with O_DIRECTORY, O_CREAT with O_TMPFILE, O_TMPFILE without
+ *     O_DIRECTORY, O_TMPFILE with read-only access). (2) O_DIRECT requested
+ *     but the filesystem does not support it.
+ *
+ * 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_CREAT is
+ *     specified and pathname names an existing directory or ends in a slash.
+ *
+ * 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. With
+ *     O_PATH and O_NOFOLLOW the symbolic link itself is opened instead.
+ *
+ * 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: The filesystem or driver open method failed with ENODEV, or the
+ *     file's inode has no file operations assigned. A device special file with
+ *     no registered device fails with ENXIO instead.
+ *
+ * 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 and O_EMPTYPATH is not specified.
+ *
+ * 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 whose device does not exist (chrdev_open, blkdev_open), or
+ *     when opening a socket inode.
+ *
+ * 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: Write access or O_TRUNC was requested for an executable image that
+ *     is currently being executed, or O_TRUNC was requested on an active swap
+ *     file. A swap file can otherwise be opened for writing.
+ *
+ * lock: files->file_lock
+ *   type: 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: semaphore
+ *   acquired: true
+ *   released: true
+ *   desc: Conditional, taken only when the final component is not resolved by
+ *     the lockless dcache lookup. lookup_open() takes it exclusively with
+ *     inode_lock() when O_CREAT is set and shared with inode_lock_shared()
+ *     otherwise. Slow-path lookup of path components takes it shared. Released
+ *     when the lookup returns. The open path has no killable variant.
+ *
+ * lock: RCU read-side
+ *   type: 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: receive
+ *   action: return
+ *   condition: When blocked in an interruptible wait
+ *   desc: The syscall may be interrupted while waiting for the partner of a
+ *     FIFO open (fifo_open), for a conflicting lease to break (__break_lease),
+ *     or inside a driver's open method. The wait returns -ERESTARTSYS, which
+ *     is restarted after the handler with SA_RESTART and reported as EINTR
+ *     otherwise.
+ *   errno: -EINTR
+ *   timing: during
+ *   restartable: yes
+ *
+ * side-effect: resource_create | 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: 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: 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: modify_state
+ *   target: inode timestamps
+ *   condition: When a symlink is followed, or O_TRUNC or O_CREAT takes effect
+ *   desc: Opening does not update the atime of the opened file. Reads update it
+ *     later, and O_NOATIME only affects those reads. Following a symlink in
+ *     the path may update the symlink's atime, subject to the mount atime
+ *     options. O_TRUNC and file creation update mtime and ctime.
+ *
+ * capability: CAP_DAC_OVERRIDE
+ *   type: 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: 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: 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: 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: O_RDONLY is defined as 0, so (flags & O_RDONLY) always evaluates to zero.
+ *   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.
+ */
 SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
 {
 	if (force_o_largefile())
Signature · 1 line
2.53.0
#6 lore raw

Re: [PATCH v5 05/11] kernel/api: add API specification for sys_open

Quoted 8 lines · Sasha Levin

Add KAPI-annotated kerneldoc for the sys_open system call in fs/open.c.

The specification documents parameter constraints (pathname, flags bitmask, permission mode), 24 error conditions, locking requirements, side effects, required capabilities, and usage examples.

Assisted-by LLM

I know Kees and Jonathan and others asked for exactly this. But one downside to this is it makes just paging through fs/open.c a lot more painful. Maybe it's worth it. Maybe "noone will ever do that again" bc that's why we have ai and tools. But a) that's how I've historically done a lot of code research, b) IMO something like a manpages section 2 under Documentation/ would be a great place for this, and c) we can also use tools to always sync these, or even show/edit in a single view when you want ('kdocedit fs/open.c').

Quoted 342 lines
---
 fs/open.c | 324 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 324 insertions(+)
fs/open.c +324 -0
index 6b1c14e684a93..92808ab20d52a 100644
@@ -1424,6 +1424,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 named by filename, relative to the current
+ *   working directory if the path is relative. With O_CREAT, the file is
+ *   created if it does not exist. With O_TMPFILE, filename must name an
+ *   existing directory, in which an unnamed file is created. A new file gets
+ *   mode & ~umask as its permission bits.
+ *
+ *   The low two bits of flags (O_ACCMODE) select the access mode: O_RDONLY,
+ *   O_WRONLY or O_RDWR. File creation and file status flags are ORed in.
+ *
+ *   File creation flags: O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC, O_DIRECTORY,
+ *   O_NOFOLLOW, O_CLOEXEC, O_TMPFILE, O_EMPTYPATH. O_EMPTYPATH permits an
+ *   empty filename, which for open() refers to the current working directory.
+ *
+ *   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 with fcntl(F_GETFL). Only
+ *   O_APPEND, O_NONBLOCK, O_DIRECT, O_NOATIME and FASYNC can be changed later
+ *   with fcntl(F_SETFL).
+ *
+ *   On success the lowest-numbered file descriptor not currently open in the
+ *   process is returned.
+ *
+ *   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.
+ *
+ *   open() is equivalent to openat(AT_FDCWD, filename, flags, mode).
+ *
+ * contexts: process, sleepable
+ *
+ * param: filename
+ *   type: path, input
+ *   constraint-type: 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: int, input
+ *   constraint-type: mask(O_RDONLY | O_WRONLY | O_RDWR | O_CREAT | O_EXCL | O_NOCTTY |
+ *                         O_TRUNC | O_APPEND | O_NONBLOCK | O_NDELAY | O_DSYNC | O_SYNC |
+ *                         FASYNC | O_DIRECT | O_LARGEFILE | O_DIRECTORY | O_NOFOLLOW |
+ *                         O_NOATIME | O_CLOEXEC | O_PATH | O_TMPFILE | O_EMPTYPATH)
+ *   cdesc: Should be one of O_RDONLY (0), O_WRONLY (1), or O_RDWR (2) as the
+ *     access mode. Additional flags may be ORed. O_CREAT combined with
+ *     O_DIRECTORY or O_TMPFILE, O_TMPFILE without O_DIRECTORY, and O_TMPFILE
+ *     with read-only mode return EINVAL. With O_PATH, open() silently drops
+ *     every other flag except O_DIRECTORY, O_NOFOLLOW, O_CLOEXEC and
+ *     O_EMPTYPATH (only openat2() rejects them with EINVAL). Unknown flags are
+ *     silently ignored for backward compatibility (unlike openat2 which
+ *     rejects them).
+ *
+ * param: mode
+ *   type: uint, input
+ *   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: int
+ *   check-type: 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
+ *     pathname is a device special file on a nodev mount, or O_CREAT on an
+ *     existing FIFO or regular file in a sticky directory is refused by
+ *     protected_fifos or protected_regular, or a security module denies the
+ *     open.
+ *
+ * error: EAGAIN, Resource temporarily unavailable
+ *   desc: O_NONBLOCK was specified and a conflicting lease is held on the file,
+ *     so the open would have to wait for the lease to break. break_lease()
+ *     returns -EWOULDBLOCK, which has the same value as EAGAIN.
+ *
+ * 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: A signal arrived while the open was blocked waiting for the partner
+ *     of a FIFO open (fifo_open), waiting for a conflicting lease to break
+ *     (__break_lease), or inside a driver's open method. The kernel-internal
+ *     -ERESTARTSYS is reported as EINTR unless the handler uses SA_RESTART.
+ *
+ * error: EINVAL, Invalid argument
+ *   desc: Returned for several conditions: (1) Invalid O_* flag combinations
+ *     (O_CREAT with O_DIRECTORY, O_CREAT with O_TMPFILE, O_TMPFILE without
+ *     O_DIRECTORY, O_TMPFILE with read-only access). (2) O_DIRECT requested
+ *     but the filesystem does not support it.
+ *
+ * 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_CREAT is
+ *     specified and pathname names an existing directory or ends in a slash.
+ *
+ * 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. With
+ *     O_PATH and O_NOFOLLOW the symbolic link itself is opened instead.
+ *
+ * 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: The filesystem or driver open method failed with ENODEV, or the
+ *     file's inode has no file operations assigned. A device special file with
+ *     no registered device fails with ENXIO instead.
+ *
+ * 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 and O_EMPTYPATH is not specified.
+ *
+ * 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 whose device does not exist (chrdev_open, blkdev_open), or
+ *     when opening a socket inode.
+ *
+ * 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: Write access or O_TRUNC was requested for an executable image that
+ *     is currently being executed, or O_TRUNC was requested on an active swap
+ *     file. A swap file can otherwise be opened for writing.
+ *
+ * lock: files->file_lock
+ *   type: 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: semaphore
+ *   acquired: true
+ *   released: true
+ *   desc: Conditional, taken only when the final component is not resolved by
+ *     the lockless dcache lookup. lookup_open() takes it exclusively with
+ *     inode_lock() when O_CREAT is set and shared with inode_lock_shared()
+ *     otherwise. Slow-path lookup of path components takes it shared. Released
+ *     when the lookup returns. The open path has no killable variant.
+ *
+ * lock: RCU read-side
+ *   type: 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: receive
+ *   action: return
+ *   condition: When blocked in an interruptible wait
+ *   desc: The syscall may be interrupted while waiting for the partner of a
+ *     FIFO open (fifo_open), for a conflicting lease to break (__break_lease),
+ *     or inside a driver's open method. The wait returns -ERESTARTSYS, which
+ *     is restarted after the handler with SA_RESTART and reported as EINTR
+ *     otherwise.
+ *   errno: -EINTR
+ *   timing: during
+ *   restartable: yes
+ *
+ * side-effect: resource_create | 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: 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: 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: modify_state
+ *   target: inode timestamps
+ *   condition: When a symlink is followed, or O_TRUNC or O_CREAT takes effect
+ *   desc: Opening does not update the atime of the opened file. Reads update it
+ *     later, and O_NOATIME only affects those reads. Following a symlink in
+ *     the path may update the symlink's atime, subject to the mount atime
+ *     options. O_TRUNC and file creation update mtime and ctime.
+ *
+ * capability: CAP_DAC_OVERRIDE
+ *   type: 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: 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: 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: 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: O_RDONLY is defined as 0, so (flags & O_RDONLY) always evaluates to zero.
+ *   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.
+ */
 SYSCALL_DEFINE3(open, const char __user *, filename, int, flags, umode_t, mode)
 {
 	if (force_o_largefile())
Signature · 1 line
2.53.0
#7 lore raw

Re: [PATCH v5 05/11] kernel/api: add API specification for sys_open

Quoted 10 lines · Serge E. Hallyn
Quoted 8 lines · Sasha Levin

Add KAPI-annotated kerneldoc for the sys_open system call in fs/open.c.

The specification documents parameter constraints (pathname, flags bitmask, permission mode), 24 error conditions, locking requirements, side effects, required capabilities, and usage examples.

Assisted-by LLM
Quoted 9 lines

I know Kees and Jonathan and others asked for exactly this. But one downside to this is it makes just paging through fs/open.c a lot more painful. Maybe it's worth it. Maybe "noone will ever do that again" bc that's why we have ai and tools. But a) that's how I've historically done a lot of code research, b) IMO something like a manpages section 2 under Documentation/ would be a great place for this, and c) we can also use tools to always sync these, or even show/edit in a single view when you want ('kdocedit fs/open.c').

In many, many other projects i've worked on, these docs are placed in the header as opposed to the .c file, but I understand there is some pain that comes with ifdef.

Keeping it in the header ties the definition to exactly the location external users import to find the function - so it makes sense.

But separating the contracts from the code guarantees they'll go stale, so I don't think shoving it in Documentation/ does anyone any good.

~Gregory

#8 lore raw

Re: [PATCH v5 05/11] kernel/api: add API specification for sys_open

Quoted 21 lines · Gregory Price
Quoted 10 lines · Serge E. Hallyn
Quoted 8 lines · Sasha Levin

Add KAPI-annotated kerneldoc for the sys_open system call in fs/open.c.

The specification documents parameter constraints (pathname, flags bitmask, permission mode), 24 error conditions, locking requirements, side effects, required capabilities, and usage examples.

Assisted-by LLM
Quoted 9 lines

I know Kees and Jonathan and others asked for exactly this. But one downside to this is it makes just paging through fs/open.c a lot more painful. Maybe it's worth it. Maybe "noone will ever do that again" bc that's why we have ai and tools. But a) that's how I've historically done a lot of code research, b) IMO something like a manpages section 2 under Documentation/ would be a great place for this, and c) we can also use tools to always sync these, or even show/edit in a single view when you want ('kdocedit fs/open.c').

Quoted 8 lines

In many, many other projects i've worked on, these docs are placed in the header as opposed to the .c file, but I understand there is some pain that comes with ifdef.

Keeping it in the header ties the definition to exactly the location external users import to find the function - so it makes sense.

But separating the contracts from the code guarantees they'll go stale,

OTOH these descriptions are so long that IMO they are guaranteed to go stale anyway :) While I'm editing a return value at the bottom of the fn, most or all of the description is already going to be off my terminal.

Quoted 1 line

so I don't think shoving it in Documentation/ does anyone any good.

If every build auto-generates an update and then looks for and flags meaningful changes (API breakages), then a) that is more reliable and b) it doesn't matter where the docs are.

Even if there's just a three line comment above a fn, history proves that it will not reliably stay in sync as the fn changes. An automation step/check is needed.

Quoted 1 line

~Gregory

#9 lore raw

Re: [PATCH v5 05/11] kernel/api: add API specification for sys_open

Quoted 22 lines · Serge E. Hallyn
Quoted 21 lines · Gregory Price
Quoted 19 lines · Serge E. Hallyn
Quoted 8 lines · Sasha Levin

Add KAPI-annotated kerneldoc for the sys_open system call in fs/open.c.

The specification documents parameter constraints (pathname, flags bitmask, permission mode), 24 error conditions, locking requirements, side effects, required capabilities, and usage examples.

Assisted-by LLM

I know Kees and Jonathan and others asked for exactly this. But one downside to this is it makes just paging through fs/open.c a lot more painful. Maybe it's worth it. Maybe "noone will ever do that again" bc that's why we have ai and tools. But a) that's how I've historically done a lot of code research, b) IMO something like a manpages section 2 under Documentation/ would be a great place for this, and c) we can also use tools to always sync these, or even show/edit in a single view when you want ('kdocedit fs/open.c').

Quoted 8 lines
Quoted 8 lines

In many, many other projects i've worked on, these docs are placed in the header as opposed to the .c file, but I understand there is some pain that comes with ifdef.

Keeping it in the header ties the definition to exactly the location external users import to find the function - so it makes sense.

But separating the contracts from the code guarantees they'll go stale,

My plan is to be able to have the more detailed part of these specs somewhere else, specially as they will grow some more, but I didn't want to add this complexity right now.

Quoted 7 lines

OTOH these descriptions are so long that IMO they are guaranteed to go stale anyway :) While I'm editing a return value at the bottom of the fn, most or all of the description is already going to be off my terminal.

Quoted 1 line

so I don't think shoving it in Documentation/ does anyone any good.

Quoted 7 lines

If every build auto-generates an update and then looks for and flags meaningful changes (API breakages), then a) that is more reliable and b) it doesn't matter where the docs are.

Even if there's just a three line comment above a fn, history proves that it will not reliably stay in sync as the fn changes. An automation step/check is needed.

Please see CONFIG_KAPI_RUNTIME_CHECKS added by this series.

Signature · 2 lines
Thanks,
Sasha
#10 lore raw

Re: [PATCH v5 05/11] kernel/api: add API specification for sys_open

Quoted 47 lines · Sasha Levin
Quoted 22 lines · Serge E. Hallyn
Quoted 21 lines · Gregory Price
Quoted 19 lines · Serge E. Hallyn
Quoted 8 lines · Sasha Levin

Add KAPI-annotated kerneldoc for the sys_open system call in fs/open.c.

The specification documents parameter constraints (pathname, flags bitmask, permission mode), 24 error conditions, locking requirements, side effects, required capabilities, and usage examples.

Assisted-by LLM

I know Kees and Jonathan and others asked for exactly this. But one downside to this is it makes just paging through fs/open.c a lot more painful. Maybe it's worth it. Maybe "noone will ever do that again" bc that's why we have ai and tools. But a) that's how I've historically done a lot of code research, b) IMO something like a manpages section 2 under Documentation/ would be a great place for this, and c) we can also use tools to always sync these, or even show/edit in a single view when you want ('kdocedit fs/open.c').

Quoted 8 lines
Quoted 8 lines

In many, many other projects i've worked on, these docs are placed in the header as opposed to the .c file, but I understand there is some pain that comes with ifdef.

Keeping it in the header ties the definition to exactly the location external users import to find the function - so it makes sense.

But separating the contracts from the code guarantees they'll go stale,

My plan is to be able to have the more detailed part of these specs somewhere else, specially as they will grow some more, but I didn't want to add this complexity right now.

Quoted 11 lines

OTOH these descriptions are so long that IMO they are guaranteed to go stale anyway :) While I'm editing a return value at the bottom of the fn, most or all of the description is already going to be off my terminal.

Quoted 1 line

so I don't think shoving it in Documentation/ does anyone any good.

If every build auto-generates an update and then looks for and flags meaningful changes (API breakages), then a) that is more reliable and b) it doesn't matter where the docs are.

Quoted 5 lines
Quoted 3 lines

Even if there's just a three line comment above a fn, history proves that it will not reliably stay in sync as the fn changes. An automation step/check is needed.

Please see CONFIG_KAPI_RUNTIME_CHECKS added by this series.

My point was just that whether the docs are inline or not, they will go stale without that automation. So if that's the case, then the docs do not need to be inline.

#11 lore raw

Re: [PATCH v5 05/11] kernel/api: add API specification for sys_open

Quoted 3 lines · Serge E. Hallyn

My point was just that whether the docs are inline or not, they will go stale without that automation. So if that's the case, then the docs do not need to be inline.

Ah, sorry - got it.

The way I saw it working out is that the core part would be inline, but the "speccy" part would move to a different location.

Ultimately, this is the call of the subsystem where those specs live, and I see different subsystems taking different approaches to this.

Signature · 2 lines
Thanks,
Sasha
#12 lore raw

Re: [PATCH v5 05/11] kernel/api: add API specification for sys_open

In reply to Serge E. Hallyn

On Thu, 8 Oct 2026 09:20:01 -0500
"Serge E. Hallyn" <[email protected]> wrote:

...

Quoted 4 lines

Even if there's just a three line comment above a fn, history proves that it will not reliably stay in sync as the fn changes. An automation step/check is needed.

The only way it can possibly stay in step is to have the compiler process the same source text.
Then, if you add/change a function parameter you'd be pretty much forced to add/change the comment.
Return values would have to be documented at the C return statement and really as an extra parameter to the return.

But, IMHO, the whole thing adds too much bloat to the source files. When you 'grep' a source file, you don't really want another match in a big comment at the top of every function.

David

Quoted 2 lines
Quoted 2 lines

~Gregory

#13 lore raw

Re: [PATCH v5 05/11] kernel/api: add API specification for sys_open

Quoted 16 lines · David Laight

On Thu, 8 Oct 2026 09:20:01 -0500
"Serge E. Hallyn" <[email protected]> wrote:

...

Quoted 4 lines

Even if there's just a three line comment above a fn, history proves that it will not reliably stay in sync as the fn changes. An automation step/check is needed.

The only way it can possibly stay in step is to have the compiler process the same source text.
Then, if you add/change a function parameter you'd be pretty much forced to add/change the comment.
Return values would have to be documented at the C return statement and really as an extra parameter to the return.

Quoted 5 lines

But, IMHO, the whole thing adds too much bloat to the source files. When you 'grep' a source file, you don't really want another match in a big comment at the top of every function.

David

That's why I feel all this info that Sasha has added should go into a Documentation/uapi/ autogenerated directory. Auto-updated on every build, with warnings if the result has changed.

-serge

#14 lore raw

Re: [PATCH v5 05/11] kernel/api: add API specification for sys_open

Quoted 17 lines · Serge E. Hallyn
Quoted 16 lines · David Laight

On Thu, 8 Oct 2026 09:20:01 -0500
"Serge E. Hallyn" <[email protected]> wrote:

...

Quoted 4 lines

Even if there's just a three line comment above a fn, history proves that it will not reliably stay in sync as the fn changes. An automation step/check is needed.

The only way it can possibly stay in step is to have the compiler process the same source text.
Then, if you add/change a function parameter you'd be pretty much forced to add/change the comment.
Return values would have to be documented at the C return statement and really as an extra parameter to the return.

Quoted 3 lines
Quoted 3 lines

But, IMHO, the whole thing adds too much bloat to the source files. When you 'grep' a source file, you don't really want another match in a big comment at the top of every function.

I guess I don't mind either way: I heard both sides of this argument, and the spec workflow is okay with either, so if the relevant maintainer asks for changes here I'm more than happy to reformat this.

Which is, I think, the advantage here: it works just fine for the various "kingdoms" we have in kernel-land.

Signature · 2 lines
Thanks,
Sasha
#15 lore raw

PATCH v5 6/11 kernel/api: add API specification for sys_close

In reply to Sasha Levin

Add KAPI-annotated kerneldoc for the sys_close system call in fs/open.c.

The specification documents the file descriptor parameter, error conditions, locking requirements, side effects on pending I/O, and the close-on-exec relationship.

Assisted-by LLM
---
 fs/open.c | 233 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 233 insertions(+)
fs/open.c +233 -0
index 92808ab20d52a..9f08c438f162a 100644
@@ -1861,6 +1861,239 @@ int filp_close(struct file *filp, fl_owner_t id)
 }
 EXPORT_SYMBOL(filp_close);
 
+/**
+ * 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.
+ *
+ *   Traditional POSIX advisory record locks held by the process on the
+ *   associated file are released when any of its fds for that inode is
+ *   closed, not only the last one. OFD locks and flock locks are associated
+ *   with the open file description and are only released when the last
+ *   reference to that open file description is dropped.
+ *
+ *   Closing a file descriptor drops one reference to its open file
+ *   description. Other descriptors (dup(), fork(), SCM_RIGHTS messages in
+ *   flight) and operations still running on the file, such as a concurrent
+ *   read(), also hold references. Only when the last reference is dropped are
+ *   the associated resources freed. If the file was previously unlinked, the
+ *   file itself is deleted when the last reference is dropped.
+ *
+ *   Except when close() fails with EBADF, the file descriptor is released even
+ *   when close() returns an error, because it is released before the flush
+ *   that may fail. POSIX leaves the state of the descriptor unspecified after
+ *   EINTR. Retrying close() after an error may close an unrelated file
+ *   descriptor that another thread has since been given.
+ *
+ *   Errors returned from close() come only from the file's ->flush() method,
+ *   called by filp_flush(). Errors from ->release() are not reported.
+ *   Filesystems without a ->flush() method, such as ext4, xfs and btrfs, never
+ *   report write errors from close(). Network filesystems such as NFS, CIFS and
+ *   FUSE implement ->flush() and report deferred write errors (EIO, ENOSPC,
+ *   EDQUOT) at close time. A successful return does not mean the data reached
+ *   storage; call fsync() before close() for that.
+ *
+ *   On close, the following cleanup operations are performed: the ->flush()
+ *   method is called if the file has one, POSIX advisory locks are removed,
+ *   dnotify registrations are cleaned up, and the file reference is released.
+ *   If this was the last reference, additional cleanup includes: fsnotify close
+ *   notification, epoll cleanup, OFD, flock and lease removal, FASYNC cleanup,
+ *   the ->release() method, and the file structure deallocation.
+ *
+ * contexts: process, sleepable
+ *
+ * param: fd
+ *   type: fd, input
+ *   constraint-type: 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. A value that is not open, including any
+ *     value at or above the current table size, fails with EBADF.
+ *
+ * return:
+ *   type: int
+ *   check-type: exact
+ *   success: 0
+ *   desc: Returns 0 on success. On error, returns a negative error code. Except
+ *     for EBADF, the file descriptor is still closed when an error is returned
+ *     and must not be used again. The error comes from the file's ->flush()
+ *     method, not from the fd remaining open. With EBADF, nothing was released.
+ *
+ * error: EBADF, Bad file descriptor
+ *   desc: fd is at or above the file descriptor table size, has no file
+ *     assigned (including a slot reserved by a concurrent open() that has not
+ *     installed its file yet), or was already closed. This is the only error
+ *     for which no file descriptor was released.
+ *
+ * error: EINTR, Interrupted system call
+ *   desc: The flush operation was interrupted by a signal before completion.
+ *     This occurs when a driver's ->flush() method (for example wdm_flush() in
+ *     drivers/usb/class/cdc-wdm.c) performs an interruptible wait that receives
+ *     a signal. The file descriptor is still released and must not be used
+ *     again. Kernel-internal restart codes (ERESTARTSYS,
+ *     ERESTARTNOINTR, ERESTARTNOHAND, ERESTART_RESTARTBLOCK) are converted to
+ *     EINTR because restarting the syscall would be incorrect once the fd is
+ *     freed.
+ *
+ * error: EIO, I/O error
+ *   desc: The file's ->flush() method reported an I/O error, typically a
+ *     deferred write error on a network filesystem such as NFS, CIFS or FUSE,
+ *     or an error from a driver's ->flush(). Previously buffered write data
+ *     may have been lost.
+ *
+ * error: ENOSPC, No space left on device
+ *   desc: The file's ->flush() method reported that there was insufficient
+ *     space to flush buffered writes, for example on NFS when the server runs
+ *     out of space between write() and close().
+ *
+ * error: EDQUOT, Disk quota exceeded
+ *   desc: The file's ->flush() method reported that the user's disk quota was
+ *     exceeded while flushing buffered writes, for example on NFS when the
+ *     quota is exceeded between write() and close().
+ *
+ * lock: files->file_lock
+ *   type: spinlock
+ *   acquired: true
+ *   released: true
+ *   desc: Taken by file_close_fd() to look up and clear the fd slot atomically,
+ *     so two concurrent close() calls on one fd cannot both obtain the struct
+ *     file. Dropped before ->flush() and the final fput. From then on the fd
+ *     number may be handed out again. An fd reserved by a concurrent open() but
+ *     not yet installed has a NULL slot, so close() returns EBADF.
+ *
+ * lock: file->f_lock
+ *   type: spinlock
+ *   acquired: true
+ *   released: true
+ *   desc: Taken from __fput() on the last reference, by eventpoll_release_file()
+ *     when the file is registered with epoll, and by fasync_remove_entry()
+ *     (through the ->fasync() method) when FASYNC is set. Protects the epoll
+ *     and fasync links of the file.
+ *
+ * lock: ep->mtx
+ *   type: 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: spinlock
+ *   acquired: true
+ *   released: true
+ *   desc: File lock context spinlock. Taken by locks_remove_posix() from
+ *     filp_flush() on every close when the file has POSIX locks, and by
+ *     locks_remove_file() from __fput() on the last reference to remove OFD,
+ *     flock, and lease locks.
+ *
+ * signal: pending_signals
+ *   direction: receive
+ *   action: return
+ *   condition: When close-time flush performs interruptible wait
+ *   desc: If the close-time ->flush() method (for example wdm_flush() in
+ *     cdc-wdm) 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.
+ *   errno: -EINTR
+ *   timing: during
+ *   restartable: no
+ *
+ * side-effect: resource_destroy | 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 happens before the flush that may fail, so
+ *     an error return does not undo it.
+ *   condition: Always (when fd is valid)
+ *   reversible: no
+ *
+ * side-effect: lock_release
+ *   target: POSIX advisory locks, OFD locks, flock locks
+ *   desc: POSIX locks held by this process on the inode are removed on every
+ *     close via locks_remove_posix() in filp_flush(), except for O_PATH files.
+ *     OFD and flock locks are removed via locks_remove_file() in __fput() only
+ *     when this is the last reference to the open file description.
+ *   condition: Any close of a non-O_PATH file for POSIX locks, last reference
+ *     for OFD and flock locks
+ *   reversible: no
+ *
+ * side-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 reference
+ *   reversible: no
+ *
+ * side-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: 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(), which runs from
+ *     __fput() only on the last reference. While other references remain, the
+ *     epoll registrations stay active.
+ *   condition: File was added to epoll instances and this is the last reference
+ *   reversible: no
+ *
+ * side-effect: filesystem
+ *   target: Buffered data
+ *   desc: The file's ->flush() method runs before the file reference is
+ *     dropped (for example on NFS, CIFS and FUSE) and may return errors such as
+ *     EIO, ENOSPC or EDQUOT.
+ *   condition: The filesystem or driver provides a ->flush() method
+ *   reversible: no
+ *
+ * side-effect: free_memory
+ *   target: struct file and related structures
+ *   desc: When this is the last reference to the file, the file structure is
+ *     freed and the dentry and mount references are released.
+ *   condition: This is the last reference to the file
+ *   reversible: no
+ *
+ * side-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.
+ *
+ * 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.
+ *
+ * examples: close(fd);  // Ignoring the result loses ->flush() errors
+ *   if (close(fd) == -1) perror("close");  // Log errors for debugging
+ *   fsync(fd); close(fd);  // Ensure data persistence before closing
+ *
+ * notes: close() drops its reference with fput_close_sync(), so when it is the last
+ *   reference __fput() runs synchronously in the calling task before close()
+ *   returns, instead of being deferred to task work.
+ *
+ *   Calling close() on a file descriptor while another thread is using it
+ *   (e.g., in a blocking read() or write()) does not interrupt the blocked
+ *   operation. The blocked operation continues on the underlying file and
+ *   may complete even after close() returns.
+ */
 /*
  * Careful here! We test whether the file pointer is NULL before
  * releasing the fd. This ensures that one clone task can't release
Signature · 1 line
2.53.0
#16 lore raw

PATCH v5 7/11 kernel/api: add API specification for sys_read

In reply to Sasha Levin

Add KAPI-annotated kerneldoc for the sys_read system call in fs/read_write.c.

The specification documents parameter constraints (fd, user buffer, count), error conditions, locking requirements, signal handling behavior, and short read semantics.

Assisted-by LLM
---
 fs/read_write.c | 297 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 297 insertions(+)
fs/read_write.c +297 -0
index e8c14e2760b20..b89c688a41992 100644
@@ -720,6 +720,303 @@ 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: Reads at most count bytes from fd into the user buffer 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 stream files (FMODE_STREAM, such as pipes, FIFOs, and
+ *   sockets), the file offset is not used. Other files, including many
+ *   character devices, keep a file offset although a driver may ignore it.
+ *
+ *   If count is zero, the usual checks still run and the file's read method is
+ *   still called. Common implementations (regular files, pipes, sockets)
+ *   return zero without transferring data.
+ *
+ *   On success the number of bytes read is returned; zero means end of file
+ *   for regular files. A read can return fewer bytes than requested, for
+ *   example near end of file, on a pipe, socket or terminal with less data
+ *   pending, or when a signal arrives after some data was copied.
+ *
+ *   On Linux, read() transfers at most MAX_RW_COUNT (INT_MAX & PAGE_MASK,
+ *   0x7ffff000 with 4KB pages, just under 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.
+ *
+ * contexts: process, sleepable
+ *
+ * param: fd
+ *   type: fd, input
+ *   constraint-type: 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: user_ptr, output
+ *   constraint-type: buffer(2)
+ *   cdesc: Must point to a writable user-space region of at least count bytes.
+ *     The range is checked via access_ok() and a range outside user space
+ *     fails with EFAULT. NULL is not rejected by that check. With a count of 0
+ *     the call returns 0 in common cases. With a count above 0 the copy fails
+ *     with EFAULT, or the call returns a short count if some data was copied
+ *     first. The buffer may be partially written if an error occurs mid-read.
+ *     O_DIRECT reads may require block-size alignment (see STATX_DIOALIGN).
+ *
+ * param: count
+ *   type: uint, input
+ *   cdesc: Maximum number of bytes to read. The range buf to buf + count must
+ *     lie within user space or access_ok() fails with EFAULT, which includes
+ *     counts that do not fit in ssize_t on 64-bit kernels. A count of 0 passes
+ *     the same checks and the file's read method is still called, typically
+ *     returning 0 without transferring data. After access_ok() and
+ *     rw_verify_area() succeed, counts above MAX_RW_COUNT (INT_MAX &
+ *     PAGE_MASK, 0x7ffff000 with 4KB pages) are clamped to MAX_RW_COUNT.
+ *
+ * return:
+ *   type: int
+ *   check-type: 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 has no read or read_iter
+ *     method (FMODE_CAN_READ is not set). (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) rw_verify_area() rejects a
+ *     negative file position, or a position plus count that overflows, on a
+ *     file without FOP_UNSIGNED_OFFSET. (5) The count, cast to ssize_t, is
+ *     negative (32-bit kernels only).
+ *
+ * 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. 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, it is returned when a
+ *     background process group reads its controlling terminal and SIGTTIN is
+ *     ignored or blocked, or the process group is orphaned.
+ *
+ * error: EOVERFLOW, Value too large for defined data type
+ *   desc: Returned by rw_verify_area() only for files with FOP_UNSIGNED_OFFSET
+ *     (for example /proc/pid/mem) when the file position is negative, meaning
+ *     above LLONG_MAX, and count is at least -pos so that the read would wrap
+ *     past the end of the 64-bit offset space. Files without
+ *     FOP_UNSIGNED_OFFSET get EINVAL for a negative position or a position
+ *     plus count that overflows.
+ *
+ * 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 checks
+ *     on each operation.
+ *
+ * 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 a filesystem built on netfs (for example AFS or Ceph)
+ *     ends a read subrequest short without making progress.
+ *
+ * error: EOPNOTSUPP, Operation not supported
+ *   desc: Returned by the read method of the file, not by the generic VFS
+ *     path. For example, a socket whose protocol has no receive method
+ *     (sock_no_recvmsg) fails with EOPNOTSUPP. A file with no read method at
+ *     all fails with EINVAL instead.
+ *
+ * lock: file->f_pos_lock
+ *   type: mutex
+ *   acquired: true
+ *   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: custom
+ *   acquired: true
+ *   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: rcu
+ *   acquired: true
+ *   released: true
+ *   desc: Taken only when the files_struct is shared with other threads, in
+ *     which case the fd lookup in fdget() uses RCU and takes a file reference.
+ *     A private table needs no RCU. The RCU read lock is acquired and released
+ *     internally by the fd lookup path, not held across the entire syscall.
+ *     fdput() releases the file reference count, not the RCU lock.
+ *
+ * signal: Any signal
+ *   direction: receive
+ *   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). If interrupted before any
+ *     data is read, returns -EINTR or -ERESTARTSYS. If data has already been
+ *     read, returns the number of bytes read.
+ *   errno: -EINTR
+ *   timing: during
+ *   restartable: yes
+ *
+ * side-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: modify_state
+ *   target: inode access time (atime)
+ *   condition: When the read_iter implementation calls file_accessed() and
+ *     O_NOATIME is not set
+ *   desc: The filesystem's read_iter implementation updates atime via
+ *     file_accessed() and touch_atime(). Buffered reads (filemap_read) do this
+ *     after the data loop, including at EOF and after errors, but not for a
+ *     count of 0. O_DIRECT reads (generic_file_read_iter) do it before the
+ *     I/O. The update may be suppressed by mount options (noatime, relatime),
+ *     the O_NOATIME flag, or if the filesystem does not support atime.
+ *     Relatime updates atime only if it is older than mtime or ctime, or more
+ *     than a day old.
+ *   reversible: no
+ *
+ * side-effect: modify_state
+ *   target: task I/O accounting
+ *   condition: When CONFIG_TASK_XACCT is enabled and the read method is invoked
+ *   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 via inc_syscr() once the read method has been invoked, even
+ *     if it fails, but not when the FMODE_READ, FMODE_CAN_READ, access_ok() or
+ *     rw_verify_area() checks fail. These statistics are visible in
+ *     /proc/[pid]/io.
+ *   reversible: no
+ *
+ * side-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
+ *
+ * constraint: MAX_RW_COUNT
+ *   desc: After the access_ok() and rw_verify_area() checks pass, the count
+ *     parameter is silently clamped to MAX_RW_COUNT (INT_MAX & PAGE_MASK, just
+ *     under 2GB) 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 lack FMODE_READ and return EBADF.
+ *     Files that lack FMODE_CAN_READ because they have no read or read_iter
+ *     method return EINVAL.
+ *   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().
+ */
 SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count)
 {
 	return ksys_read(fd, buf, count);
Signature · 1 line
2.53.0
#17 lore raw

PATCH v5 8/11 kernel/api: add API specification for sys_write

In reply to Sasha Levin

Add KAPI-annotated kerneldoc for the sys_write system call in fs/read_write.c.

The specification documents parameter constraints (fd, user buffer, count), error conditions, locking requirements, signal handling behavior, and short write semantics.

Assisted-by LLM
---
 fs/read_write.c | 413 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 413 insertions(+)
fs/read_write.c +413 -0
index b89c688a41992..a9c07c21f5888 100644
@@ -1041,6 +1041,419 @@ 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: Writes at most count bytes from the user buffer buf to 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 stream files
+ *   (FMODE_STREAM, such as pipes, FIFOs, and sockets), the file offset is not
+ *   used and writing occurs at the position defined by the device. Other
+ *   files, including many character devices, keep a file offset although a
+ *   driver may ignore it.
+ *
+ *   Fewer than count bytes may be written, for example when the filesystem
+ *   runs out of space, the write reaches RLIMIT_FSIZE, or a signal arrives
+ *   after some data was written. The caller writes the rest with another
+ *   write() call.
+ *
+ *   On Linux, write() transfers at most MAX_RW_COUNT (INT_MAX & PAGE_MASK,
+ *   0x7ffff000 with 4KB pages, just under 2GB) 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.
+ *
+ * contexts: process, sleepable
+ *
+ * param: fd
+ *   type: fd, input
+ *   constraint-type: 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: user_ptr, input
+ *   constraint-type: buffer(2)
+ *   cdesc: Must point to a readable user-space region of at least count bytes.
+ *     The range is checked via access_ok() and a range outside user space
+ *     fails with EFAULT. NULL is not rejected by that check. With a count of 0
+ *     the call returns 0 in common cases. With a count above 0 the copy from
+ *     user space fails with EFAULT, or the call returns a short count if part
+ *     of the buffer was copied first. O_DIRECT writes may require block-size
+ *     alignment (see STATX_DIOALIGN).
+ *
+ * param: count
+ *   type: uint, input
+ *   cdesc: Maximum number of bytes to write. The range buf to buf + count must
+ *     lie within user space or access_ok() fails with EFAULT, which includes
+ *     counts that do not fit in ssize_t on 64-bit kernels. On 32-bit kernels
+ *     such a count reaches rw_verify_area() and fails with EINVAL. A count of
+ *     0 is passed to the file's write method, which typically returns 0 but
+ *     may trigger driver-specific side effects. After the checks pass, counts
+ *     above MAX_RW_COUNT (INT_MAX & PAGE_MASK, 0x7ffff000 with 4KB pages) are
+ *     clamped.
+ *
+ * return:
+ *   type: int
+ *   check-type: range
+ *   success: >= 0
+ *   desc: On success, returns the number of bytes written (non-negative). Zero
+ *     indicates that nothing was written (count was 0, or a device-specific
+ *     write method accepted no data). Non-blocking writes that cannot proceed
+ *     return -EAGAIN instead. 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 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 has no write or write_iter
+ *     method (FMODE_CAN_WRITE is not set). (2) The file was opened with
+ *     O_DIRECT and the buffer alignment, offset, or count does not meet the
+ *     filesystem's alignment requirements. (3) rw_verify_area() rejects a
+ *     negative file position, or a position plus count that overflows, on a
+ *     file without FOP_UNSIGNED_OFFSET. (4) The count, cast to ssize_t, is
+ *     negative (32-bit kernels only, as 64-bit kernels fail access_ok() first
+ *     with EFAULT).
+ *
+ * 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.
+ *     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: The write starts at or beyond a file size limit. The generic write
+ *     path returns EFBIG when the starting position is at or beyond
+ *     RLIMIT_FSIZE, in which case the process also receives SIGXFSZ, or at or
+ *     beyond the maximum file size of the filesystem. Without O_LARGEFILE
+ *     (32-bit systems only) that maximum is 2GB minus one byte. A write that
+ *     starts below a limit but would cross it is shortened to end at the
+ *     limit.
+ *
+ * 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, or F_SEAL_GROW for a write that
+ *     extends the file), (2) by a filesystem-specific check, for example ext4
+ *     refuses writes to an immutable inode, (3) because the file is a
+ *     read-only block device, (4) by an LSM hook denying the operation, or (5)
+ *     by a fanotify pre-content (FAN_PRE_ACCESS) listener denying the write.
+ *
+ * error: EOVERFLOW, Value too large for defined data type
+ *   desc: Returned by rw_verify_area() only for files with FOP_UNSIGNED_OFFSET
+ *     (for example /proc/pid/mem) when the file position is negative, meaning
+ *     above LLONG_MAX, and count is at least -pos so that the write would wrap
+ *     past the end of the 64-bit offset space. Files without
+ *     FOP_UNSIGNED_OFFSET get EINVAL for a negative position or a position
+ *     plus count that overflows. Exceeding filesystem file size limits is
+ *     EFBIG, not EOVERFLOW.
+ *
+ * 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).
+ *
+ * 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: mutex
+ *   acquired: true
+ *   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: custom
+ *   acquired: true
+ *   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: semaphore
+ *   acquired: true
+ *   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: mutex
+ *   acquired: true
+ *   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: rcu
+ *   acquired: true
+ *   released: true
+ *   desc: Taken only when the files_struct is shared with other threads, in
+ *     which case the fd lookup in fdget() uses RCU and takes a file reference.
+ *     A private table needs no RCU. The RCU read lock is acquired and released
+ *     internally by the fd lookup path, not held across the entire syscall.
+ *     fdput() releases the file reference count, not the RCU lock.
+ *
+ * signal: SIGPIPE
+ *   number: SIGPIPE
+ *   direction: send
+ *   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: during
+ *
+ * signal: SIGXFSZ
+ *   number: SIGXFSZ
+ *   direction: send
+ *   action: coredump
+ *   condition: Write starts at or beyond RLIMIT_FSIZE
+ *   desc: When a write starts at or beyond the soft file size limit
+ *     (RLIMIT_FSIZE), generic_write_check_limits() sends SIGXFSZ and the write
+ *     returns EFBIG. The default action terminates with a core dump. A write
+ *     that starts below the limit but would cross it is shortened to end at
+ *     the limit, with no signal. If RLIMIT_FSIZE is RLIM_INFINITY, no signal
+ *     is sent.
+ *   timing: during
+ *
+ * signal: Any signal
+ *   direction: receive
+ *   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.
+ *   errno: -EINTR
+ *   timing: during
+ *   restartable: yes
+ *
+ * side-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: modify_state
+ *   target: inode timestamps (mtime, ctime)
+ *   condition: Before the data is copied, for a non-zero count on the generic
+ *     write path
+ *   desc: Updates the file's modification time (mtime) and change time (ctime)
+ *     via file_update_time(), which runs before the data is copied, so the
+ *     timestamps can change even if the write then fails or is short. The
+ *     update is skipped for inodes flagged NOCMTIME and when the timestamps
+ *     are unchanged. The timestamp precision depends on whether the filesystem
+ *     type sets FS_MGTIME (multigrain timestamps).
+ *   reversible: no
+ *
+ * side-effect: modify_state
+ *   target: SUID/SGID bits (mode) and file capabilities
+ *   condition: Write to a regular file that has S_ISUID, S_ISGID, or file
+ *     capabilities set, with a non-zero count
+ *   desc: file_remove_privs() clears S_ISUID, and clears S_ISGID when S_IXGRP
+ *     is also set or the caller is not in the file's group, unless the caller
+ *     has CAP_FSETID. File capabilities (the security.capability xattr) are
+ *     removed as well, regardless of CAP_FSETID. This is a security feature to
+ *     prevent privilege escalation via modified setuid binaries. It runs before
+ *     the data is copied.
+ *   reversible: no
+ *
+ * side-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 is not guaranteed to be persistent until fsync() or fdatasync()
+ *     completes, or writeback has written it to storage.
+ *   reversible: no
+ *
+ * side-effect: modify_state
+ *   target: task I/O accounting
+ *   condition: When CONFIG_TASK_XACCT is enabled and the write method is
+ *     invoked
+ *   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 via inc_syscw() once the write method has been invoked, even
+ *     if it fails, but not when the FMODE_WRITE, FMODE_CAN_WRITE, access_ok()
+ *     or rw_verify_area() checks fail. These statistics are visible in
+ *     /proc/[pid]/io.
+ *   reversible: no
+ *
+ * side-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_FSETID
+ *   type: bypass_check
+ *   allows: Keep the SUID and SGID bits set when the file is written
+ *   without: SUID is cleared on write, and SGID is cleared if S_IXGRP is set
+ *     or the caller is not in the file's group
+ *   condition: Checked in setattr_should_drop_suidgid() during
+ *     file_remove_privs()
+ *
+ * constraint: MAX_RW_COUNT
+ *   desc: After the access_ok() and rw_verify_area() checks pass, the count
+ *     parameter is silently clamped to MAX_RW_COUNT (INT_MAX & PAGE_MASK, just
+ *     under 2GB) 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. In generic_write_check_limits(), a write that starts at or beyond
+ *     the limit sends SIGXFSZ and returns EFBIG. A write that starts below the
+ *     limit but would cross it is shortened to limit - pos bytes, with no
+ *     signal.
+ *   expr: pos < 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
+ *   // Handle short writes:
+ *   while (total < len) {
+ *     n = write(fd, buf + total, len - total);
+ *     if (n < 0) break;
+ *     total += n;
+ *   }
+ *   // Pipe error handling:
+ *   if (write(pipefd[1], &byte, 1) < 0 && errno == EPIPE)
+ *     handle_broken_pipe();
+ *
+ * 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.
+ */
 SYSCALL_DEFINE3(write, unsigned int, fd, const char __user *, buf,
 		size_t, count)
 {
Signature · 1 line
2.53.0
#18 lore raw

PATCH v5 9/11 kernel/api: add runtime verification selftest

In reply to Sasha Levin

Add 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-8: Unknown open flag bits and a NULL path are rejected with EINVAL,
while mode bits above 07777 are accepted (the kernel masks them)
9-20: Boundary conditions and error paths (bad and closed fds, zero
counts, over-long paths, unmapped buffers, wrong access mode)
21-27: Pipe, file descriptor lifecycle and other error paths 28-30: A normal open/read/write/close sequence, and read()/write() with
a NULL buffer and a zero count returning 0
31: dmesg contains the expected KAPI warning strings

Tests that depend on CONFIG_KAPI_RUNTIME_CHECKS are skipped when an open() with an unknown flag bit succeeds, which means the checks are not active.

Assisted-by LLM
---
 MAINTAINERS                                   |    1 +
 tools/testing/selftests/Makefile              |    1 +
 tools/testing/selftests/kapi/.gitignore       |    2 +
 tools/testing/selftests/kapi/Makefile         |    7 +
 tools/testing/selftests/kapi/kapi_test_util.h |   31 +
 tools/testing/selftests/kapi/test_kapi.c      | 1163 +++++++++++++++++
 6 files changed, 1205 insertions(+)
 create mode 100644 tools/testing/selftests/kapi/.gitignore
 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
index cd15c6a776ae3..1d9e55b6bf5ff 100644
@@ -14128,6 +14128,7 @@ F:	include/linux/kernel_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/Makefile +1 -0
index 273853937c254..d5f973eeefc83 100644
@@ -60,6 +60,7 @@ TARGETS += intel_pstate
 TARGETS += iommu
 TARGETS += ipc
 TARGETS += ir
+TARGETS += kapi
 TARGETS += kcmp
 TARGETS += kexec
 TARGETS += kselftest_harness
tools/testing/selftests/kapi/.gitignore new file +2 -0
new file mode 100644
index 0000000000000..e60893d183d81
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0-only
+test_kapi
tools/testing/selftests/kapi/Makefile new file +7 -0
new file mode 100644
index 0000000000000..d1bb26541c0b8
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0
+
+TEST_GEN_PROGS := test_kapi
+
+CFLAGS += -static -Wall -Wextra -O2 $(KHDR_INCLUDES)
+
+include ../lib.mk
tools/testing/selftests/kapi/kapi_test_util.h new file +31 -0
new file mode 100644
index 0000000000000..a09871207bfc6
@@ -0,0 +1,31 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) 2026 Sasha Levin <[email protected]>
+ *
+ * Compatibility helpers for KAPI selftests.
+ *
+ * __NR_open does not exist on architectures using the generic syscall table
+ * (e.g. arm64, riscv); only __NR_openat does. There the wrapper falls back to
+ * openat(AT_FDCWD, ...), which does not go through sys_open, so the sys_open
+ * KAPI checks are not exercised.
+ */
+#ifndef KAPI_TEST_UTIL_H
+#define KAPI_TEST_UTIL_H
+
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/syscall.h>
+
+#ifndef __NR_open
+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 +1163 -0

1,163 lines not on this page · raw message

Signature · 1 line
2.53.0
#19 lore raw

PATCH v5 10/11 kernel/api: add API specification for sys_madvise

In reply to Sasha Levin

Add KAPI-annotated kerneldoc for the sys_madvise system call in mm/madvise.c.

The specification documents the parameters (start, len_in, behavior), per-behavior error conditions, lock acquisition (mmap_lock read and write modes plus the per-VMA fast path, mmu_gather and mmu_notifier brackets), signal handling, side effects, capability requirements (CAP_SYS_ADMIN for MADV_HWPOISON and MADV_SOFT_OFFLINE), mseal interaction, and how each behavior skips pages or reports errors.

Assisted-by LLM
---
 mm/madvise.c | 549 +++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 549 insertions(+)
mm/madvise.c +549 -0
index eeee82cf2b3f4..4eb29922a2150 100644
@@ -2018,6 +2018,555 @@ int do_madvise(struct mm_struct *mm, unsigned long start, size_t len_in, int beh
 	return error;
 }
 
+/**
+ * sys_madvise - Give advice about use of memory
+ * @start: Starting virtual address of the range to advise on
+ * @len_in: Length of the range in bytes
+ * @behavior: Advice (a MADV_* constant) the kernel should apply to the range
+ *
+ * long-desc: Provides the kernel with advice or directions about the address
+ *   range starting at start and extending for len_in bytes. The advice is
+ *   selected by behavior, which is one of the MADV_* constants defined in
+ *   <sys/mman.h>. The behaviors fall into three groups. The hint group
+ *   updates VMA flags (MADV_NORMAL, MADV_RANDOM, MADV_SEQUENTIAL,
+ *   MADV_DONTFORK, MADV_DOFORK, MADV_DONTDUMP, MADV_DODUMP, MADV_WIPEONFORK,
+ *   MADV_KEEPONFORK, MADV_MERGEABLE, MADV_UNMERGEABLE, MADV_HUGEPAGE,
+ *   MADV_NOHUGEPAGE). The immediate-action group performs work synchronously
+ *   while preserving page contents (MADV_WILLNEED, MADV_COLD, MADV_PAGEOUT,
+ *   MADV_POPULATE_READ, MADV_POPULATE_WRITE, MADV_COLLAPSE, MADV_GUARD_REMOVE,
+ *   MADV_SOFT_OFFLINE). The destructive group discards, replaces or
+ *   invalidates page contents (MADV_DONTNEED, MADV_DONTNEED_LOCKED, MADV_FREE,
+ *   MADV_REMOVE, MADV_GUARD_INSTALL, MADV_HWPOISON). MADV_GUARD_INSTALL
+ *   belongs to the destructive group because it zaps any existing pages in
+ *   the range before installing PTE guard markers.
+ *
+ *   start must be page-aligned; len_in is rounded up to the next page
+ *   boundary internally. Once those validation checks pass, a zero-length
+ *   range succeeds without performing work. The kernel rejects ranges that
+ *   wrap (start + PAGE_ALIGN(len_in) < start) and ranges where len_in is
+ *   non-zero but rounds up to zero. Address tagging bits are stripped
+ *   from start before VMA lookup for every behavior except MADV_HWPOISON
+ *   and MADV_SOFT_OFFLINE, which receive the raw start value because they
+ *   bypass the VMA walk entirely.
+ *
+ *   The kernel return value reports whether any error condition was
+ *   encountered, not whether the requested work was performed. The
+ *   relationship between the return code and the work done varies by
+ *   handler:
+ *
+ *     - Hint behaviors set or clear VMA flags; how the flag is used later
+ *       depends on the behavior. MADV_DONTFORK / MADV_DOFORK set or clear
+ *       VM_DONTCOPY, which dup_mmap() honors, so the child does not get the
+ *       mapping. MADV_MERGEABLE / MADV_UNMERGEABLE control whether KSM scans
+ *       the VMA. MADV_NOHUGEPAGE blocks the fault-time, MADV_COLLAPSE and
+ *       khugepaged THP paths for the VMA. MADV_HUGEPAGE makes the VMA
+ *       eligible for THP when the transparent_hugepage mode is "madvise" and
+ *       increases defrag effort; it does not force allocation, which still
+ *       depends on the global mode, VMA suitability, defrag GFP policy, and
+ *       allocation or memcg-charge success. MADV_WIPEONFORK does not wipe
+ *       pages at fork time; the child VMA's pages are not copied, and the
+ *       child sees zero-filled pages when it first touches them.
+ *       MADV_KEEPONFORK clears VM_WIPEONFORK. MADV_DONTDUMP / MADV_DODUMP set
+ *       or clear VM_DONTDUMP, although always_dump_vma() still includes gate,
+ *       vm_ops-named or arch-named VMAs in a core dump. MADV_NORMAL /
+ *       MADV_RANDOM / MADV_SEQUENTIAL set or clear VM_RAND_READ / VM_SEQ_READ,
+ *       which only steer read-ahead.
+ *
+ *     - Walk-and-skip handlers (MADV_COLD, MADV_PAGEOUT, MADV_FREE,
+ *       MADV_GUARD_REMOVE) traverse the range and silently skip pages or
+ *       PMDs that fail per-page preconditions (absent, special, device,
+ *       shared, non-LRU, unsplittable, locked, etc.), returning 0 even
+ *       when most or all pages were skipped.
+ *
+ *     - Bulk-backend handlers delegate the requested range to a single
+ *       backend call: MADV_DONTNEED and MADV_DONTNEED_LOCKED to
+ *       zap_vma_range_batched(), MADV_REMOVE to vfs_fallocate(),
+ *       MADV_WILLNEED on regular files to vfs_fadvise(). The backend's
+ *       return is propagated for MADV_REMOVE and discarded for
+ *       MADV_WILLNEED; DAX files short-circuit MADV_WILLNEED entirely.
+ *
+ *     - Stop-on-error handlers (MADV_POPULATE_READ, MADV_POPULATE_WRITE,
+ *       MADV_SOFT_OFFLINE) walk the range but surface the first per-page
+ *       failure as an errno (-EHWPOISON, -EFAULT, -ENOMEM, ...) rather
+ *       than skipping silently.
+ *
+ *     - Hybrid handlers combine modes: MADV_WILLNEED walks for anonymous
+ *       and shmem ranges but bulk-calls vfs_fadvise() for regular files;
+ *       MADV_COLLAPSE walks PMD-by-PMD and tracks the last scan failure
+ *       so transient skips coexist with terminal errors;
+ *       MADV_GUARD_INSTALL walks to install markers and re-walks after
+ *       zap_vma_range() to clear pre-existing pages, retrying up to
+ *       MAX_MADVISE_GUARD_RETRIES; MADV_HWPOISON walks pages but folds
+ *       memory_failure()'s -EOPNOTSUPP back to 0.
+ *
+ *   Applications that need to know whether a specific page was acted on
+ *   must verify the result through other means (e.g. /proc/[pid]/smaps,
+ *   page faults, read-after-write).
+ *
+ *   On success, madvise() returns 0; unlike read(2) and write(2) it has no
+ *   notion of partial completion at the syscall boundary. When the range
+ *   spans multiple VMAs, the kernel applies the advice to each in turn. For
+ *   the behaviors that walk VMAs (all except MADV_POPULATE_*, MADV_HWPOISON
+ *   and MADV_SOFT_OFFLINE), an unmapped gap inside the range causes the call
+ *   to return -ENOMEM after processing the mapped portions, rather than
+ *   aborting at the gap, although the walk stops at the first per-VMA error.
+ *   MADV_POPULATE_* stops at the first failure, and MADV_HWPOISON and
+ *   MADV_SOFT_OFFLINE bypass the walk, so an unmapped address gives -EFAULT.
+ *
+ *   POSIX defines posix_madvise(3) for a portable subset (POSIX_MADV_NORMAL,
+ *   _RANDOM, _SEQUENTIAL, _WILLNEED, _DONTNEED). Linux MADV_DONTNEED is
+ *   destructive: it discards the contents of the affected anonymous pages and
+ *   subsequent reads return zero. POSIX permits but does not require
+ *   destruction, so portable code that needs the POSIX semantics should use
+ *   posix_madvise(3) instead.
+ *
+ * contexts: process, sleepable
+ *
+ * param: start
+ *   type: uint, input
+ *   constraint-type: page_aligned
+ *   cdesc: Starting virtual address of the range. Must be aligned to
+ *     PAGE_SIZE. An unaligned start always returns -EINVAL, even when
+ *     len_in is zero. Address tag bits, where supported by the architecture,
+ *     are cleared via untagged_addr() before the range is interpreted, with
+ *     the exception of MADV_HWPOISON and MADV_SOFT_OFFLINE, which receive
+ *     the raw start value because they bypass the VMA walk.
+ *
+ * param: len_in
+ *   type: uint, input
+ *   cdesc: Length of the range in bytes. Internally rounded up to a multiple
+ *     of PAGE_SIZE. A len_in of 0 is accepted and the call is a no-op that
+ *     returns 0. A non-zero len_in that rounds up to 0 (i.e. wraps around)
+ *     returns -EINVAL, as does a range whose end (start + PAGE_ALIGN(len_in))
+ *     would wrap below start.
+ *
+ * param: behavior
+ *   type: int, input
+ *   cdesc: One of the MADV_* constants from <sys/mman.h>. See the long
+ *     description above for the full list and the three semantic groups
+ *     (hint, immediate-action, destructive). Behaviors gated by Kconfig
+ *     (KSM, transparent hugepage, memory failure) return -EINVAL when the
+ *     underlying support is disabled. A few architectures (notably alpha)
+ *     renumber values; portable code should always use the symbolic names.
+ *
+ * return:
+ *   type: int
+ *   check-type: exact
+ *   success: 0
+ *   desc: On success, returns 0. On error, returns a negative error code.
+ *     There is no partial-success indication; either the entire processed
+ *     range succeeded, or an error is returned and an unspecified prefix of
+ *     the range may have been advised.
+ *
+ * error: EINVAL, Invalid argument
+ *   desc: Invalid input (unknown or Kconfig-disabled MADV_*, unaligned start,
+ *     range wrap, non-zero len_in rounding up to zero) or a VMA filter.
+ *     DONTNEED/FREE reject VM_PFNMAP, VM_LOCKED (not DONTNEED_LOCKED) and
+ *     misaligned hugetlb; FREE non-anonymous; WIPEONFORK file or shared; REMOVE
+ *     VM_LOCKED or no file; COLD/PAGEOUT LOCKED/PFNMAP/HUGETLB; DOFORK
+ *     VM_SPECIAL; KEEPONFORK VM_DROPPABLE; DODUMP SPECIAL/DROPPABLE; GUARD_*
+ *     SPECIAL/HUGETLB (INSTALL also LOCKED); COLLAPSE if not possible;
+ *     POPULATE_* on bad permissions.
+ *
+ * error: ENOMEM, Cannot allocate memory
+ *   desc: For VMA-walking behaviors, a gap between mapped VMAs inside the range
+ *     gives -ENOMEM after the mapped subranges have been processed, unless a
+ *     per-VMA error ends the walk first. MADV_POPULATE_* stops at the first
+ *     failure and returns -ENOMEM when the region has no VMA or
+ *     faultin_page_range() exhausts memory. MADV_COLLAPSE returns -ENOMEM when
+ *     its struct collapse_control cannot be allocated, and when
+ *     madvise_collapse_errno() maps SCAN_ALLOC_HUGE_PAGE_FAIL (no hugepage
+ *     available) to it.
+ *
+ * error: EAGAIN, Resource temporarily unavailable
+ *   desc: For the VMA-flag-mutating behaviors, an internal -ENOMEM from VMA
+ *     splitting is translated to -EAGAIN before being returned to userspace,
+ *     advising the caller that a transient kernel resource shortage
+ *     prevented the update. Also returned by MADV_COLLAPSE via
+ *     madvise_collapse_errno() for transient scan failures (folio lock
+ *     contention, LRU isolation failure, dirty/writeback) where retrying
+ *     the call may succeed.
+ *
+ * error: EIO, Input/output error
+ *   desc: For MADV_REMOVE, an I/O error from the underlying filesystem's
+ *     FALLOC_FL_PUNCH_HOLE handler is propagated back as -EIO, and
+ *     MADV_SOFT_OFFLINE returns -EIO when soft_offline_page() cannot handle
+ *     the page. MADV_HWPOISON reports an unhandled page as -EBUSY; -EIO can
+ *     reach it only from a ZONE_DEVICE pagemap's ->memory_failure()
+ *     callback. MADV_WILLNEED and MADV_PAGEOUT do not surface filesystem or
+ *     device I/O errors: vfs_fadvise() returns are discarded by
+ *     madvise_willneed() and the pageout walk is invoked through a void
+ *     helper, so transient I/O failures during read-ahead or page-out are
+ *     silently dropped.
+ *
+ * error: EBADF, Bad file descriptor
+ *   desc: Returned by MADV_WILLNEED when applied to a non-file-backed VMA
+ *     and the kernel was built without CONFIG_SWAP, so there is neither a
+ *     file to read-ahead from nor a swap device to fault from.
+ *
+ * error: EACCES, Permission denied
+ *   desc: Returned by MADV_REMOVE when the target VMA fails
+ *     vma_is_shared_maywrite(), which needs both VM_SHARED and VM_MAYWRITE.
+ *     Private file mappings and shared mappings of files not opened for
+ *     writing are refused, while a PROT_READ MAP_SHARED mapping of a file
+ *     opened O_RDWR is accepted. Punching a hole through a refused mapping
+ *     would either be invisible to other mappers or bypass file write
+ *     permission.
+ *
+ * error: EPERM, Operation not permitted
+ *   desc: Returned in two situations. First, MADV_HWPOISON and
+ *     MADV_SOFT_OFFLINE require CAP_SYS_ADMIN; the inject-error handler
+ *     refuses non-privileged callers. Second, on 64-bit kernels, a discard
+ *     operation (MADV_FREE, MADV_DONTNEED, MADV_DONTNEED_LOCKED, MADV_REMOVE,
+ *     MADV_DONTFORK, MADV_WIPEONFORK, MADV_GUARD_INSTALL) is refused on a
+ *     read-only anonymous VMA that has been sealed with mseal(2), to prevent
+ *     bypassing the seal by discarding mapped data.
+ *
+ * error: EINTR, Interrupted system call
+ *   desc: Returned when a fatal signal is delivered while the call is
+ *     waiting to acquire the mmap write lock for a VMA-flag-mutating
+ *     behavior (mmap_write_lock_killable() returns -EINTR), or when
+ *     MADV_POPULATE_READ/MADV_POPULATE_WRITE is interrupted while faulting
+ *     in pages (faultin_page_range() returns -EINTR). Only a fatal signal
+ *     interrupts these waits, so the task is being killed and user space
+ *     does not normally see the error.
+ *
+ * error: EHWPOISON, Memory page has hardware error
+ *   desc: MADV_POPULATE_READ or MADV_POPULATE_WRITE encountered a page that
+ *     has been marked as containing a hardware-detected memory error and
+ *     could not be faulted in. MADV_HWPOISON also returns it when
+ *     memory_failure() finds the page already poisoned.
+ *
+ * error: EFAULT, Bad address
+ *   desc: MADV_POPULATE_READ or MADV_POPULATE_WRITE attempted to fault in a
+ *     page whose mapping raised VM_FAULT_SIGBUS or VM_FAULT_SIGSEGV (for
+ *     example, a file-backed page beyond the end of the file).
+ *     MADV_HWPOISON and MADV_SOFT_OFFLINE return a get_user_pages_fast()
+ *     failure, typically -EFAULT for an unmapped address.
+ *
+ * error: EBUSY, Device or resource busy
+ *   desc: Returned by MADV_COLLAPSE via madvise_collapse_errno() in two
+ *     specific scan-failure modes: SCAN_CGROUP_CHARGE_FAIL (the new
+ *     hugepage cannot be charged to the memory cgroup) and
+ *     SCAN_EXCEED_NONE_PTE (too many absent PTEs in the candidate range
+ *     for a synchronous collapse). Other transient collapse failures are
+ *     reported as -EAGAIN; non-transient ones as -EINVAL. MADV_HWPOISON and
+ *     MADV_SOFT_OFFLINE also return -EBUSY when the page cannot be handled.
+ *
+ * error: EOPNOTSUPP, Operation not supported
+ *   desc: MADV_REMOVE propagates vfs_fallocate() errors verbatim, so a
+ *     filesystem without FALLOC_FL_PUNCH_HOLE support fails with -EOPNOTSUPP
+ *     (other propagated errors include -EPERM, -ETXTBSY and -ENOSPC).
+ *     MADV_SOFT_OFFLINE also returns it when soft offlining is disabled via
+ *     /proc/sys/vm/enable_soft_offline or the event is filtered by
+ *     hwpoison_filter(); MADV_HWPOISON folds that case to 0.
+ *
+ * lock: mm->mmap_lock (read mode)
+ *   type: semaphore
+ *   acquired: yes
+ *   released: yes
+ *   desc: Taken for read for MADV_REMOVE, MADV_WILLNEED, MADV_COLD,
+ *     MADV_PAGEOUT, MADV_COLLAPSE, MADV_POPULATE_READ and
+ *     MADV_POPULATE_WRITE, and as the fallback when the per-VMA lock path
+ *     declines. It is dropped and retaken around vfs_fadvise() (WILLNEED on
+ *     regular files), vfs_fallocate() and userfaultfd_remove() (REMOVE, and
+ *     DONTNEED or FREE with UFFD_FEATURE_EVENT_REMOVE), the anon and file
+ *     collapse paths (COLLAPSE) and inside faultin_page_range()
+ *     (POPULATE_*), so the VMA must be looked up again afterwards.
+ *
+ * lock: mm->mmap_lock (write mode; killable)
+ *   type: semaphore
+ *   acquired: yes
+ *   released: yes
+ *   desc: Acquired in killable write mode for behaviors that modify
+ *     vma->vm_flags or split/merge VMAs (MADV_NORMAL, MADV_RANDOM,
+ *     MADV_SEQUENTIAL, MADV_DONTFORK, MADV_DOFORK, MADV_DONTDUMP, MADV_DODUMP,
+ *     MADV_WIPEONFORK, MADV_KEEPONFORK, MADV_MERGEABLE, MADV_UNMERGEABLE,
+ *     MADV_HUGEPAGE, MADV_NOHUGEPAGE). If the acquisition is killed by a
+ *     fatal signal, the syscall returns -EINTR before any VMA is touched.
+ *
+ * lock: per-VMA read lock (vma->vm_refcnt)
+ *   type: custom
+ *   acquired: yes
+ *   released: yes
+ *   desc: Tried first for MADV_DONTNEED, MADV_DONTNEED_LOCKED, MADV_FREE,
+ *     MADV_GUARD_INSTALL and MADV_GUARD_REMOVE via lock_vma_under_rcu(). The
+ *     lock is a reference on the VMA (vm_refcnt), not an rwsem. The per-VMA
+ *     path is taken only when the requested range fits within a single VMA,
+ *     the target mm is the caller's mm, the VMA is not armed with
+ *     userfaultfd, and, for MADV_GUARD_INSTALL on an anonymous VMA, an
+ *     anon_vma is already attached. Otherwise the code falls back to the
+ *     mmap read lock above.
+ *
+ * lock: mmu_gather TLB batch
+ *   type: custom
+ *   acquired: yes
+ *   released: yes
+ *   desc: For MADV_DONTNEED, MADV_DONTNEED_LOCKED and MADV_FREE a single
+ *     tlb_gather_mmu() / tlb_finish_mmu() pair (madvise_init_tlb() and
+ *     madvise_finish_tlb()) wraps the whole syscall, batching TLB invalidation
+ *     across all VMAs in the range. MADV_COLD and MADV_PAGEOUT build a
+ *     short-lived gather inside the handler. MADV_GUARD_INSTALL builds a
+ *     transient gather via zap_vma_range() each time the retry loop clears
+ *     pre-existing pages, and none if the range is already empty.
+ *     MADV_GUARD_REMOVE never gathers.
+ *
+ * lock: mmu_notifier invalidate range
+ *   type: custom
+ *   acquired: yes
+ *   released: yes
+ *   desc: All zap-based paths -- MADV_DONTNEED, MADV_DONTNEED_LOCKED, the
+ *     zap branch of MADV_GUARD_INSTALL via zap_vma_range(), and
+ *     MADV_FREE's own walk -- bracket their work with
+ *     mmu_notifier_invalidate_range_start()/_end() so secondary MMUs (KVM,
+ *     IOMMU SVA, etc.) observe the page clearing.
+ *
+ * signal: Any fatal signal
+ *   direction: receive
+ *   action: return
+ *   condition: Acquiring the mmap write lock or faulting in pages for
+ *     MADV_POPULATE_*
+ *   desc: A pending fatal signal aborts mmap_write_lock_killable() (used by
+ *     the VMA-flag-mutating behaviors) and faultin_page_range() (used by
+ *     MADV_POPULATE_READ and MADV_POPULATE_WRITE), in both cases surfacing as
+ *     -EINTR. Only a fatal signal interrupts these waits, so the task is
+ *     being killed and user space does not normally see the error.
+ *   errno: -EINTR
+ *   timing: during
+ *   restartable: no
+ *
+ * side-effect: modify_state
+ *   target: vma->vm_flags
+ *   condition: Hint-group behaviors (MADV_NORMAL, MADV_RANDOM, MADV_SEQUENTIAL,
+ *     MADV_DONTFORK, MADV_DOFORK, MADV_DONTDUMP, MADV_DODUMP, MADV_WIPEONFORK,
+ *     MADV_KEEPONFORK, MADV_MERGEABLE, MADV_UNMERGEABLE, MADV_HUGEPAGE,
+ *     MADV_NOHUGEPAGE)
+ *   desc: Sets or clears VM_RAND_READ, VM_SEQ_READ, VM_DONTCOPY,
+ *     VM_DONTDUMP, VM_WIPEONFORK, VM_MERGEABLE, VM_HUGEPAGE or VM_NOHUGEPAGE
+ *     on the affected VMAs, splitting or merging VMAs as needed. Reversible
+ *     with the inverse advice (MADV_DOFORK undoes MADV_DONTFORK), except
+ *     that the inverse call's VMA filter still applies (DOFORK rejects
+ *     VM_SPECIAL, DODUMP rejects non-hugetlb VM_SPECIAL or VM_DROPPABLE,
+ *     KEEPONFORK rejects VM_DROPPABLE).
+ *   reversible: yes
+ *
+ * side-effect: free_memory | modify_state | irreversible
+ *   target: page tables and resident pages within the range
+ *   condition: MADV_DONTNEED, MADV_DONTNEED_LOCKED, MADV_FREE
+ *   desc: MADV_DONTNEED zaps PTEs, releasing the pages or swap slots so the
+ *     next access faults in zero-filled anonymous pages or re-reads the
+ *     file. MADV_DONTNEED_LOCKED is identical but tolerates VM_LOCKED.
+ *     MADV_FREE marks anonymous pages lazy-freeable; clean pages may be
+ *     reclaimed under memory pressure and a write before reclaim cancels
+ *     the lazy free. Discarded data cannot be recovered.
+ *   reversible: no
+ *
+ * side-effect: filesystem | irreversible
+ *   target: backing file (FALLOC_FL_PUNCH_HOLE)
+ *   condition: MADV_REMOVE
+ *   desc: Calls vfs_fallocate(FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE) on
+ *     the backing file, deallocating the corresponding file blocks. The hole
+ *     is visible to all mappers of the file and to read(2)/write(2)
+ *     callers; subsequent reads return zero. Filesystem freeze protection,
+ *     i_rwsem and any quota/space accounting are taken by the underlying
+ *     fallocate path.
+ *   reversible: no
+ *
+ * side-effect: modify_state | schedule
+ *   target: LRU lists and page reclaim
+ *   condition: MADV_COLD, MADV_PAGEOUT
+ *   desc: MADV_COLD deactivates the affected pages, moving them to the
+ *     inactive LRU and clearing PG_referenced/PG_young so they are reclaimed
+ *     sooner under pressure. MADV_PAGEOUT additionally calls reclaim_pages()
+ *     to write dirty pages out and drop clean ones synchronously. Page data
+ *     is preserved (rereads will fault in the same content), but the I/O and
+ *     LRU bookkeeping cannot be undone.
+ *   reversible: no
+ *
+ * side-effect: modify_state
+ *   target: page tables (faultin)
+ *   condition: MADV_POPULATE_READ, MADV_POPULATE_WRITE
+ *   desc: Walks the requested range with faultin_page_range(), populating
+ *     PTEs by triggering read or write faults so subsequent accesses do not
+ *     fault. Equivalent to touching every page in the range while suppressing
+ *     SIGBUS/SIGSEGV through the syscall return value. Allocations made by
+ *     faultin are not undone on partial failure.
+ *   reversible: no
+ *
+ * side-effect: modify_state | schedule
+ *   target: transparent hugepage layout
+ *   condition: MADV_COLLAPSE
+ *   desc: Synchronously coalesces base pages in the range into a PMD-sized
+ *     transparent hugepage when the mapping permits. Performs the same page
+ *     migration and zeroing that khugepaged would do asynchronously; the
+ *     range's data is preserved across the collapse.
+ *   reversible: no
+ *
+ * side-effect: free_memory | modify_state | irreversible
+ *   target: PTE marker (PTE_MARKER_GUARD)
+ *   condition: MADV_GUARD_INSTALL, MADV_GUARD_REMOVE
+ *   desc: MADV_GUARD_INSTALL installs PTE_MARKER_GUARD entries that cause
+ *     subsequent accesses to deliver SIGSEGV without consuming physical
+ *     memory; existing pages already mapped in the range are zapped via
+ *     zap_vma_range() before the markers are installed, so any
+ *     prior contents are lost. MADV_GUARD_REMOVE clears the markers but
+ *     does not (and cannot) restore zapped data.
+ *   reversible: no
+ *
+ * side-effect: hardware | irreversible
+ *   target: physical page (memory_failure)
+ *   condition: MADV_HWPOISON
+ *   desc: MADV_HWPOISON marks the affected pages as containing an
+ *     unrecoverable hardware error using the same machine-check path that
+ *     real ECC failures take. This affects physical memory bookkeeping
+ *     kernel-wide, and madvise() has no inverse. The poison can be cleared
+ *     through unpoison_memory() (the hwpoison-inject debugfs interface).
+ *     Intended for testing the memory-failure pipeline; restricted to
+ *     CAP_SYS_ADMIN.
+ *   reversible: no
+ *
+ * side-effect: hardware
+ *   target: physical page (soft_offline_page)
+ *   condition: MADV_SOFT_OFFLINE
+ *   desc: Migrates the contents off the affected pages and removes them from
+ *     the buddy allocator. Page contents are preserved. madvise() has no
+ *     inverse. The pages can be brought back through unpoison_memory() (the
+ *     hwpoison-inject debugfs interface). Intended for testing the
+ *     memory-failure pipeline; restricted to CAP_SYS_ADMIN.
+ *   reversible: no
+ *
+ * side-effect: modify_state
+ *   target: KSM merge state (vm_flags & VM_MERGEABLE)
+ *   condition: MADV_MERGEABLE, MADV_UNMERGEABLE
+ *   desc: Toggles VM_MERGEABLE, the VMA's eligibility for the kernel
+ *     same-page merger. MADV_MERGEABLE lets ksmd later replace identical
+ *     anonymous pages with shared, write-protected copies and is silently
+ *     ignored on KSM-incompatible VMAs. MADV_UNMERGEABLE synchronously
+ *     calls break_ksm(), which faults each KSM page in the range back to an
+ *     exclusive copy, before clearing VM_MERGEABLE. An -ENOMEM from either
+ *     advice is returned as -EAGAIN. The flag toggle is reversible by
+ *     issuing the inverse advice.
+ *   reversible: yes
+ *
+ * side-effect: modify_state
+ *   target: userfaultfd event queue
+ *   condition: MADV_DONTNEED, MADV_DONTNEED_LOCKED, MADV_FREE, MADV_REMOVE
+ *     on a VMA whose userfaultfd context negotiated UFFD_FEATURE_EVENT_REMOVE
+ *   desc: Generates a UFFD_EVENT_REMOVE notification covering the discarded
+ *     range so userfaultfd monitors observing the mapping see the
+ *     invalidation. The event is queued before the discard takes effect; the
+ *     monitor cannot veto it.
+ *   reversible: no
+ *
+ * capability: CAP_SYS_ADMIN
+ *   type: perform_operation
+ *   allows: Inject memory errors via MADV_HWPOISON or MADV_SOFT_OFFLINE
+ *   without: Both behaviors return -EPERM
+ *   condition: Checked at entry to madvise_inject_error() before any pages
+ *     are looked up
+ *
+ * constraint: Page-aligned start
+ *   desc: start must lie on a page boundary; otherwise the call returns
+ *     -EINVAL before any VMA is consulted.
+ *   expr: (start & (PAGE_SIZE - 1)) == 0
+ *
+ * constraint: Length rounded up to PAGE_SIZE
+ *   desc: The effective range length is PAGE_ALIGN(len_in). A non-zero len_in
+ *     that overflows during rounding, or a (start, end) range that wraps,
+ *     is rejected with -EINVAL.
+ *   expr: end = start + PAGE_ALIGN(len_in); end >= start
+ *
+ * constraint: Behavior must be supported
+ *   desc: behavior must be one of the MADV_* values listed under the
+ *     behavior parameter. Behaviors gated by Kconfig (KSM, THP, memory
+ *     failure) are rejected with -EINVAL when the corresponding option is
+ *     disabled in the running kernel.
+ *
+ * constraint: mseal-protected discards
+ *   desc: On 64-bit kernels, a discard operation (FREE, DONTNEED,
+ *     DONTNEED_LOCKED, REMOVE, DONTFORK, WIPEONFORK, GUARD_INSTALL) against
+ *     a sealed anonymous VMA is rejected unless the mapping is currently
+ *     writable -- both VM_WRITE in vm_flags and arch_vma_access_permitted()
+ *     allowing write -- so that mseal(2) cannot be bypassed by instructing
+ *     the kernel to throw the data away. File-backed sealed VMAs and
+ *     writable sealed VMAs are not subject to this restriction.
+ *   expr: !is_discard(behavior) || !vma_is_sealed(vma) ||
+ *     !vma_is_anonymous(vma) || ((vma->vm_flags & VM_WRITE) &&
+ *     arch_vma_access_permitted(vma, true, false, false))
+ *
+ * constraint: MADV_FREE requires anonymous mappings
+ *   desc: MADV_FREE is defined only over anonymous mappings; the handler
+ *     requires vma_is_anonymous() (no vm_ops) and rejects file-backed VMAs,
+ *     including shared anonymous (shmem) VMAs, with -EINVAL.
+ *   expr: vma_is_anonymous(vma)
+ *
+ * constraint: MADV_WIPEONFORK requires private anonymous mappings
+ *   desc: MADV_WIPEONFORK rejects file-backed mappings and shared anonymous
+ *     mappings; only MAP_PRIVATE anonymous VMAs accept it. Both rejections
+ *     surface as -EINVAL.
+ *   expr: !vma->vm_file && !(vma->vm_flags & VM_SHARED)
+ *
+ * constraint: MADV_REMOVE requires a shared file mapping that may be written
+ *   desc: MADV_REMOVE rejects VM_LOCKED VMAs and VMAs without an associated
+ *     file/mapping/host inode with -EINVAL. It rejects VMAs failing
+ *     vma_is_shared_maywrite() (VM_SHARED and VM_MAYWRITE) with -EACCES,
+ *     which covers private file mappings and shared mappings of files not
+ *     opened for writing, but not a PROT_READ MAP_SHARED mapping of a file
+ *     opened O_RDWR.
+ *   expr: !(vma->vm_flags & VM_LOCKED) && vma->vm_file &&
+ *     vma->vm_file->f_mapping && vma->vm_file->f_mapping->host &&
+ *     vma_is_shared_maywrite(vma)
+ *
+ * constraint: MADV_COLD / MADV_PAGEOUT VMA filter
+ *   desc: Both behaviors require LRU-managed pages; they reject VMAs that
+ *     are mlocked, raw-PFN or hugetlb.
+ *   expr: !(vma->vm_flags & (VM_LOCKED | VM_PFNMAP | VM_HUGETLB))
+ *
+ * examples: madvise(p, len, MADV_SEQUENTIAL);  // set VM_SEQ_READ on the VMA
+ *   madvise(p, len, MADV_POPULATE_WRITE);  // prefault writable PTEs
+ *   madvise(p, len, MADV_DONTNEED);        // discard anonymous pages
+ *   madvise(p, len, MADV_GUARD_INSTALL);   // install SIGSEGV guard pages
+ *
+ * notes: Behavior introduction history (mainline): MADV_FREE in 4.5,
+ *   MADV_WIPEONFORK / MADV_KEEPONFORK in 4.14, MADV_COLD / MADV_PAGEOUT in
+ *   5.4, MADV_POPULATE_READ / MADV_POPULATE_WRITE in 5.14,
+ *   MADV_DONTNEED_LOCKED in 5.18, MADV_COLLAPSE in 6.1, MADV_GUARD_INSTALL /
+ *   MADV_GUARD_REMOVE in 6.13. Code that wants to remain portable to older
+ *   kernels must handle -EINVAL gracefully and fall back.
+ *
+ *   process_madvise(2) applies the same advice values to another process
+ *   identified by a pidfd. When the target mm is the caller's own (the
+ *   pidfd refers to the caller), any locally-supported MADV_* value is
+ *   accepted. When the target is a different mm, the behavior must be in
+ *   the non-destructive remote subset (MADV_COLD, MADV_PAGEOUT,
+ *   MADV_WILLNEED, MADV_COLLAPSE) or the call returns -EINVAL, and the
+ *   caller must hold CAP_SYS_NICE.
+ *
+ *   MADV_PAGEOUT on a non-anonymous VM_MAYSHARE mapping is a silent no-op
+ *   returning 0 unless can_do_file_pageout() holds, meaning the caller owns
+ *   the file or is capable over it (file_owner_or_capable(), which honors
+ *   the mount idmap) or may write it (file_permission(MAY_WRITE)). On a
+ *   private file mapping that fails the same test, only anonymous pages are
+ *   paged out. MADV_COLD has no such filter.
+ *
+ *   MADV_GUARD_INSTALL retries up to MAX_MADVISE_GUARD_RETRIES (3) times
+ *   when it loses races with concurrent faulting or khugepaged. If those
+ *   retries are exhausted the handler returns -ERESTARTNOINTR via
+ *   restart_syscall(), which sets TIF_SIGPENDING so the return path runs
+ *   signal handling. madvise() is then transparently re-executed with the
+ *   same arguments, after any handler for a pending signal has run, unless
+ *   a fatal signal terminates the task first. The caller never observes an
+ *   errno from the restart itself and the call appears to make eventual
+ *   forward progress.
+ *
+ *   anon_vma_prepare() failures inside MADV_GUARD_INSTALL bypass the
+ *   ENOMEM-to-EAGAIN translation that applies to the VMA-flag-mutating
+ *   behaviors and surface as -ENOMEM directly.
+ *
+ *   Architecture note: alpha defines MADV_DONTNEED as 6 (not 4) and reserves
+ *   MADV_SPACEAVAIL=5; portable code must use the symbolic names from
+ *   <sys/mman.h>.
+ */
 SYSCALL_DEFINE3(madvise, unsigned long, start, size_t, len_in, int, behavior)
 {
 	return do_madvise(current->mm, start, len_in, behavior);
Signature · 1 line
2.53.0
#20 lore raw

PATCH v5 11/11 kernel/api: add syscall enter/exit tracepoints

In reply to Sasha Levin

Add two tracepoints to the CONFIG_KAPI_RUNTIME_CHECKS syscall validation path so the framework's behavior can be observed without the noise and loss of pr_warn_ratelimited():

kapi_syscall_enter - the spec name, the raw argument values, and a
rendered "name=value" list of the specified parameters (pointer-like values in hex, signed integers and file descriptors in decimal)
kapi_syscall_exit - the spec name, the return value, and whether it
matched the specification (spec_match)

Both fire only for syscalls that have a KAPI specification and live inside the existing CONFIG_KAPI_RUNTIME_CHECKS region, so they exist exactly when the runtime checks do; they compile to no-ops without CONFIG_TRACEPOINTS and stay dormant until enabled. The parameter list is rendered only when the enter tracepoint is enabled.

kapi_syscall_exit is also emitted on the parameter-validation rejection path -- where the validator returns -EINVAL and the real handler is skipped -- with spec_match=0, so every kapi_syscall_enter has a matching exit.

Assisted-by LLM
---
 Documentation/dev-tools/kernel-api-spec.rst | 31 ++++++++
 MAINTAINERS                                 |  1 +
 include/trace/events/kapi.h                 | 74 +++++++++++++++++++
 kernel/api/kernel_api_spec.c                | 79 +++++++++++++++++----
 4 files changed, 173 insertions(+), 12 deletions(-)
 create mode 100644 include/trace/events/kapi.h
Documentation/dev-tools/kernel-api-spec.rst +31 -0
index 95b72060f8ef8..818c9b966a0c0 100644
@@ -312,6 +312,37 @@ specification. Kerneldoc annotations cannot set it, so it is only available to a
     .constraint_type = KAPI_CONSTRAINT_CUSTOM,
     .validate = validate_buffer_size,
 
+Tracepoints
+-----------
+
+When ``CONFIG_KAPI_RUNTIME_CHECKS`` is enabled, the syscall validation path emits
+two ftrace tracepoints (in the ``kapi`` trace system) for every syscall that has a
+specification:
+
+- ``kapi_syscall_enter`` -- fired before parameter validation, recording the spec
+  name, the raw syscall argument values, and -- when the spec provides parameter
+  metadata -- a rendered ``name=value`` list: signed integer and file descriptor
+  values are shown in decimal, all other values in hex, and an unnamed parameter
+  as ``arg``.
+- ``kapi_syscall_exit`` -- fired after the handler returns, or in place of the
+  handler when parameter validation rejects the call (the handler is skipped and
+  ``-EINVAL`` is returned). Records the spec name, the return value, and
+  ``spec_match``: 0 when the parameters were rejected or a successful ``fd`` return
+  was not a valid file descriptor, and 1 otherwise. Error codes missing from the
+  spec do not clear it.
+
+Unlike the ``pr_warn_ratelimited`` violation reports, the tracepoints capture every
+spec'd call rather than only violations, and can be filtered with the usual ftrace
+facilities. They require ``CONFIG_TRACEPOINTS`` and stay dormant
+until enabled::
+
+    # echo 1 > /sys/kernel/tracing/events/kapi/enable
+    # cat /sys/kernel/tracing/trace
+     ...  kapi_syscall_enter: sys_read(fd=3, buf=0x7ffd46780b58, count=0x340)
+     ...  kapi_syscall_exit: sys_read = 832 spec_match=1
+     ...  kapi_syscall_enter: sys_open(filename=0x480300, flags=268435456, mode=0x0)
+     ...  kapi_syscall_exit: sys_open = -22 spec_match=0
+
 DebugFS Interface
 =================
 
MAINTAINERS +1 -0
index 1d9e55b6bf5ff..20020705921a6 100644
@@ -14125,6 +14125,7 @@ S:	Maintained
 F:	Documentation/dev-tools/kernel-api-spec.rst
 F:	include/linux/kapi_syscall.h
 F:	include/linux/kernel_api_spec.h
+F:	include/trace/events/kapi.h
 F:	kernel/api/
 F:	tools/kapi/
 F:	tools/lib/python/kdoc/kdoc_apispec.py
include/trace/events/kapi.h new file +74 -0

74 lines not on this page · raw message

kernel/api/kernel_api_spec.c +67 -12

119 lines not on this page · raw message

Signature · 1 line
2.53.0