* [PATCH v3 01/19] coverage: move gcov and kcov under kernel/coverage/
2026-11-25 2:05 [PATCH v3 00/19] Unify code coverage and add Clang source-based coverage with MC/DC Sasha Levin
@ 2026-11-25 2:05 ` Sasha Levin
2026-11-25 2:05 ` [PATCH v3 10/19] objtool: Remove coverage counter updates from noinstr code Sasha Levin
` (7 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-11-25 2:05 UTC (permalink / raw)
To: linux-kernel
Cc: Alexander Potapenko, Andrew Morton, Andrey Konovalov, Ben Segall,
Bill Wendling, Chuck Wolber, Dietmar Eggemann, Dmitry Vyukov,
Ingo Molnar, Josh Poimboeuf, Juri Lelli, Justin Stitt,
K Prateek Nayak, kasan-dev, linux-doc, llvm, Marco Elver,
Masami Hiramatsu, Mauro Carvalho Chehab, Mel Gorman,
Nathan Chancellor, Nick Desaulniers, Peter Oberparleiter,
Peter Zijlstra, Steven Rostedt, Thomas Gleixner,
Valentin Schneider, Vincent Guittot
The kernel carries more than one code coverage implementation, each
with its own directory, Kconfig menu, build plumbing and debugfs
interface. Start consolidating them by moving the existing
implementations next to each other:
kernel/gcov/ -> kernel/coverage/gcov/
kernel/kcov.c -> kernel/coverage/kcov.c
Both are configured from a new "Code coverage" menu in
kernel/coverage/Kconfig, which is sourced from "Kernel Testing and
Coverage" where the KCOV options used to live. The gcov options move
there from "General architecture-dependent options".
The Kconfig symbols and their dependencies are unchanged, and so are the
per-object compiler flags of kcov.o, which move to
kernel/coverage/Makefile.
The move is visible in one place. When gcov profiles the whole kernel,
the data of its own base.o shows up in debugfs under
kernel/coverage/gcov/ instead of kernel/gcov/. lcov looks for
kernel/gcov/base.gcno there to detect the kernel build directory and no
longer finds it, so "lcov --capture" needs the build directory passed
with -b, as it already does when gcov's own files aren't profiled.
Signed-off-by: Sasha Levin <sashal@kernel.org>
Reviewed-by: Peter Oberparleiter <oberpar@linux.ibm.com> # gcov
Reviewed-by: Nathan Chancellor <nathan@kernel.org>
---
MAINTAINERS | 8 +++-
arch/Kconfig | 2 -
include/linux/sched.h | 2 +-
kernel/Makefile | 15 +------
kernel/coverage/Kconfig | 65 +++++++++++++++++++++++++++
kernel/coverage/Makefile | 16 +++++++
kernel/{ => coverage}/gcov/Kconfig | 0
kernel/{ => coverage}/gcov/Makefile | 0
kernel/{ => coverage}/gcov/base.c | 0
kernel/{ => coverage}/gcov/clang.c | 2 +-
kernel/{ => coverage}/gcov/fs.c | 0
kernel/{ => coverage}/gcov/gcc_4_7.c | 0
kernel/{ => coverage}/gcov/gcc_base.c | 0
kernel/{ => coverage}/gcov/gcov.h | 0
kernel/{ => coverage}/kcov.c | 0
lib/Kconfig.debug | 59 +-----------------------
tools/unittests/test_cmatch.py | 2 +-
17 files changed, 92 insertions(+), 79 deletions(-)
create mode 100644 kernel/coverage/Kconfig
create mode 100644 kernel/coverage/Makefile
rename kernel/{ => coverage}/gcov/Kconfig (100%)
rename kernel/{ => coverage}/gcov/Makefile (100%)
rename kernel/{ => coverage}/gcov/base.c (100%)
rename kernel/{ => coverage}/gcov/clang.c (99%)
rename kernel/{ => coverage}/gcov/fs.c (100%)
rename kernel/{ => coverage}/gcov/gcc_4_7.c (100%)
rename kernel/{ => coverage}/gcov/gcc_base.c (100%)
rename kernel/{ => coverage}/gcov/gcov.h (100%)
rename kernel/{ => coverage}/kcov.c (100%)
diff --git a/MAINTAINERS b/MAINTAINERS
index 44540a1eb2b80..06caae6d28cf5 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -11172,7 +11172,9 @@ GCOV BASED KERNEL PROFILING
M: Peter Oberparleiter <oberpar@linux.ibm.com>
S: Maintained
F: Documentation/dev-tools/gcov.rst
-F: kernel/gcov/
+F: kernel/coverage/Kconfig
+F: kernel/coverage/Makefile
+F: kernel/coverage/gcov/
F: scripts/Makefile.gcov
GDB KERNEL DEBUGGING HELPER SCRIPTS
@@ -14406,7 +14408,9 @@ B: https://bugzilla.kernel.org/buglist.cgi?component=Sanitizers&product=Memory%2
F: Documentation/dev-tools/kcov.rst
F: include/linux/kcov.h
F: include/uapi/linux/kcov.h
-F: kernel/kcov.c
+F: kernel/coverage/Kconfig
+F: kernel/coverage/Makefile
+F: kernel/coverage/kcov.c
F: scripts/Makefile.kcov
KCSAN
diff --git a/arch/Kconfig b/arch/Kconfig
index 1163736de1f99..057ada4747387 100644
--- a/arch/Kconfig
+++ b/arch/Kconfig
@@ -1769,8 +1769,6 @@ config ARCH_VMLINUX_NEEDS_RELOCS
config HAVE_GENERIC_TIF_BITS
bool
-source "kernel/gcov/Kconfig"
-
source "scripts/gcc-plugins/Kconfig"
config FUNCTION_ALIGNMENT_4B
diff --git a/include/linux/sched.h b/include/linux/sched.h
index e4f6323d78555..615e4c1bacd61 100644
--- a/include/linux/sched.h
+++ b/include/linux/sched.h
@@ -1538,7 +1538,7 @@ struct task_struct {
#endif /* CONFIG_TRACING */
#ifdef CONFIG_KCOV
- /* See kernel/kcov.c for more details. */
+ /* See kernel/coverage/kcov.c for more details. */
/* Coverage collection mode enabled for this task (0 if disabled): */
unsigned int kcov_mode;
diff --git a/kernel/Makefile b/kernel/Makefile
index 4ff92e24680c5..50bf37a26bae3 100644
--- a/kernel/Makefile
+++ b/kernel/Makefile
@@ -35,18 +35,6 @@ KCSAN_SANITIZE_softirq.o = n
# and produce insane amounts of uninteresting coverage.
KCOV_INSTRUMENT_extable.o := n
KCOV_INSTRUMENT_stacktrace.o := n
-# Don't self-instrument.
-KCOV_INSTRUMENT_kcov.o := n
-# If sanitizers detect any issues in kcov, it may lead to recursion
-# via printk, etc.
-KASAN_SANITIZE_kcov.o := n
-KCSAN_SANITIZE_kcov.o := n
-UBSAN_SANITIZE_kcov.o := n
-KMSAN_SANITIZE_kcov.o := n
-
-CONTEXT_ANALYSIS_kcov.o := y
-CFLAGS_kcov.o := $(call cc-option, -fno-conserve-stack) -fno-stack-protector
-
obj-y += sched/
obj-y += locking/
obj-y += power/
@@ -96,8 +84,7 @@ obj-$(CONFIG_IKHEADERS) += kheaders.o
obj-$(CONFIG_SMP) += stop_machine.o
obj-$(CONFIG_AUDIT) += audit.o auditfilter.o
obj-$(CONFIG_AUDITSYSCALL) += auditsc.o audit_watch.o audit_fsnotify.o audit_tree.o
-obj-$(CONFIG_GCOV_KERNEL) += gcov/
-obj-$(CONFIG_KCOV) += kcov.o
+obj-y += coverage/
obj-$(CONFIG_KPROBES) += kprobes.o
obj-$(CONFIG_FAIL_FUNCTION) += fail_function.o
obj-$(CONFIG_KGDB) += debug/
diff --git a/kernel/coverage/Kconfig b/kernel/coverage/Kconfig
new file mode 100644
index 0000000000000..dd90b6a61ae65
--- /dev/null
+++ b/kernel/coverage/Kconfig
@@ -0,0 +1,65 @@
+# SPDX-License-Identifier: GPL-2.0-only
+menu "Code coverage"
+
+source "kernel/coverage/gcov/Kconfig"
+
+config ARCH_HAS_KCOV
+ bool
+ help
+ An architecture should select this when it can successfully
+ build and run with CONFIG_KCOV. This typically requires
+ disabling instrumentation for some early boot code.
+
+config KCOV
+ bool "Code coverage for fuzzing"
+ depends on ARCH_HAS_KCOV
+ depends on !ARCH_WANTS_NO_INSTR || HAVE_NOINSTR_HACK || \
+ GCC_VERSION >= 120000 || CC_IS_CLANG
+ select DEBUG_FS
+ select OBJTOOL if HAVE_NOINSTR_HACK
+ help
+ KCOV exposes kernel code coverage information in a form suitable
+ for coverage-guided fuzzing (randomized testing).
+
+ For more details, see Documentation/dev-tools/kcov.rst.
+
+config KCOV_ENABLE_COMPARISONS
+ bool "Enable comparison operands collection by KCOV"
+ depends on KCOV
+ depends on $(cc-option,-fsanitize-coverage=trace-cmp)
+ help
+ KCOV also exposes operands of every comparison in the instrumented
+ code along with operand sizes and PCs of the comparison instructions.
+ These operands can be used by fuzzing engines to improve the quality
+ of fuzzing coverage.
+
+config KCOV_INSTRUMENT_ALL
+ bool "Instrument all code by default"
+ depends on KCOV
+ default y
+ help
+ If you are doing generic system call fuzzing (like e.g. syzkaller),
+ then you will want to instrument the whole kernel and you should
+ say y here. If you are doing more targeted fuzzing (like e.g.
+ filesystem fuzzing with AFL) then you will want to enable coverage
+ for more specific subsets of files, and should say n here.
+
+config KCOV_IRQ_AREA_SIZE
+ hex "Size of interrupt coverage collection area in words"
+ depends on KCOV
+ range 0x80 0x1000000
+ default 0x40000
+ help
+ KCOV uses preallocated areas to collect coverage from soft
+ interrupts. This specifies the size of those areas in the
+ number of unsigned long words.
+
+config KCOV_SELFTEST
+ bool "Perform short selftests on boot"
+ depends on KCOV
+ help
+ Run short KCOV coverage collection selftests on boot.
+ On test failure, causes the kernel to panic. Recommended to be
+ enabled, ensuring critical functionality works as intended.
+
+endmenu
diff --git a/kernel/coverage/Makefile b/kernel/coverage/Makefile
new file mode 100644
index 0000000000000..a4cd8cc18d9bc
--- /dev/null
+++ b/kernel/coverage/Makefile
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: GPL-2.0
+
+obj-$(CONFIG_GCOV_KERNEL) += gcov/
+obj-$(CONFIG_KCOV) += kcov.o
+
+# Don't self-instrument.
+KCOV_INSTRUMENT_kcov.o := n
+# If sanitizers detect any issues in kcov, it may lead to recursion
+# via printk, etc.
+KASAN_SANITIZE_kcov.o := n
+KCSAN_SANITIZE_kcov.o := n
+UBSAN_SANITIZE_kcov.o := n
+KMSAN_SANITIZE_kcov.o := n
+
+CONTEXT_ANALYSIS_kcov.o := y
+CFLAGS_kcov.o := $(call cc-option, -fno-conserve-stack) -fno-stack-protector
diff --git a/kernel/gcov/Kconfig b/kernel/coverage/gcov/Kconfig
similarity index 100%
rename from kernel/gcov/Kconfig
rename to kernel/coverage/gcov/Kconfig
diff --git a/kernel/gcov/Makefile b/kernel/coverage/gcov/Makefile
similarity index 100%
rename from kernel/gcov/Makefile
rename to kernel/coverage/gcov/Makefile
diff --git a/kernel/gcov/base.c b/kernel/coverage/gcov/base.c
similarity index 100%
rename from kernel/gcov/base.c
rename to kernel/coverage/gcov/base.c
diff --git a/kernel/gcov/clang.c b/kernel/coverage/gcov/clang.c
similarity index 99%
rename from kernel/gcov/clang.c
rename to kernel/coverage/gcov/clang.c
index fd98ced0e51d2..e979e8983dce8 100644
--- a/kernel/gcov/clang.c
+++ b/kernel/coverage/gcov/clang.c
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (C) 2019 Google, Inc.
- * modified from kernel/gcov/gcc_4_7.c
+ * modified from kernel/coverage/gcov/gcc_4_7.c
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
diff --git a/kernel/gcov/fs.c b/kernel/coverage/gcov/fs.c
similarity index 100%
rename from kernel/gcov/fs.c
rename to kernel/coverage/gcov/fs.c
diff --git a/kernel/gcov/gcc_4_7.c b/kernel/coverage/gcov/gcc_4_7.c
similarity index 100%
rename from kernel/gcov/gcc_4_7.c
rename to kernel/coverage/gcov/gcc_4_7.c
diff --git a/kernel/gcov/gcc_base.c b/kernel/coverage/gcov/gcc_base.c
similarity index 100%
rename from kernel/gcov/gcc_base.c
rename to kernel/coverage/gcov/gcc_base.c
diff --git a/kernel/gcov/gcov.h b/kernel/coverage/gcov/gcov.h
similarity index 100%
rename from kernel/gcov/gcov.h
rename to kernel/coverage/gcov/gcov.h
diff --git a/kernel/kcov.c b/kernel/coverage/kcov.c
similarity index 100%
rename from kernel/kcov.c
rename to kernel/coverage/kcov.c
diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 2d22638ec13a6..bb939219f4cb4 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -2192,64 +2192,7 @@ config FAULT_INJECTION_STACKTRACE_FILTER
help
Provide stacktrace filter for fault-injection capabilities
-config ARCH_HAS_KCOV
- bool
- help
- An architecture should select this when it can successfully
- build and run with CONFIG_KCOV. This typically requires
- disabling instrumentation for some early boot code.
-
-config KCOV
- bool "Code coverage for fuzzing"
- depends on ARCH_HAS_KCOV
- depends on !ARCH_WANTS_NO_INSTR || HAVE_NOINSTR_HACK || \
- GCC_VERSION >= 120000 || CC_IS_CLANG
- select DEBUG_FS
- select OBJTOOL if HAVE_NOINSTR_HACK
- help
- KCOV exposes kernel code coverage information in a form suitable
- for coverage-guided fuzzing (randomized testing).
-
- For more details, see Documentation/dev-tools/kcov.rst.
-
-config KCOV_ENABLE_COMPARISONS
- bool "Enable comparison operands collection by KCOV"
- depends on KCOV
- depends on $(cc-option,-fsanitize-coverage=trace-cmp)
- help
- KCOV also exposes operands of every comparison in the instrumented
- code along with operand sizes and PCs of the comparison instructions.
- These operands can be used by fuzzing engines to improve the quality
- of fuzzing coverage.
-
-config KCOV_INSTRUMENT_ALL
- bool "Instrument all code by default"
- depends on KCOV
- default y
- help
- If you are doing generic system call fuzzing (like e.g. syzkaller),
- then you will want to instrument the whole kernel and you should
- say y here. If you are doing more targeted fuzzing (like e.g.
- filesystem fuzzing with AFL) then you will want to enable coverage
- for more specific subsets of files, and should say n here.
-
-config KCOV_IRQ_AREA_SIZE
- hex "Size of interrupt coverage collection area in words"
- depends on KCOV
- range 0x80 0x1000000
- default 0x40000
- help
- KCOV uses preallocated areas to collect coverage from soft
- interrupts. This specifies the size of those areas in the
- number of unsigned long words.
-
-config KCOV_SELFTEST
- bool "Perform short selftests on boot"
- depends on KCOV
- help
- Run short KCOV coverage collection selftests on boot.
- On test failure, causes the kernel to panic. Recommended to be
- enabled, ensuring critical functionality works as intended.
+source "kernel/coverage/Kconfig"
menuconfig RUNTIME_TESTING_MENU
bool "Runtime Testing"
diff --git a/tools/unittests/test_cmatch.py b/tools/unittests/test_cmatch.py
index 109141cd2ab8d..06f9c61572e2e 100755
--- a/tools/unittests/test_cmatch.py
+++ b/tools/unittests/test_cmatch.py
@@ -706,7 +706,7 @@ class TestSubWithLocalXforms(TestCaseDiff):
def test_struct_kcov(self):
"""
- Test a struct from kernel/kcov.c.
+ Test a struct from kernel/coverage/kcov.c.
"""
line = """
struct kcov {
--
2.53.0
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v3 10/19] objtool: Remove coverage counter updates from noinstr code
2026-11-25 2:05 [PATCH v3 00/19] Unify code coverage and add Clang source-based coverage with MC/DC Sasha Levin
2026-11-25 2:05 ` [PATCH v3 01/19] coverage: move gcov and kcov under kernel/coverage/ Sasha Levin
@ 2026-11-25 2:05 ` Sasha Levin
2026-11-25 2:05 ` [PATCH v3 11/19] objtool: Point the remaining coverage accesses in noinstr code at a sink Sasha Levin
` (6 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-11-25 2:05 UTC (permalink / raw)
To: linux-kernel
Cc: Alexander Potapenko, Andrey Konovalov, Bill Wendling,
Chuck Wolber, Dmitry Vyukov, Josh Poimboeuf, Justin Stitt,
kasan-dev, llvm, Marco Elver, Masami Hiramatsu, Nathan Chancellor,
Nick Desaulniers, Peter Oberparleiter, Peter Zijlstra,
Thomas Gleixner
gcov and Clang's source-based code coverage update their counters
inline, with an instruction like
lock addq $0x1,__gcov0.foo(%rip)
rather than by calling into a runtime the way KCOV does. noinstr
functions aren't instrumented themselves: noinstr implies __no_profile
since commit 380d53c45ff2 ("compiler_attributes.h: define __no_profile,
add to noinstr"). But the compilers add the counter updates before
inlining, and the attribute doesn't cover what gets inlined into a
function, so the counter updates of every inlined function come along,
whether it is __always_inline or not. An x86-64 defconfig kernel with
KVM, built with GCC 16 and gcov for the whole kernel, has 1823 of them
in 108 noinstr functions of vmlinux and 106 more in the KVM modules.
noinstr code runs where the kernel can't take an exception yet [1], and
a counter update is a store, which can cause one. On x86 that is a data
breakpoint. With gcov profiling the whole kernel, exc_debug_kernel()
updates a counter before it has read and cleared DR7, so with a data
breakpoint on that counter the next kernel #DB never returns: the
handler keeps interrupting itself. On v7.4-rc4, a guest with one CPU
hangs that way once a second breakpoint, on jiffies_64, fires.
exc_page_fault() updates a counter right before it reads CR2, which is
lost if the #DB taken there faults.
The data that such code touches is kept away from data breakpoints by
hand, see within_cpu_entry() and for example commit 3943abf2dbfa
("x86/debug: Prevent data breakpoints on cpu_dr7"). That doesn't work
for coverage counters: there are thousands of them, and with gcov they
are ordinary variables spread over .bss.
The compilers could drop the instrumentation that ends up in a
no_profile_instrument_function function after inlining, but neither
does. So have objtool remove the counter updates from noinstr code,
under --hacks=noinstr, which already removes the KCOV calls that
compilers leave there. An update of a counter has no other output than
the arithmetic flags, which nothing uses: the only reader after one of
them is native_save_fl(), which is after the interrupt flag. Replace
them with NOPs. That covers everything GCC generates with the atomic
counter updates that the kernel asks for (-fprofile-update=prefer-atomic).
Clang needs more, which the next patch adds.
A counter is recognized when the relocation names it or the section
that Clang's source-based code coverage keeps its counters in. gcov's
counters are local objects in .bss though, referenced through the
section like the objects next to them, where an address inside a
counter can also be the end of the object in front of it or the base of
an indexed access to a neighbour. There, only an instruction that reads
or writes the memory at that very address is taken for an access to a
counter. Those are the instructions with a one byte opcode and a memory
operand without a base and an index register, lea aside. The compilers
use nothing else on the counters, and the longer opcodes include bit
tests that reach beyond their operand and instructions that only use
its address.
Like the KCOV calls, the counter updates are removed from all the code
in the noinstr sections, including the instrumentation_begin() and
instrumentation_end() sections of noinstr functions. That keeps this
independent of the control flow, so it works on single objects and
modules as well. The cost is that a function which gets inlined into
noinstr code no longer counts the executions that come through it.
Select OBJTOOL for gcov like KCOV does, for the configurations that
don't run objtool otherwise.
This is limited to x86-64, the only architecture with
HAVE_NOINSTR_HACK. Nothing changes for the others.
[1] https://lore.kernel.org/all/20210614190700.GF68749@worktop.programming.kicks-ass.net/
Suggested-by: Josh Poimboeuf <jpoimboe@kernel.org>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---
kernel/coverage/Kconfig | 1 +
tools/objtool/arch/x86/decode.c | 121 ++++++++++++++++++++-
tools/objtool/check.c | 154 +++++++++++++++++++++++++++
tools/objtool/include/objtool/arch.h | 2 +
tools/objtool/include/objtool/elf.h | 1 +
5 files changed, 277 insertions(+), 2 deletions(-)
diff --git a/kernel/coverage/Kconfig b/kernel/coverage/Kconfig
index d16fa049995c6..6e70065be06b9 100644
--- a/kernel/coverage/Kconfig
+++ b/kernel/coverage/Kconfig
@@ -42,6 +42,7 @@ config GCOV_KERNEL
bool "gcov-based kernel profiling"
depends on DEBUG_FS
select CONSTRUCTORS
+ select OBJTOOL if HAVE_NOINSTR_HACK
help
This option enables gcov-based code profiling (e.g. for code coverage
measurements), with GCC or Clang. The coverage data of the kernel
diff --git a/tools/objtool/arch/x86/decode.c b/tools/objtool/arch/x86/decode.c
index 1b387d5a195ba..6416426a89326 100644
--- a/tools/objtool/arch/x86/decode.c
+++ b/tools/objtool/arch/x86/decode.c
@@ -97,6 +97,112 @@ s64 arch_insn_adjusted_addend(struct instruction *insn, struct reloc *reloc)
return phys_to_virt(addend);
}
+/*
+ * Decode @insn, if it has a memory operand with @reloc as its displacement.
+ */
+static bool decode_mem_reloc(struct instruction *insn, struct reloc *reloc,
+ struct insn *ins)
+{
+ if (insn_decode(ins, insn->sec->data->d_buf + insn->offset, insn->len,
+ INSN_MODE_64) < 0)
+ return false;
+
+ return ins->modrm.nbytes && X86_MODRM_MOD(ins->modrm.value) != 3 &&
+ ins->displacement.nbytes == 4 &&
+ reloc_offset(reloc) == insn->offset + insn_offset_displacement(ins);
+}
+
+static bool has_seg_base(struct insn *ins)
+{
+ insn_byte_t p;
+
+ for_each_insn_prefix(ins, p) {
+ if (p == 0x64 || p == 0x65)
+ return true;
+ }
+
+ return false;
+}
+
+/* An instruction with a one byte opcode */
+static bool is_legacy_insn(struct insn *ins)
+{
+ return !ins->vex_prefix.nbytes && !insn_is_rex2(ins) &&
+ ins->opcode.nbytes == 1;
+}
+
+/*
+ * An add, or, adc, sbb, and, sub, xor, inc or dec of a memory operand: these
+ * write their operand and the flags, and nothing else.
+ */
+static bool is_mem_update(struct insn *ins)
+{
+ u8 modrm_reg = X86_MODRM_REG(ins->modrm.value);
+ u8 op = ins->opcode.bytes[0];
+
+ if (!is_legacy_insn(ins))
+ return false;
+
+ /* <op> r/m, reg: the next one up, 0x38, is cmp */
+ if (op < 0x38 && !(op & 0x06))
+ return true;
+
+ switch (op) {
+ case 0x80: case 0x81: case 0x83: /* <op> r/m, imm: 7 is cmp */
+ return modrm_reg != 7;
+ case 0xfe: case 0xff: /* inc/dec r/m */
+ return modrm_reg <= 1;
+ }
+
+ return false;
+}
+
+/*
+ * Does @insn access the memory that @reloc stands for, and nothing else: is
+ * @reloc the address of a memory operand with no base and no index register,
+ * of an instruction that reads or writes its operand?
+ *
+ * Of the instructions with a one byte opcode, lea is the only one that
+ * doesn't. The ones with longer opcodes are left out: among them are bit
+ * tests that reach beyond their operand and instructions that only use its
+ * address, and the compilers don't use any of them on coverage counters.
+ */
+bool arch_insn_is_mem_direct(struct instruction *insn, struct reloc *reloc)
+{
+ struct insn ins;
+
+ if (!decode_mem_reloc(insn, reloc, &ins) || ins.addr_bytes != 8)
+ return false;
+
+ if (!is_legacy_insn(&ins) || ins.opcode.bytes[0] == 0x8d)
+ return false;
+
+ /* %fs and %gs add their base to the address */
+ if (has_seg_base(&ins))
+ return false;
+
+ if (insn_rip_relative(&ins))
+ return arch_pc_relative_reloc(reloc);
+
+ /* An absolute address takes a SIB byte without a base and an index */
+ return !arch_pc_relative_reloc(reloc) &&
+ ins.sib.nbytes && X86_MODRM_MOD(ins.modrm.value) == 0 &&
+ X86_SIB_BASE(ins.sib.value) == 5 &&
+ X86_SIB_INDEX(ins.sib.value) == 4 &&
+ !X86_REX_X(ins.rex_prefix.value);
+}
+
+/*
+ * Does @insn do nothing but update the memory operand that @reloc points to,
+ * and the flags? If those aren't used, a NOP can replace it.
+ */
+bool arch_insn_is_mem_update(struct instruction *insn, struct reloc *reloc)
+{
+ struct insn ins;
+
+ return decode_mem_reloc(insn, reloc, &ins) && is_mem_update(&ins);
+}
+
static void scan_for_insn(struct section *sec, unsigned long offset,
unsigned long *insn_off, unsigned int *insn_len)
{
@@ -846,15 +952,26 @@ void arch_initial_func_cfi_state(struct cfi_init_state *state)
const char *arch_nop_insn(int len)
{
- static const char nops[5][5] = {
+ /* Up to the longest instruction, which takes two NOPs */
+ static const char nops[15][15] = {
{ BYTES_NOP1 },
{ BYTES_NOP2 },
{ BYTES_NOP3 },
{ BYTES_NOP4 },
{ BYTES_NOP5 },
+ { BYTES_NOP6 },
+ { BYTES_NOP7 },
+ { BYTES_NOP8 },
+ { BYTES_NOP9 },
+ { BYTES_NOP10 },
+ { BYTES_NOP11 },
+ { BYTES_NOP11, BYTES_NOP1 },
+ { BYTES_NOP11, BYTES_NOP2 },
+ { BYTES_NOP11, BYTES_NOP3 },
+ { BYTES_NOP11, BYTES_NOP4 },
};
- if (len < 1 || len > 5) {
+ if (len < 1 || len > 15) {
ERROR("invalid NOP size: %d\n", len);
return NULL;
}
diff --git a/tools/objtool/check.c b/tools/objtool/check.c
index 4ef5bf97d3335..85cb21b41508b 100644
--- a/tools/objtool/check.c
+++ b/tools/objtool/check.c
@@ -4,6 +4,7 @@
*/
#define _GNU_SOURCE /* memmem() */
+#include <ctype.h>
#include <fnmatch.h>
#include <string.h>
#include <stdlib.h>
@@ -407,6 +408,7 @@ static void *cfi_hash_alloc(unsigned long size)
static unsigned long nr_insns;
static unsigned long nr_insns_visited;
+static unsigned long nr_coverage_nops;
/*
* Call the arch-specific instruction decoder for all the instructions and add
@@ -2494,6 +2496,31 @@ static bool is_profiling_func(const char *name)
return false;
}
+/*
+ * Return true if sym is a code coverage counter: GCC's __gcov<N>.* and Clang's
+ * __llvm_gcov_ctr* gcov counters, or the counters and MC/DC bitmaps of Clang's
+ * source-based code coverage, which have sections of their own.
+ */
+static bool is_coverage_counter(struct symbol *sym)
+{
+ const char *name = sym->name;
+
+ if (!strcmp(sym->sec->name, "__llvm_prf_cnts") ||
+ !strcmp(sym->sec->name, "__llvm_prf_bits"))
+ return true;
+
+ if (strstarts(name, "__llvm_gcov_ctr"))
+ return true;
+
+ if (!strstarts(name, "__gcov") || !isdigit((unsigned char)name[6]))
+ return false;
+
+ for (name += 6; isdigit((unsigned char)*name); name++)
+ ;
+
+ return *name == '.';
+}
+
static int classify_symbols(struct objtool_file *file)
{
struct symbol *func;
@@ -2503,6 +2530,9 @@ static int classify_symbols(struct objtool_file *file)
if (is_notype_sym(func) && strstarts(func->name, ".L"))
func->local_label = true;
+ if (is_coverage_counter(func))
+ func->coverage_counter = true;
+
if (!is_global_sym(func))
continue;
@@ -2609,6 +2639,126 @@ static bool alts_needed(void)
opts.checksum;
}
+__weak bool arch_insn_is_mem_direct(struct instruction *insn, struct reloc *reloc)
+{
+ return false;
+}
+
+__weak bool arch_insn_is_mem_update(struct instruction *insn, struct reloc *reloc)
+{
+ return false;
+}
+
+static struct reloc *insn_next_reloc(struct objtool_file *file,
+ struct instruction *insn,
+ struct reloc *reloc)
+{
+ unsigned long offset = reloc_offset(reloc) + 1;
+
+ return find_reloc_by_dest_range(file->elf, insn->sec, offset,
+ insn->offset + insn->len - offset);
+}
+
+/* Where @reloc of @insn points to, in the section of its symbol */
+static s64 insn_reloc_dest(struct instruction *insn, struct reloc *reloc)
+{
+ s64 offset = reloc->sym->offset + reloc_addend(reloc);
+
+ if (arch_pc_relative_reloc(reloc))
+ offset += insn->offset + insn->len - reloc_offset(reloc);
+
+ return offset;
+}
+
+/*
+ * Does @reloc refer to code coverage counters?
+ *
+ * It does when it names them, or the section that Clang's source-based code
+ * coverage keeps them in. The counters of gcov are local objects in .bss
+ * though, which are referenced through that section, just like their
+ * neighbours. An address in such a counter may as well be the end of the
+ * object in front of it, or the base of an indexed access to a neighbour, so
+ * there only an access to the memory at that very address counts.
+ */
+static bool is_coverage_reloc(struct objtool_file *file,
+ struct instruction *insn, struct reloc *reloc)
+{
+ struct symbol *sym = reloc->sym;
+ unsigned long offset;
+ s64 dest;
+
+ if (reloc_type(reloc) != R_DATA32 &&
+ !arch_absolute_reloc(file->elf, reloc))
+ return false;
+
+ dest = insn_reloc_dest(insn, reloc);
+ if (dest < 0)
+ return false;
+
+ offset = dest;
+
+ if (sym->coverage_counter) {
+ if (sym->len)
+ return offset >= sym->offset &&
+ offset < sym->offset + sym->len;
+
+ return offset <= sec_size(sym->sec);
+ }
+
+ if (!is_sec_sym(sym) || !arch_insn_is_mem_direct(insn, reloc))
+ return false;
+
+ sym = find_symbol_containing(sym->sec, offset);
+
+ return sym && sym->coverage_counter;
+}
+
+static bool is_coverage_update(struct objtool_file *file,
+ struct instruction *insn, struct reloc *reloc)
+{
+ return !insn_next_reloc(file, insn, reloc) &&
+ is_coverage_reloc(file, insn, reloc) &&
+ arch_insn_is_mem_update(insn, reloc);
+}
+
+/*
+ * gcov and Clang's source-based code coverage update their counters inline,
+ * and the compilers add those updates before inlining. The counter updates of
+ * a function that gets inlined into a noinstr function come along, even though
+ * the noinstr function is __no_profile.
+ *
+ * Remove them. An update of a counter has no other output than the flags, which
+ * the compilers don't use, so a NOP can take its place.
+ */
+static int remove_noinstr_coverage(struct objtool_file *file)
+{
+ struct instruction *insn;
+ struct section *sec;
+ struct reloc *reloc;
+
+ for_each_sec(file->elf, sec) {
+ if (!sec->noinstr)
+ continue;
+
+ sec_for_each_insn(file, sec, insn) {
+ reloc = insn_reloc(file, insn);
+ if (!reloc || !is_coverage_update(file, insn, reloc))
+ continue;
+
+ set_reloc_type(file->elf, reloc, R_NONE);
+
+ if (elf_write_insn(file->elf, insn->sec, insn->offset,
+ insn->len, arch_nop_insn(insn->len)))
+ return -1;
+
+ insn->type = INSN_NOP;
+ nr_coverage_nops++;
+ }
+ }
+
+ return 0;
+}
+
int decode_file(struct objtool_file *file)
{
arch_initial_func_cfi_state(&initial_func_cfi);
@@ -2686,6 +2836,9 @@ int decode_file(struct objtool_file *file)
if (read_annotate(file, __annotate_late))
return -1;
+ if (opts.hack_noinstr && remove_noinstr_coverage(file))
+ return -1;
+
return 0;
}
@@ -4950,6 +5103,7 @@ int check(struct objtool_file *file)
printf("nr_cfi: %ld\n", nr_cfi);
printf("nr_cfi_reused: %ld\n", nr_cfi_reused);
printf("nr_cfi_cache: %ld\n", nr_cfi_cache);
+ printf("nr_coverage_nops: %ld\n", nr_coverage_nops);
}
out:
diff --git a/tools/objtool/include/objtool/arch.h b/tools/objtool/include/objtool/arch.h
index 96d828a8401fd..c8f89da36bfb6 100644
--- a/tools/objtool/include/objtool/arch.h
+++ b/tools/objtool/include/objtool/arch.h
@@ -101,6 +101,8 @@ bool arch_is_embedded_insn(struct symbol *sym);
int arch_rewrite_retpolines(struct objtool_file *file);
bool arch_pc_relative_reloc(struct reloc *reloc);
+bool arch_insn_is_mem_direct(struct instruction *insn, struct reloc *reloc);
+bool arch_insn_is_mem_update(struct instruction *insn, struct reloc *reloc);
bool arch_absolute_reloc(struct elf *elf, struct reloc *reloc);
unsigned int arch_reloc_size(struct reloc *reloc);
diff --git a/tools/objtool/include/objtool/elf.h b/tools/objtool/include/objtool/elf.h
index a82517a76a0f6..202e77f26785a 100644
--- a/tools/objtool/include/objtool/elf.h
+++ b/tools/objtool/include/objtool/elf.h
@@ -84,6 +84,7 @@ struct symbol {
u8 return_thunk : 1;
u8 fentry : 1;
u8 profiling_func : 1;
+ u8 coverage_counter : 1;
u8 warned : 1;
u8 embedded_insn : 1;
u8 local_label : 1;
--
2.53.0
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v3 11/19] objtool: Point the remaining coverage accesses in noinstr code at a sink
2026-11-25 2:05 [PATCH v3 00/19] Unify code coverage and add Clang source-based coverage with MC/DC Sasha Levin
2026-11-25 2:05 ` [PATCH v3 01/19] coverage: move gcov and kcov under kernel/coverage/ Sasha Levin
2026-11-25 2:05 ` [PATCH v3 10/19] objtool: Remove coverage counter updates from noinstr code Sasha Levin
@ 2026-11-25 2:05 ` Sasha Levin
2026-11-25 2:05 ` [PATCH v3 12/19] x86/sev: Stop excluding noinstr.o from code coverage Sasha Levin
` (5 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-11-25 2:05 UTC (permalink / raw)
To: linux-kernel
Cc: Bill Wendling, Chuck Wolber, Josh Poimboeuf, Justin Stitt, llvm,
Marco Elver, Masami Hiramatsu, Nathan Chancellor,
Nick Desaulniers, Peter Zijlstra, Thomas Gleixner
Not every reference to a coverage counter in noinstr code is an update
that a NOP can replace. Clang's source-based code coverage may load
the address of one of several counters into a register and update the
counter through it:
movq $__llvm_prf_cnts+0x20,%rax
...
lock incq (%rax)
and its MC/DC bitmap updates load the byte of the bitmap first, to test
the bit. The update at the end can be replaced by a NOP, the load can't:
movzbl __llvm_prf_bits(%rdi),%ecx
btl %esi,%ecx
jae ...
lock orb %r8b,__llvm_prf_bits(%rdi)
Clang's gcov, whose counter updates aren't atomic, loads a counter,
keeps it in a register across a loop and stores it back. Removing these
takes following the values through the registers.
Change where they point instead. Retarget the relocation of every such
access to a sink, a new .bss section that objtool adds to the object,
and leave the instructions as they are. The counters of every function
are mapped to the same place in the sink with their offsets kept, and
the sink has room for the largest of them on either side of that place,
so that an indexed access stays within it whether it is relative to the
start of its counters or to their end.
With the configuration of the previous patch, a kernel built with
Clang 22, source-based code coverage and MC/DC gets 3319 counter updates
in noinstr code replaced by NOPs and 229 accesses pointed at a sink of
2048 bytes. With Clang's gcov that is 2020 and 177. GCC's atomic counter
updates don't need a sink.
Clang's gcov can also update a counter through its address in a
register, which it loads as an immediate. Such an address looks just
like the end of the object in front of the counter, so those are left
alone. The kernel above has none.
The sink is ordinary memory, and nothing keeps a data breakpoint away
from it yet.
Suggested-by: Josh Poimboeuf <jpoimboe@kernel.org>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---
tools/objtool/check.c | 207 +++++++++++++++++++++++++++++++++++++++++-
1 file changed, 203 insertions(+), 4 deletions(-)
diff --git a/tools/objtool/check.c b/tools/objtool/check.c
index 85cb21b41508b..41a5e587a129e 100644
--- a/tools/objtool/check.c
+++ b/tools/objtool/check.c
@@ -22,6 +22,7 @@
#include <objtool/warn.h>
#include <objtool/util.h>
+#include <linux/align.h>
#include <linux/objtool_types.h>
#include <linux/hashtable.h>
#include <linux/kernel.h>
@@ -408,7 +409,7 @@ static void *cfi_hash_alloc(unsigned long size)
static unsigned long nr_insns;
static unsigned long nr_insns_visited;
-static unsigned long nr_coverage_nops;
+static unsigned long nr_coverage_nops, nr_coverage_sink;
/*
* Call the arch-specific instruction decoder for all the instructions and add
@@ -2721,6 +2722,184 @@ static bool is_coverage_update(struct objtool_file *file,
arch_insn_is_mem_update(insn, reloc);
}
+/* The alignment of the sink, and the extra room at both of its ends */
+#define COVERAGE_SINK_ALIGN 64
+
+struct coverage_access {
+ struct reloc *reloc;
+ struct symbol *sym;
+ s64 addend;
+};
+
+struct coverage_sink {
+ struct coverage_access *accs;
+ unsigned int nr, max;
+ unsigned long size;
+};
+
+/*
+ * Find the counters that @reloc refers to: the counters or the MC/DC bitmap
+ * of one function. Those of gcov are sized symbols, the ones of Clang's
+ * source-based code coverage are unsized and end where the next ones start.
+ *
+ * Returns the room that accesses relative to @reloc may need around the start
+ * of the counters.
+ */
+static unsigned long coverage_object(struct instruction *insn,
+ struct reloc *reloc, unsigned long *start)
+{
+ struct section *sec = reloc->sym->sec;
+ struct symbol *sym = reloc->sym;
+ unsigned long end, prev = 0;
+ s64 offset;
+
+ if (sym->len) {
+ *start = sym->offset;
+ return sym->len;
+ }
+
+ offset = clamp(insn_reloc_dest(insn, reloc), (s64)0, (s64)sec_size(sec));
+
+ if (!sym->coverage_counter) {
+ sym = find_symbol_containing(sec, offset);
+ if (sym) {
+ *start = sym->offset;
+ return sym->len;
+ }
+ }
+
+ *start = 0;
+ end = sec_size(sec);
+
+ sec_for_each_sym(sec, sym) {
+ if (sym->offset > offset) {
+ end = min(end, sym->offset);
+ continue;
+ }
+
+ *start = max(*start, sym->offset);
+ if (sym->offset < offset)
+ prev = max(prev, sym->offset);
+ }
+
+ /* The start of these counters is also the end of the ones before */
+ if (offset == *start)
+ return max(end - *start, *start - prev);
+
+ return end - *start;
+}
+
+static int add_coverage_access(struct coverage_sink *sink,
+ struct instruction *insn, struct reloc *reloc)
+{
+ struct coverage_access *acc;
+ unsigned long start, size;
+
+ if (sink->nr == sink->max) {
+ sink->max = sink->max ? sink->max * 2 : 64;
+ sink->accs = realloc(sink->accs, sink->max * sizeof(*acc));
+ if (!sink->accs) {
+ ERROR_GLIBC("realloc");
+ return -1;
+ }
+ }
+
+ size = coverage_object(insn, reloc, &start);
+
+ acc = &sink->accs[sink->nr++];
+ acc->reloc = reloc;
+ acc->sym = reloc->sym;
+ acc->addend = reloc_addend(reloc) + reloc->sym->offset - start;
+
+ sink->size = max(sink->size, size);
+
+ return 0;
+}
+
+/* Take the relocations that no longer refer to @sym off its list */
+static void prune_sym_relocs(struct symbol *sym)
+{
+ struct reloc *reloc, *prev = NULL, *next;
+
+ for (reloc = sym->relocs; reloc; reloc = next) {
+ next = sym_next_reloc(reloc);
+
+ if (reloc->sym == sym) {
+ prev = reloc;
+ continue;
+ }
+
+ if (prev)
+ set_sym_next_reloc(prev, next);
+ else
+ sym->relocs = next;
+ }
+}
+
+/*
+ * Point the accesses at a sink in a new .bss section. Only the relocations
+ * change, so this also works when the address of the counters gets loaded
+ * into a register first. The counters of every function start at the same
+ * place in the sink, which keeps their offsets and alignment, with room for
+ * the largest of them on either side: an indexed access stays within the sink
+ * whether it is relative to the start of its counters or to their end.
+ */
+static int create_coverage_sink(struct objtool_file *file,
+ struct coverage_sink *sink)
+{
+ unsigned long base = ALIGN(sink->size, COVERAGE_SINK_ALIGN) +
+ COVERAGE_SINK_ALIGN;
+ struct coverage_access *accs = sink->accs;
+ struct section *sec;
+ struct symbol *sym;
+ unsigned int i, j;
+ char name[32];
+
+ /* Don't trip over a section of that name which is already there */
+ for (i = 0; ; i++) {
+ snprintf(name, sizeof(name),
+ i ? ".bss.coverage_sink.%u" : ".bss.coverage_sink", i);
+ if (!find_section_by_name(file->elf, name))
+ break;
+ }
+
+ sec = elf_create_section(file->elf, name, 2 * base, 0, SHT_NOBITS,
+ COVERAGE_SINK_ALIGN, SHF_ALLOC | SHF_WRITE);
+ if (!sec)
+ return -1;
+
+ sym = elf_create_symbol(file->elf, "__coverage_sink", sec, STB_LOCAL,
+ STT_OBJECT, 0, sec_size(sec));
+ if (!sym)
+ return -1;
+
+ for (i = 0; i < sink->nr; i++) {
+ accs[i].reloc->sym = sym;
+ set_reloc_sym(file->elf, accs[i].reloc, sym->idx);
+ set_reloc_addend(file->elf, accs[i].reloc,
+ base + accs[i].addend);
+ }
+
+ for (i = 0; i < sink->nr; i++) {
+ for (j = 0; j < i; j++) {
+ if (accs[j].sym == accs[i].sym)
+ break;
+ }
+
+ if (j == i)
+ prune_sym_relocs(accs[i].sym);
+ }
+
+ for (i = 0; i < sink->nr; i++) {
+ set_sym_next_reloc(accs[i].reloc, sym->relocs);
+ sym->relocs = accs[i].reloc;
+ }
+
+ nr_coverage_sink += sink->nr;
+
+ return 0;
+}
+
/*
* gcov and Clang's source-based code coverage update their counters inline,
* and the compilers add those updates before inlining. The counter updates of
@@ -2728,13 +2907,17 @@ static bool is_coverage_update(struct objtool_file *file,
* the noinstr function is __no_profile.
*
* Remove them. An update of a counter has no other output than the flags, which
- * the compilers don't use, so a NOP can take its place.
+ * the compilers don't use, so a NOP can take its place. Everything else that
+ * refers to the counters, like the loads and the address calculations of
+ * Clang's MC/DC bitmap updates, is pointed at a sink instead.
*/
static int remove_noinstr_coverage(struct objtool_file *file)
{
+ struct coverage_sink sink = {};
struct instruction *insn;
struct section *sec;
struct reloc *reloc;
+ int ret = 0;
for_each_sec(file->elf, sec) {
if (!sec->noinstr)
@@ -2742,9 +2925,19 @@ static int remove_noinstr_coverage(struct objtool_file *file)
sec_for_each_insn(file, sec, insn) {
reloc = insn_reloc(file, insn);
- if (!reloc || !is_coverage_update(file, insn, reloc))
+ if (!reloc)
continue;
+ if (!is_coverage_update(file, insn, reloc)) {
+ for (; reloc; reloc = insn_next_reloc(file, insn, reloc)) {
+ if (is_coverage_reloc(file, insn, reloc) &&
+ add_coverage_access(&sink, insn, reloc))
+ return -1;
+ }
+
+ continue;
+ }
+
set_reloc_type(file->elf, reloc, R_NONE);
if (elf_write_insn(file->elf, insn->sec, insn->offset,
@@ -2756,7 +2949,12 @@ static int remove_noinstr_coverage(struct objtool_file *file)
}
}
- return 0;
+ if (sink.nr)
+ ret = create_coverage_sink(file, &sink);
+
+ free(sink.accs);
+
+ return ret;
}
int decode_file(struct objtool_file *file)
@@ -5104,6 +5302,7 @@ int check(struct objtool_file *file)
printf("nr_cfi_reused: %ld\n", nr_cfi_reused);
printf("nr_cfi_cache: %ld\n", nr_cfi_cache);
printf("nr_coverage_nops: %ld\n", nr_coverage_nops);
+ printf("nr_coverage_sink: %ld\n", nr_coverage_sink);
}
out:
--
2.53.0
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v3 12/19] x86/sev: Stop excluding noinstr.o from code coverage
2026-11-25 2:05 [PATCH v3 00/19] Unify code coverage and add Clang source-based coverage with MC/DC Sasha Levin
` (2 preceding siblings ...)
2026-11-25 2:05 ` [PATCH v3 11/19] objtool: Point the remaining coverage accesses in noinstr code at a sink Sasha Levin
@ 2026-11-25 2:05 ` Sasha Levin
2026-11-25 2:05 ` [PATCH v3 13/19] coverage: add Clang's source-based " Sasha Levin
` (4 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-11-25 2:05 UTC (permalink / raw)
To: linux-kernel
Cc: Bill Wendling, Borislav Petkov, Chuck Wolber, Dave Hansen,
H. Peter Anvin, Ingo Molnar, Josh Poimboeuf, Justin Stitt, llvm,
Marco Elver, Masami Hiramatsu, Nathan Chancellor,
Nick Desaulniers, Peter Zijlstra, Thomas Gleixner, x86
noinstr.o was excluded from gcov after Clang's gcov instrumentation
left calls to kasan_check_write() in __sev_es_nmi_complete(), and
because any coverage instrumentation would violate noinstr.
The GHCB accessors no longer call the KASAN and KCSAN checks, the
noinstr attribute keeps the functions themselves from being
instrumented, and objtool now removes the coverage instrumentation of
what gets inlined into them. Drop the exclusion, so that the file is
handled like the rest of the kernel's noinstr code.
Signed-off-by: Sasha Levin <sashal@kernel.org>
---
arch/x86/coco/sev/Makefile | 2 --
1 file changed, 2 deletions(-)
diff --git a/arch/x86/coco/sev/Makefile b/arch/x86/coco/sev/Makefile
index be4785d766ec1..fb8ffedfc8b0c 100644
--- a/arch/x86/coco/sev/Makefile
+++ b/arch/x86/coco/sev/Makefile
@@ -8,5 +8,3 @@ UBSAN_SANITIZE_noinstr.o := n
# GCC may fail to respect __no_sanitize_address or __no_kcsan when inlining
KASAN_SANITIZE_noinstr.o := n
KCSAN_SANITIZE_noinstr.o := n
-
-COVERAGE_PROFILE_noinstr.o := n
--
2.53.0
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v3 13/19] coverage: add Clang's source-based code coverage
2026-11-25 2:05 [PATCH v3 00/19] Unify code coverage and add Clang source-based coverage with MC/DC Sasha Levin
` (3 preceding siblings ...)
2026-11-25 2:05 ` [PATCH v3 12/19] x86/sev: Stop excluding noinstr.o from code coverage Sasha Levin
@ 2026-11-25 2:05 ` Sasha Levin
2026-11-25 2:05 ` [PATCH v3 14/19] x86: Enable " Sasha Levin
` (3 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-11-25 2:05 UTC (permalink / raw)
To: linux-kernel
Cc: Alexander Potapenko, Andrey Konovalov, Arnd Bergmann,
Bill Wendling, Chuck Wolber, Dmitry Vyukov, Josh Poimboeuf,
Justin Stitt, kasan-dev, linux-arch, linux-kbuild, llvm,
Marco Elver, Masami Hiramatsu, Nathan Chancellor,
Nick Desaulniers, Nicolas Schier, Peter Oberparleiter,
Peter Zijlstra, Thomas Gleixner, Wentao Zhang
Add Clang's Source-based Code Coverage [1] as a second code coverage
measurement implementation, next to gcov.
gcov works at the object code level, which may better reflect actual
execution, but its measurements can lose source level precision when
compiler optimizations are enabled, as they always are for the kernel.
In the following example from drivers/firmware/dmi_scan.c, measured on
v6.11, gcov reports six branch outcomes for an expression with four
conditions:
5: 1068: if (s == e || *e != '/' || !month || month > 12) {
branch 0 taken 5 (fallthrough)
branch 1 taken 0
branch 2 taken 5 (fallthrough)
branch 3 taken 0
branch 4 taken 0 (fallthrough)
branch 5 taken 5
Clang's Source-based Code Coverage instruments the code in the compiler
front end, so the coverage data maps back to the source code exactly,
regardless of optimizations, and reports each condition:
1068| 5| if (s == e || *e != '/' || !month || month > 12) {
------------------
| Branch (1068:6): [True: 0, False: 5]
| Branch (1068:16): [True: 0, False: 5]
| Branch (1068:29): [True: 0, False: 5]
| Branch (1068:39): [True: 0, False: 5]
------------------
It is selected with CONFIG_LLVM_COV_KERNEL in the "Code coverage
measurement" choice, uses the common COVERAGE_PROFILE annotations and
noinstr handling, and exports the raw profile of the kernel image in
/sys/kernel/debug/coverage/llvm/profraw. Writing to
/sys/kernel/debug/coverage/llvm/reset resets the coverage data. The raw
profile formats of Clang 19 to 22 (version 10) and of Clang 23 and later
(version 11) are supported. Counters are updated atomically, like gcov
does when the compiler allows it. Jump tables are turned off for the
instrumented code: Clang would also turn a switch into a table of the
counters to update, which objtool can't keep out of noinstr code.
The data is exported from sections that the architecture's linker script
places with LLVM_COV_DATA, so only code built into the kernel image is
instrumented; modules are left alone. The coverage mapping, which Clang
doesn't allocate since only llvm-cov reads it from vmlinux, is placed
with LLVM_COV_MAPPING next to the debug sections.
The rds selftest configuration script, which selects gcov or no code
coverage, now also turns it off.
This reuses the debugfs interface and raw profile serialization of
earlier work by Sami Tolvanen et al. [2], without the parts specific to
profile guided optimization.
Link: https://clang.llvm.org/docs/SourceBasedCodeCoverage.html [1]
Link: https://lore.kernel.org/lkml/20210407211704.367039-1-morbo@google.com/ [2]
Originally-by: Wentao Zhang <wentaoz5@illinois.edu>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---
MAINTAINERS | 2 +
Makefile | 1 +
include/asm-generic/vmlinux.lds.h | 35 ++++
kernel/coverage/Kconfig | 34 +++-
kernel/coverage/Makefile | 1 +
kernel/coverage/llvm/Makefile | 4 +
kernel/coverage/llvm/fs.c | 218 ++++++++++++++++++++++
kernel/coverage/llvm/llvm-cov.h | 139 ++++++++++++++
scripts/Makefile.lib | 7 +-
scripts/Makefile.llvm-cov | 8 +
tools/testing/selftests/net/rds/config.sh | 2 +
11 files changed, 448 insertions(+), 3 deletions(-)
create mode 100644 kernel/coverage/llvm/Makefile
create mode 100644 kernel/coverage/llvm/fs.c
create mode 100644 kernel/coverage/llvm/llvm-cov.h
create mode 100644 scripts/Makefile.llvm-cov
diff --git a/MAINTAINERS b/MAINTAINERS
index 77a0f2aef0de4..d7910586005a1 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -6640,6 +6640,8 @@ F: kernel/coverage/Kconfig
F: kernel/coverage/Makefile
F: kernel/coverage/core.c
F: kernel/coverage/coverage.h
+F: kernel/coverage/llvm/
+F: scripts/Makefile.llvm-cov
CODE OF CONDUCT
M: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
diff --git a/Makefile b/Makefile
index 9d5bfe5e0b43c..84654466e7822 100644
--- a/Makefile
+++ b/Makefile
@@ -1205,6 +1205,7 @@ include-$(CONFIG_KMSAN) += scripts/Makefile.kmsan
include-$(CONFIG_UBSAN) += scripts/Makefile.ubsan
include-$(CONFIG_KCOV) += scripts/Makefile.kcov
include-$(CONFIG_GCOV_KERNEL) += scripts/Makefile.gcov
+include-$(CONFIG_LLVM_COV_KERNEL) += scripts/Makefile.llvm-cov
include-$(CONFIG_RANDSTRUCT) += scripts/Makefile.randstruct
include-$(CONFIG_KSTACK_ERASE) += scripts/Makefile.kstack_erase
include-$(CONFIG_AUTOFDO_CLANG) += scripts/Makefile.autofdo
diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h
index 3eb732942d699..ddcd8992abe80 100644
--- a/include/asm-generic/vmlinux.lds.h
+++ b/include/asm-generic/vmlinux.lds.h
@@ -359,6 +359,41 @@
#define THERMAL_TABLE(name)
#endif
+#ifdef CONFIG_LLVM_COV_KERNEL
+#define LLVM_COV_DATA \
+ __llvm_prf_data : AT(ADDR(__llvm_prf_data) - LOAD_OFFSET) { \
+ BOUNDED_SECTION_POST_LABEL(__llvm_prf_data, \
+ __llvm_prf_data, \
+ _start, _end) \
+ } \
+ __llvm_prf_cnts : AT(ADDR(__llvm_prf_cnts) - LOAD_OFFSET) { \
+ BOUNDED_SECTION_POST_LABEL(__llvm_prf_cnts, \
+ __llvm_prf_cnts, \
+ _start, _end) \
+ } \
+ __llvm_prf_names : AT(ADDR(__llvm_prf_names) - LOAD_OFFSET) { \
+ BOUNDED_SECTION_POST_LABEL(__llvm_prf_names, \
+ __llvm_prf_names, \
+ _start, _end) \
+ } \
+ __llvm_prf_bits : AT(ADDR(__llvm_prf_bits) - LOAD_OFFSET) { \
+ BOUNDED_SECTION_POST_LABEL(__llvm_prf_bits, \
+ __llvm_prf_bits, \
+ _start, _end) \
+ }
+
+/*
+ * Clang doesn't allocate the coverage mapping, which only llvm-cov reads from
+ * vmlinux, so it goes next to the debug sections, outside of the image.
+ */
+#define LLVM_COV_MAPPING \
+ __llvm_covfun 0 : { KEEP(*(__llvm_covfun)) } \
+ __llvm_covmap 0 : { KEEP(*(__llvm_covmap)) }
+#else
+#define LLVM_COV_DATA
+#define LLVM_COV_MAPPING
+#endif
+
#define KERNEL_DTB() \
STRUCT_ALIGN(); \
__dtb_start = .; \
diff --git a/kernel/coverage/Kconfig b/kernel/coverage/Kconfig
index 6e70065be06b9..4d1b6190bcde1 100644
--- a/kernel/coverage/Kconfig
+++ b/kernel/coverage/Kconfig
@@ -4,6 +4,16 @@ menu "Code coverage"
config ARCH_HAS_GCOV_PROFILE_ALL
def_bool n
+config ARCH_HAS_LLVM_COV
+ bool
+ help
+ An architecture should select this when its linker script places
+ the sections of Clang's source-based code coverage (LLVM_COV_DATA
+ and LLVM_COV_MAPPING).
+
+config ARCH_HAS_LLVM_COV_PROFILE_ALL
+ bool
+
choice
prompt "Code coverage measurement"
default GCOV_KERNEL if COMPILE_TEST
@@ -49,9 +59,30 @@ config GCOV_KERNEL
and its modules is exported in gcov's format in /sys/kernel/debug/gcov,
see Documentation/dev-tools/gcov.rst.
+config LLVM_COV_KERNEL
+ bool "Clang's source-based code coverage"
+ depends on CC_IS_CLANG && CLANG_VERSION >= 190000
+ depends on DEBUG_FS
+ depends on ARCH_HAS_LLVM_COV
+ select OBJTOOL if HAVE_NOINSTR_HACK
+ help
+ This option enables Clang's Source-based Code Coverage. It
+ instruments the code in the compiler's front end, so that coverage
+ data maps back to the source code exactly, regardless of the
+ optimizations applied.
+
+ The raw profile is exported in /sys/kernel/debug/coverage/llvm/profraw.
+ Convert it with "llvm-profdata merge" and analyze it with "llvm-cov"
+ against vmlinux, using the LLVM version that built the kernel.
+
+ Only code built into the kernel image is instrumented.
+
endchoice
config COVERAGE_KERNEL
+ def_bool GCOV_KERNEL || LLVM_COV_KERNEL
+
+config COVERAGE_MODULES
def_bool GCOV_KERNEL
config GCOV_PROFILE_ALL
@@ -64,7 +95,8 @@ config GCOV_PROFILE_ALL
config COVERAGE_PROFILE_ALL
bool "Profile entire kernel"
depends on !COMPILE_TEST
- depends on GCOV_KERNEL && ARCH_HAS_GCOV_PROFILE_ALL
+ depends on (GCOV_KERNEL && ARCH_HAS_GCOV_PROFILE_ALL) || \
+ (LLVM_COV_KERNEL && ARCH_HAS_LLVM_COV_PROFILE_ALL)
default GCOV_PROFILE_ALL
help
This option activates coverage instrumentation for the entire kernel.
diff --git a/kernel/coverage/Makefile b/kernel/coverage/Makefile
index 881fada442bd1..d783272d9974d 100644
--- a/kernel/coverage/Makefile
+++ b/kernel/coverage/Makefile
@@ -2,6 +2,7 @@
obj-$(or $(CONFIG_COVERAGE_KERNEL),$(CONFIG_KCOV)) += core.o
obj-$(CONFIG_GCOV_KERNEL) += gcov/
+obj-$(CONFIG_LLVM_COV_KERNEL) += llvm/
obj-$(CONFIG_KCOV) += kcov.o
# Don't self-instrument.
diff --git a/kernel/coverage/llvm/Makefile b/kernel/coverage/llvm/Makefile
new file mode 100644
index 0000000000000..7090171b070eb
--- /dev/null
+++ b/kernel/coverage/llvm/Makefile
@@ -0,0 +1,4 @@
+# SPDX-License-Identifier: GPL-2.0
+COVERAGE_PROFILE := n
+
+obj-y := fs.o
diff --git a/kernel/coverage/llvm/fs.c b/kernel/coverage/llvm/fs.c
new file mode 100644
index 0000000000000..6f5bc16fea600
--- /dev/null
+++ b/kernel/coverage/llvm/fs.c
@@ -0,0 +1,218 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Copyright (C) 2019 Sami Tolvanen <samitolvanen@google.com>, Google, Inc.
+ * Copyright (C) 2024 Jinghao Jia <jinghao7@illinois.edu>, UIUC
+ * Copyright (C) 2024 Wentao Zhang <wentaoz5@illinois.edu>, UIUC
+ */
+
+#define pr_fmt(fmt) "llvm-cov: " fmt
+
+#include <linux/debugfs.h>
+#include <linux/fs.h>
+#include <linux/init.h>
+#include <linux/mutex.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/vmalloc.h>
+
+#include "../coverage.h"
+#include "llvm-cov.h"
+
+/*
+ * Serializes taking a snapshot of the profile data against resetting it. The
+ * instrumented code updates the counters and bitmaps without taking it, so a
+ * snapshot is not atomic with respect to code running on other CPUs.
+ */
+static DEFINE_MUTEX(llvm_cov_mutex);
+
+struct llvm_cov_private_data {
+ char *buffer;
+ unsigned long size;
+};
+
+/*
+ * Raw profile data format:
+ * https://llvm.org/docs/InstrProfileFormat.html#raw-profile-format. Only the
+ * information relevant to Source-based Code Coverage is populated. Binary IDs,
+ * continuous mode, single-byte mode, value profiling, type profiling and
+ * uniform counters are not implemented.
+ */
+
+static void llvm_cov_fill_raw_profile_header(void **buffer)
+{
+ struct __llvm_profile_header *header = *buffer;
+
+ header->magic = INSTR_PROF_RAW_MAGIC_64;
+ header->version = INSTR_PROF_RAW_VERSION;
+ header->binary_ids_size = 0;
+ header->num_data = __llvm_prf_data_count();
+ header->padding_bytes_before_counters = 0;
+ header->num_counters = __llvm_prf_cnts_count();
+ header->padding_bytes_after_counters =
+ __llvm_prf_get_padding(__llvm_prf_cnts_size());
+ header->num_bitmap_bytes = __llvm_prf_bits_size();
+ header->padding_bytes_after_bitmap_bytes =
+ __llvm_prf_get_padding(__llvm_prf_bits_size());
+#if CONFIG_CLANG_VERSION >= 230000
+ header->num_uniform_counters = 0;
+ header->padding_bytes_after_uniform_counters = 0;
+ header->uniform_counters_delta = 0;
+#endif
+ header->names_size = __llvm_prf_names_size();
+ header->counters_delta = (u64)__llvm_prf_cnts_start -
+ (u64)__llvm_prf_data_start;
+ header->bitmap_delta = (u64)__llvm_prf_bits_start -
+ (u64)__llvm_prf_data_start;
+ header->names_delta = (u64)__llvm_prf_names_start;
+ header->num_v_tables = 0;
+ header->v_names_size = 0;
+ header->value_kind_last = IPVK_LAST;
+
+ *buffer += sizeof(*header);
+}
+
+/*
+ * Copy the source into the buffer, incrementing the pointer into buffer in the
+ * process.
+ */
+static void llvm_cov_copy_section_to_buffer(void **buffer, void *src,
+ unsigned long size)
+{
+ memcpy(*buffer, src, size);
+ *buffer += size;
+}
+
+static unsigned long llvm_cov_get_raw_profile_size(void)
+{
+ return sizeof(struct __llvm_profile_header) +
+ __llvm_prf_data_size() +
+ __llvm_prf_cnts_size() +
+ __llvm_prf_get_padding(__llvm_prf_cnts_size()) +
+ __llvm_prf_bits_size() +
+ __llvm_prf_get_padding(__llvm_prf_bits_size()) +
+ __llvm_prf_names_size() +
+ __llvm_prf_get_padding(__llvm_prf_names_size());
+}
+
+/*
+ * Serialize in-memory data into a format LLVM tools can understand
+ * (https://llvm.org/docs/InstrProfileFormat.html#raw-profile-format)
+ */
+static int llvm_cov_serialize_raw_profile(struct llvm_cov_private_data *p)
+{
+ void *buffer;
+
+ p->size = llvm_cov_get_raw_profile_size();
+ p->buffer = vzalloc(p->size);
+ if (!p->buffer)
+ return -ENOMEM;
+
+ buffer = p->buffer;
+
+ llvm_cov_fill_raw_profile_header(&buffer);
+ llvm_cov_copy_section_to_buffer(&buffer, __llvm_prf_data_start,
+ __llvm_prf_data_size());
+ llvm_cov_copy_section_to_buffer(&buffer, __llvm_prf_cnts_start,
+ __llvm_prf_cnts_size());
+ buffer += __llvm_prf_get_padding(__llvm_prf_cnts_size());
+ llvm_cov_copy_section_to_buffer(&buffer, __llvm_prf_bits_start,
+ __llvm_prf_bits_size());
+ buffer += __llvm_prf_get_padding(__llvm_prf_bits_size());
+ llvm_cov_copy_section_to_buffer(&buffer, __llvm_prf_names_start,
+ __llvm_prf_names_size());
+
+ return 0;
+}
+
+/* open() implementation for llvm-cov data file. */
+static int llvm_cov_open(struct inode *inode, struct file *file)
+{
+ struct llvm_cov_private_data *data;
+ int err;
+
+ data = kzalloc_obj(*data);
+ if (!data)
+ return -ENOMEM;
+
+ mutex_lock(&llvm_cov_mutex);
+ err = llvm_cov_serialize_raw_profile(data);
+ mutex_unlock(&llvm_cov_mutex);
+
+ if (err) {
+ kfree(data);
+ return err;
+ }
+
+ file->private_data = data;
+ return 0;
+}
+
+/* read() implementation for llvm-cov data file. */
+static ssize_t llvm_cov_read(struct file *file, char __user *buf, size_t count,
+ loff_t *ppos)
+{
+ struct llvm_cov_private_data *data = file->private_data;
+
+ return simple_read_from_buffer(buf, count, ppos, data->buffer,
+ data->size);
+}
+
+/* release() implementation for llvm-cov data file. */
+static int llvm_cov_release(struct inode *inode, struct file *file)
+{
+ struct llvm_cov_private_data *data = file->private_data;
+
+ vfree(data->buffer);
+ kfree(data);
+ return 0;
+}
+
+static const struct file_operations llvm_cov_data_fops = {
+ .owner = THIS_MODULE,
+ .open = llvm_cov_open,
+ .read = llvm_cov_read,
+ .llseek = default_llseek,
+ .release = llvm_cov_release,
+};
+
+/* write() implementation for the reset file. */
+static ssize_t llvm_cov_reset_write(struct file *file, const char __user *buf,
+ size_t len, loff_t *pos)
+{
+ mutex_lock(&llvm_cov_mutex);
+ memset(__llvm_prf_cnts_start, 0, __llvm_prf_cnts_size());
+ memset(__llvm_prf_bits_start, 0, __llvm_prf_bits_size());
+ mutex_unlock(&llvm_cov_mutex);
+ return len;
+}
+
+/* Allow reads so that a recursive copy of the directory doesn't fail. */
+static ssize_t llvm_cov_reset_read(struct file *file, char __user *buf,
+ size_t len, loff_t *pos)
+{
+ return 0;
+}
+
+static const struct file_operations llvm_cov_reset_fops = {
+ .write = llvm_cov_reset_write,
+ .read = llvm_cov_reset_read,
+ .llseek = noop_llseek,
+};
+
+static const struct coverage_backend llvm_cov_backend = {
+ .name = "llvm",
+};
+
+static int __init llvm_cov_init(void)
+{
+ struct dentry *dir;
+
+ dir = debugfs_create_dir("llvm", coverage_debugfs_root());
+ debugfs_create_file_size("profraw", 0400, dir, NULL, &llvm_cov_data_fops,
+ llvm_cov_get_raw_profile_size());
+ debugfs_create_file("reset", 0600, dir, NULL, &llvm_cov_reset_fops);
+ coverage_register_backend(&llvm_cov_backend);
+
+ return 0;
+}
+device_initcall(llvm_cov_init);
diff --git a/kernel/coverage/llvm/llvm-cov.h b/kernel/coverage/llvm/llvm-cov.h
new file mode 100644
index 0000000000000..61c76e803f88b
--- /dev/null
+++ b/kernel/coverage/llvm/llvm-cov.h
@@ -0,0 +1,139 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Copyright (C) 2019 Sami Tolvanen <samitolvanen@google.com>, Google, Inc.
+ * Copyright (C) 2024 Jinghao Jia <jinghao7@illinois.edu>, UIUC
+ * Copyright (C) 2024 Wentao Zhang <wentaoz5@illinois.edu>, UIUC
+ */
+
+#ifndef _LLVM_COV_H
+#define _LLVM_COV_H
+
+#include <linux/types.h>
+
+/*
+ * These internal LLVM definitions must match the compiler version. See
+ * llvm/include/llvm/ProfileData/InstrProfData.inc in LLVM's source code.
+ */
+
+#define INSTR_PROF_RAW_MAGIC_64 \
+ ((u64)255 << 56 | \
+ (u64)'l' << 48 | \
+ (u64)'p' << 40 | \
+ (u64)'r' << 32 | \
+ (u64)'o' << 24 | \
+ (u64)'f' << 16 | \
+ (u64)'r' << 8 | \
+ (u64)129)
+
+#if CONFIG_CLANG_VERSION >= 230000
+#define INSTR_PROF_RAW_VERSION 11
+#else
+#define INSTR_PROF_RAW_VERSION 10
+#endif
+#define INSTR_PROF_DATA_ALIGNMENT 8
+#define IPVK_LAST 2
+
+/**
+ * struct __llvm_profile_header - represents the raw profile header data
+ * structure. Description of each member can be found here:
+ * https://llvm.org/docs/InstrProfileFormat.html#header.
+ */
+struct __llvm_profile_header {
+ u64 magic;
+ u64 version;
+ u64 binary_ids_size;
+ u64 num_data;
+ u64 padding_bytes_before_counters;
+ u64 num_counters;
+ u64 padding_bytes_after_counters;
+ u64 num_bitmap_bytes;
+ u64 padding_bytes_after_bitmap_bytes;
+#if CONFIG_CLANG_VERSION >= 230000
+ u64 num_uniform_counters;
+ u64 padding_bytes_after_uniform_counters;
+ u64 uniform_counters_delta;
+#endif
+ u64 names_size;
+ u64 counters_delta;
+ u64 bitmap_delta;
+ u64 names_delta;
+ u64 num_v_tables;
+ u64 v_names_size;
+ u64 value_kind_last;
+};
+
+/**
+ * struct __llvm_profile_data - represents the per-function control structure.
+ * Description of each member can be found here:
+ * https://llvm.org/docs/InstrProfileFormat.html#profile-metadata. To measure
+ * Source-based Code Coverage, the internals of this struct don't matter at run
+ * time. The only purpose of the definition below is to run sizeof() against it
+ * so that we can calculate the "num_data" field in header.
+ */
+struct __llvm_profile_data {
+ const u64 name_ref;
+ const u64 func_hash;
+ const void *counter_ptr;
+#if CONFIG_CLANG_VERSION >= 230000
+ const void *uniform_counter_ptr;
+#endif
+ const void *bitmap_ptr;
+ const void *function_pointer;
+ void *values;
+ const u32 num_counters;
+ const u16 num_value_sites[IPVK_LAST + 1];
+#if CONFIG_CLANG_VERSION >= 230000
+ const u16 offload_device_wave_size;
+#endif
+ const u32 num_bitmap_bytes;
+} __aligned(INSTR_PROF_DATA_ALIGNMENT);
+
+/* Payload sections */
+
+extern struct __llvm_profile_data __llvm_prf_data_start[];
+extern struct __llvm_profile_data __llvm_prf_data_end[];
+
+extern u64 __llvm_prf_cnts_start[];
+extern u64 __llvm_prf_cnts_end[];
+
+extern char __llvm_prf_names_start[];
+extern char __llvm_prf_names_end[];
+
+extern char __llvm_prf_bits_start[];
+extern char __llvm_prf_bits_end[];
+
+#define __DEFINE_SECTION_SIZE(s) \
+ static inline unsigned long __llvm_prf_ ## s ## _size(void) \
+ { \
+ unsigned long start = \
+ (unsigned long)__llvm_prf_ ## s ## _start; \
+ unsigned long end = \
+ (unsigned long)__llvm_prf_ ## s ## _end; \
+ return end - start; \
+ }
+#define __DEFINE_SECTION_COUNT(s) \
+ static inline unsigned long __llvm_prf_ ## s ## _count(void) \
+ { \
+ return __llvm_prf_ ## s ## _size() / \
+ sizeof(__llvm_prf_ ## s ## _start[0]); \
+ }
+
+__DEFINE_SECTION_SIZE(data)
+__DEFINE_SECTION_SIZE(cnts)
+__DEFINE_SECTION_SIZE(names)
+__DEFINE_SECTION_SIZE(bits)
+
+__DEFINE_SECTION_COUNT(data)
+__DEFINE_SECTION_COUNT(cnts)
+__DEFINE_SECTION_COUNT(names)
+__DEFINE_SECTION_COUNT(bits)
+
+#undef __DEFINE_SECTION_SIZE
+#undef __DEFINE_SECTION_COUNT
+
+static inline unsigned long __llvm_prf_get_padding(unsigned long size)
+{
+ return 7 & (sizeof(u64) - size % sizeof(u64));
+}
+
+#endif /* _LLVM_COV_H */
diff --git a/scripts/Makefile.lib b/scripts/Makefile.lib
index e0dc21e009522..77d1ab47125be 100644
--- a/scripts/Makefile.lib
+++ b/scripts/Makefile.lib
@@ -42,10 +42,13 @@ _cpp_flags = $(KBUILD_CPPFLAGS) $(cppflags-y) $(CPPFLAGS_$(target-stem).lds)
# depending on variables COVERAGE_PROFILE_obj.o, COVERAGE_PROFILE and
# CONFIG_COVERAGE_PROFILE_ALL (in this order)
#
+# Modules are only instrumented if the coverage implementation supports them.
+#
ifeq ($(CONFIG_COVERAGE_KERNEL),y)
-_c_flags += $(if $(patsubst n%,, \
+_c_flags += $(if $(if $(part-of-module),$(CONFIG_COVERAGE_MODULES),y), \
+ $(if $(patsubst n%,, \
$(COVERAGE_PROFILE_$(target-stem).o)$(COVERAGE_PROFILE)$(if $(is-kernel-object),$(CONFIG_COVERAGE_PROFILE_ALL))), \
- $(CFLAGS_COVERAGE))
+ $(CFLAGS_COVERAGE)))
endif
#
diff --git a/scripts/Makefile.llvm-cov b/scripts/Makefile.llvm-cov
new file mode 100644
index 0000000000000..764adf1730ee9
--- /dev/null
+++ b/scripts/Makefile.llvm-cov
@@ -0,0 +1,8 @@
+# SPDX-License-Identifier: GPL-2.0
+
+# No jump tables: Clang would also turn a switch into a table of the counters
+# to update, where objtool can't keep them out of noinstr code.
+CFLAGS_COVERAGE := -fprofile-instr-generate -fcoverage-mapping \
+ -fprofile-update=atomic -fno-jump-tables
+
+export CFLAGS_COVERAGE
diff --git a/tools/testing/selftests/net/rds/config.sh b/tools/testing/selftests/net/rds/config.sh
index d95a46def7513..dd6f9e50161b8 100755
--- a/tools/testing/selftests/net/rds/config.sh
+++ b/tools/testing/selftests/net/rds/config.sh
@@ -41,6 +41,8 @@ fi
scripts/config "${FLAGS[@]}" --enable CONFIG_RDS
scripts/config "${FLAGS[@]}" --enable CONFIG_RDS_TCP
+scripts/config "${FLAGS[@]}" --disable CONFIG_LLVM_COV_KERNEL
+
if [ "$GENERATE_GCOV_REPORT" -eq 1 ]; then
# instrument RDS and only RDS
scripts/config "${FLAGS[@]}" --disable CONFIG_COVERAGE_NONE
--
2.53.0
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v3 14/19] x86: Enable Clang's source-based code coverage
2026-11-25 2:05 [PATCH v3 00/19] Unify code coverage and add Clang source-based coverage with MC/DC Sasha Levin
` (4 preceding siblings ...)
2026-11-25 2:05 ` [PATCH v3 13/19] coverage: add Clang's source-based " Sasha Levin
@ 2026-11-25 2:05 ` Sasha Levin
2026-11-25 2:05 ` [PATCH v3 15/19] coverage: add MC/DC measurement Sasha Levin
` (2 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-11-25 2:05 UTC (permalink / raw)
To: linux-kernel
Cc: Bill Wendling, Borislav Petkov, Chuck Wolber, Dave Hansen,
H. Peter Anvin, Ingo Molnar, Josh Poimboeuf, Justin Stitt, llvm,
Marco Elver, Masami Hiramatsu, Nathan Chancellor,
Nick Desaulniers, Peter Zijlstra, Thomas Gleixner, Wentao Zhang,
x86
Place the sections of Clang's source-based code coverage in the x86
linker script and allow it to be used, including for the entire
kernel, on x86_64.
The coverage mapping is not part of the loaded image, but GNU objcopy
would keep it in the payload of the compressed kernel. Remove it there,
llvm-cov reads it from vmlinux.
Originally-by: Wentao Zhang <wentaoz5@illinois.edu>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---
arch/x86/Kconfig | 2 ++
arch/x86/boot/compressed/Makefile | 5 +++++
arch/x86/kernel/vmlinux.lds.S | 3 +++
3 files changed, 10 insertions(+)
diff --git a/arch/x86/Kconfig b/arch/x86/Kconfig
index 3159852fd6b3e..44bb4a2f5655e 100644
--- a/arch/x86/Kconfig
+++ b/arch/x86/Kconfig
@@ -89,6 +89,8 @@ config X86
select ARCH_HAS_FORTIFY_SOURCE
select ARCH_HAS_GCOV_PROFILE_ALL
select ARCH_HAS_KCOV if X86_64
+ select ARCH_HAS_LLVM_COV if X86_64
+ select ARCH_HAS_LLVM_COV_PROFILE_ALL if X86_64
select ARCH_HAS_KERNEL_FPU_SUPPORT
select ARCH_HAS_MEM_ENCRYPT
select ARCH_HAS_MEMBARRIER_SYNC_CORE
diff --git a/arch/x86/boot/compressed/Makefile b/arch/x86/boot/compressed/Makefile
index 680ad803cba7d..ecb86fb1a35ea 100644
--- a/arch/x86/boot/compressed/Makefile
+++ b/arch/x86/boot/compressed/Makefile
@@ -117,6 +117,11 @@ $(obj)/vmlinux: $(vmlinux-objs-y) $(vmlinux-libs-y) FORCE
$(call if_changed,ld)
OBJCOPYFLAGS_vmlinux.bin := -R .comment -S
+ifdef CONFIG_LLVM_COV_KERNEL
+# Only llvm-cov reads the coverage mapping, from vmlinux. GNU objcopy -S
+# would keep it in the payload of the compressed kernel.
+OBJCOPYFLAGS_vmlinux.bin += -R __llvm_covfun -R __llvm_covmap
+endif
$(obj)/vmlinux.bin: vmlinux FORCE
$(call if_changed,objcopy)
diff --git a/arch/x86/kernel/vmlinux.lds.S b/arch/x86/kernel/vmlinux.lds.S
index 2438b89a4620a..d9f9dee635fcd 100644
--- a/arch/x86/kernel/vmlinux.lds.S
+++ b/arch/x86/kernel/vmlinux.lds.S
@@ -212,6 +212,8 @@ SECTIONS
BUG_TABLE
+ LLVM_COV_DATA
+
ORC_UNWIND_TABLE
/* Init code and data - will be freed after init */
@@ -417,6 +419,7 @@ SECTIONS
STABS_DEBUG
DWARF_DEBUG
+ LLVM_COV_MAPPING
PROPELLER_DATA
MODINFO
ELF_DETAILS
--
2.53.0
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v3 15/19] coverage: add MC/DC measurement
2026-11-25 2:05 [PATCH v3 00/19] Unify code coverage and add Clang source-based coverage with MC/DC Sasha Levin
` (5 preceding siblings ...)
2026-11-25 2:05 ` [PATCH v3 14/19] x86: Enable " Sasha Levin
@ 2026-11-25 2:05 ` Sasha Levin
2026-11-25 2:06 ` [PATCH v3 18/19] gcov: add MC/DC condition coverage support Sasha Levin
2026-11-25 2:06 ` [PATCH v3 19/19] Documentation: dev-tools: document the common code coverage interface Sasha Levin
8 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-11-25 2:05 UTC (permalink / raw)
To: linux-kernel
Cc: Alexander Potapenko, Andrey Konovalov, Bill Wendling,
Chuck Wolber, Dmitry Vyukov, Josh Poimboeuf, Justin Stitt,
kasan-dev, linux-kbuild, llvm, Marco Elver, Masami Hiramatsu,
Nathan Chancellor, Nick Desaulniers, Nicolas Schier,
Peter Oberparleiter, Peter Zijlstra, Thomas Gleixner,
Wentao Zhang
Add CONFIG_COVERAGE_MCDC to measure Modified Condition/Decision
Coverage (MC/DC) [1], which is required by several automotive and
aviation standards for certifying safety critical software [2]. Start
with Clang's source-based code coverage, which supports it since Clang
18 [3].
In the following example from arch/x86/events/probe.c, measured on
v6.11, llvm-cov gives the MC/DC measurement for the compound logic
decision at line 43:
43| 12| if (msr[bit].test && !msr[bit].test(bit, data))
------------------
|---> MC/DC Decision Region (43:8) to (43:50)
|
| Number of Conditions: 2
| Condition C1 --> (43:8)
| Condition C2 --> (43:25)
|
| Executed MC/DC Test Vectors:
|
| C1, C2 Result
| 1 { T, F = F }
| 2 { T, T = T }
|
| C1-Pair: not covered
| C2-Pair: covered: (1,2)
| MC/DC Coverage for Decision: 50.00%
|
------------------
44| 5| continue;
Only condition C2 was shown to independently affect the outcome of the
decision, so the MC/DC of this decision is 1 out of 2.
MC/DC uses bitmaps to track the executed test vectors, which grow
quickly with the number of conditions. CONFIG_LLVM_COV_MCDC_MAX_CONDITIONS
sets the largest decision to instrument, through -fmcdc-max-conditions.
Larger decisions, and decisions the compiler can't instrument, are left
out of the MC/DC data and only get branch coverage. The compiler warns
about each of them, which is nothing to act on in the code, so disable
those warnings; building with KCFLAGS=-Wpgo-coverage lists them. Clang
only allows disabling them since version 22. Older versions always
print them, and -Werror doesn't make them errors, so CONFIG_COVERAGE_MCDC
isn't offered for those versions when CONFIG_WERROR is set and the build
is expected to be free of warnings.
Link: https://en.wikipedia.org/wiki/Modified_condition%2Fdecision_coverage [1]
Link: https://digital-library.theiet.org/content/journals/10.1049/sej.1994.0025 [2]
Link: https://clang.llvm.org/docs/SourceBasedCodeCoverage.html#mc-dc-instrumentation [3]
Originally-by: Wentao Zhang <wentaoz5@illinois.edu>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---
kernel/coverage/Kconfig | 26 ++++++++++++++++++++++++++
kernel/coverage/llvm/fs.c | 3 ++-
scripts/Kconfig.toolchain | 5 +++++
scripts/Makefile.llvm-cov | 9 +++++++++
4 files changed, 42 insertions(+), 1 deletion(-)
diff --git a/kernel/coverage/Kconfig b/kernel/coverage/Kconfig
index 4d1b6190bcde1..173a321741f87 100644
--- a/kernel/coverage/Kconfig
+++ b/kernel/coverage/Kconfig
@@ -106,6 +106,32 @@ config COVERAGE_PROFILE_ALL
Note that a kernel compiled with profiling flags will be significantly
larger and run slower.
+config COVERAGE_MCDC
+ bool "Measure modified condition/decision coverage (MC/DC)"
+ depends on LLVM_COV_KERNEL
+ depends on CLANG_VERSION >= 220000 || !WERROR
+ help
+ MC/DC verifies that each condition of a boolean decision has been
+ shown to independently affect the outcome of the decision. It is
+ required for certification by safety standards such as DO-178C
+ (avionics) and ISO 26262 (automotive).
+
+ Decisions that the compiler can't instrument are not measured, and
+ only get branch coverage.
+
+ If unsure, say N.
+
+config LLVM_COV_MCDC_MAX_CONDITIONS
+ int "Maximum number of conditions in a decision to instrument"
+ range 6 32767
+ depends on COVERAGE_MCDC && LLVM_COV_KERNEL
+ default 6
+ help
+ This value is passed to the "-fmcdc-max-conditions" option of Clang.
+ Decisions with more conditions are not instrumented. MC/DC uses
+ bitmaps to track the executed test vectors, which grow quickly with
+ the number of conditions.
+
# The per-subsystem COVERAGE_PROFILE_* options used to be GCOV_PROFILE_*.
config GCOV_PROFILE_AMDGPU
bool
diff --git a/kernel/coverage/llvm/fs.c b/kernel/coverage/llvm/fs.c
index 6f5bc16fea600..99fe5dc50a2fe 100644
--- a/kernel/coverage/llvm/fs.c
+++ b/kernel/coverage/llvm/fs.c
@@ -200,7 +200,8 @@ static const struct file_operations llvm_cov_reset_fops = {
};
static const struct coverage_backend llvm_cov_backend = {
- .name = "llvm",
+ .name = "llvm",
+ .features = IS_ENABLED(CONFIG_COVERAGE_MCDC) ? "mcdc" : NULL,
};
static int __init llvm_cov_init(void)
diff --git a/scripts/Kconfig.toolchain b/scripts/Kconfig.toolchain
index 2acbd40a38f16..8571cd16a2edd 100644
--- a/scripts/Kconfig.toolchain
+++ b/scripts/Kconfig.toolchain
@@ -188,6 +188,11 @@ config CC_OPT_NO_ALLOW_STORE_DATA_RACES
config CC_HAS_MNOP_MCOUNT
def_bool $(cc-option,-mnop-mcount)
+config CC_OPT_WNO_PGO_COVERAGE
+ # clang-22: https://github.com/llvm/llvm-project/commit/80887c7de9d82c809555f52948af1a5d7484e28f
+ # gcc: not supported
+ def_string "$(cc-option-str,-Wno-pgo-coverage)"
+
config LD_OPT_FORCE_GROUP_ALLOCATION
def_string "$(ld-option-str,--force-group-allocation)"
diff --git a/scripts/Makefile.llvm-cov b/scripts/Makefile.llvm-cov
index 764adf1730ee9..2ec97bf3cf73a 100644
--- a/scripts/Makefile.llvm-cov
+++ b/scripts/Makefile.llvm-cov
@@ -5,4 +5,13 @@
CFLAGS_COVERAGE := -fprofile-instr-generate -fcoverage-mapping \
-fprofile-update=atomic -fno-jump-tables
+ifdef CONFIG_COVERAGE_MCDC
+CFLAGS_COVERAGE += -fcoverage-mcdc \
+ -Xclang -fmcdc-max-conditions=$(CONFIG_LLVM_COV_MCDC_MAX_CONDITIONS)
+# Decisions that MC/DC leaves out are nothing to fix in the code. Disable the
+# warnings here rather than in CFLAGS_COVERAGE, so that KCFLAGS=-Wpgo-coverage
+# can list them. Clang only allows this since version 22.
+KBUILD_CFLAGS += $(CONFIG_CC_OPT_WNO_PGO_COVERAGE)
+endif
+
export CFLAGS_COVERAGE
--
2.53.0
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v3 18/19] gcov: add MC/DC condition coverage support
2026-11-25 2:05 [PATCH v3 00/19] Unify code coverage and add Clang source-based coverage with MC/DC Sasha Levin
` (6 preceding siblings ...)
2026-11-25 2:05 ` [PATCH v3 15/19] coverage: add MC/DC measurement Sasha Levin
@ 2026-11-25 2:06 ` Sasha Levin
2026-11-25 2:06 ` [PATCH v3 19/19] Documentation: dev-tools: document the common code coverage interface Sasha Levin
8 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-11-25 2:06 UTC (permalink / raw)
To: linux-kernel
Cc: Alexander Potapenko, Andrey Konovalov, Anton Ivanov,
Bill Wendling, Borislav Petkov, Chuck Wolber, Dave Hansen,
Dmitry Vyukov, H. Peter Anvin, Ingo Molnar, Johannes Berg,
Josh Poimboeuf, Justin Stitt, kasan-dev, linux-kbuild, linux-um,
llvm, Marco Elver, Masami Hiramatsu, Nathan Chancellor,
Nick Desaulniers, Nicolas Schier, Peter Oberparleiter,
Peter Zijlstra, Richard Weinberger, Thomas Gleixner, x86
Support CONFIG_COVERAGE_MCDC with gcov, using GCC's MC/DC condition
coverage instrumentation (-fcondition-coverage), which is available
since GCC 14. The data is shown by "gcov --conditions".
Add -fcondition-coverage to the gcov compiler flags when enabled, and
disable the warnings about decisions it leaves out, as is done for
Clang. Both are gated on the config option to avoid Clang warnings
about unknown options.
Signed-off-by: Sasha Levin <sashal@kernel.org>
Reviewed-by: Peter Oberparleiter <oberpar@linux.ibm.com>
---
kernel/coverage/Kconfig | 7 +++++--
kernel/coverage/gcov/fs.c | 3 ++-
scripts/Makefile.gcov | 5 +++++
3 files changed, 12 insertions(+), 3 deletions(-)
diff --git a/kernel/coverage/Kconfig b/kernel/coverage/Kconfig
index 173a321741f87..77df4c04945dc 100644
--- a/kernel/coverage/Kconfig
+++ b/kernel/coverage/Kconfig
@@ -108,8 +108,8 @@ config COVERAGE_PROFILE_ALL
config COVERAGE_MCDC
bool "Measure modified condition/decision coverage (MC/DC)"
- depends on LLVM_COV_KERNEL
- depends on CLANG_VERSION >= 220000 || !WERROR
+ depends on LLVM_COV_KERNEL || (GCOV_KERNEL && CC_HAS_CONDITION_COVERAGE)
+ depends on !(LLVM_COV_KERNEL && CLANG_VERSION < 220000 && WERROR)
help
MC/DC verifies that each condition of a boolean decision has been
shown to independently affect the outcome of the decision. It is
@@ -119,6 +119,9 @@ config COVERAGE_MCDC
Decisions that the compiler can't instrument are not measured, and
only get branch coverage.
+ With gcov this requires GCC 14 or later, and the data is shown by
+ "gcov --conditions".
+
If unsure, say N.
config LLVM_COV_MCDC_MAX_CONDITIONS
diff --git a/kernel/coverage/gcov/fs.c b/kernel/coverage/gcov/fs.c
index fe1b85d54ede0..aa51e76c0e530 100644
--- a/kernel/coverage/gcov/fs.c
+++ b/kernel/coverage/gcov/fs.c
@@ -861,7 +861,8 @@ void gcov_event(enum gcov_action action, struct gcov_info *info)
}
static const struct coverage_backend gcov_backend = {
- .name = "gcov",
+ .name = "gcov",
+ .features = IS_ENABLED(CONFIG_COVERAGE_MCDC) ? "mcdc" : NULL,
};
/* Create debugfs entries. */
diff --git a/scripts/Makefile.gcov b/scripts/Makefile.gcov
index 1cfe04d89b0a2..977c8ee023f68 100644
--- a/scripts/Makefile.gcov
+++ b/scripts/Makefile.gcov
@@ -18,4 +18,9 @@ CFLAGS_COVERAGE += $(call try-run,\
cmp -s "$$TMP.ubase" "$$TMP.utest",\
-fprofile-update=prefer-atomic)
endif
+ifdef CONFIG_COVERAGE_MCDC
+CFLAGS_COVERAGE += -fcondition-coverage
+# As for Clang: KCFLAGS=-Wcoverage-too-many-conditions lists what's left out.
+KBUILD_CFLAGS += -Wno-coverage-too-many-conditions
+endif
export CFLAGS_COVERAGE
--
2.53.0
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v3 19/19] Documentation: dev-tools: document the common code coverage interface
2026-11-25 2:05 [PATCH v3 00/19] Unify code coverage and add Clang source-based coverage with MC/DC Sasha Levin
` (7 preceding siblings ...)
2026-11-25 2:06 ` [PATCH v3 18/19] gcov: add MC/DC condition coverage support Sasha Levin
@ 2026-11-25 2:06 ` Sasha Levin
8 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-11-25 2:06 UTC (permalink / raw)
To: linux-kernel
Cc: Alexander Potapenko, Andrey Konovalov, Bill Wendling,
Chuck Wolber, Dmitry Vyukov, Jonathan Corbet, Josh Poimboeuf,
Justin Stitt, kasan-dev, linux-doc, llvm, Marco Elver,
Masami Hiramatsu, Nathan Chancellor, Nick Desaulniers,
Peter Oberparleiter, Peter Zijlstra, Randy Dunlap, Shuah Khan,
Thomas Gleixner, workflows
Describe the code coverage implementations and what they share: the
Kconfig options, the COVERAGE_PROFILE annotations, the
/sys/kernel/debug/coverage/ interface, MC/DC measurement, and how they
deal with noinstr code. Point to it from the gcov and KCOV
documentation, and document gcov's MC/DC support.
Signed-off-by: Sasha Levin <sashal@kernel.org>
---
Documentation/dev-tools/coverage.rst | 173 +++++++++++++++++++++++++++
Documentation/dev-tools/gcov.rst | 28 +++++
Documentation/dev-tools/index.rst | 1 +
Documentation/dev-tools/kcov.rst | 3 +
MAINTAINERS | 1 +
5 files changed, 206 insertions(+)
create mode 100644 Documentation/dev-tools/coverage.rst
diff --git a/Documentation/dev-tools/coverage.rst b/Documentation/dev-tools/coverage.rst
new file mode 100644
index 0000000000000..3634f01a9444d
--- /dev/null
+++ b/Documentation/dev-tools/coverage.rst
@@ -0,0 +1,173 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+=============
+Code coverage
+=============
+
+The kernel can be instrumented to find out which parts of it get executed.
+This serves two different purposes:
+
+* Measuring code coverage, e.g. to assess and improve a test suite, or to
+ show the structural coverage required by safety standards. This is done by
+ one of the code coverage measurement implementations described below.
+
+* Guiding fuzzers. This is done by KCOV, which collects coverage per task;
+ see Documentation/dev-tools/kcov.rst.
+
+All of them are configured in the "Kernel hacking -> Kernel Testing and
+Coverage -> Code coverage" menu, live in ``kernel/coverage/``, and share the
+``/sys/kernel/debug/coverage/`` debugfs directory.
+
+
+Code coverage measurement
+=========================
+
+The implementation is selected by the "Code coverage measurement" choice:
+
+============================ ============== ================================
+Option Compilers Data
+============================ ============== ================================
+``CONFIG_GCOV_KERNEL`` GCC, Clang gcov ``.gcda`` files, see
+ Documentation/dev-tools/gcov.rst
+``CONFIG_LLVM_COV_KERNEL`` Clang 19 and LLVM raw profile of the kernel
+ later image (``.profraw``)
+============================ ============== ================================
+
+The instrumentation and the format of the data are defined by the toolchain,
+so only one implementation can be used at a time. Both only instrument C
+code.
+
+Clang's source-based code coverage (``CONFIG_LLVM_COV_KERNEL``) instruments
+the code in the compiler front end. Its data therefore maps back to the source
+code exactly, regardless of the optimizations applied, and it can show the
+coverage of every condition of a decision. It only instruments code built into
+the kernel image. gcov also supports modules.
+
+
+Selecting the code to instrument
+--------------------------------
+
+``CONFIG_COVERAGE_PROFILE_ALL`` instruments the entire kernel. On architectures
+that don't support it, or to instrument only parts of the kernel, add a line
+like the following to the respective Makefile.
+
+For a single file (e.g. main.o)::
+
+ COVERAGE_PROFILE_main.o := y
+
+For all files in one directory::
+
+ COVERAGE_PROFILE := y
+
+To exclude files from being instrumented even when
+``CONFIG_COVERAGE_PROFILE_ALL`` is enabled, use::
+
+ COVERAGE_PROFILE_main.o := n
+
+and::
+
+ COVERAGE_PROFILE := n
+
+The per-file setting takes precedence over the per-directory one, which takes
+precedence over ``CONFIG_COVERAGE_PROFILE_ALL``.
+
+Code that is built as a module is only instrumented by an implementation that
+supports modules, whatever these settings say.
+
+Only exclude code that can't work when instrumented, for example because it
+runs before the kernel is relocated or is copied elsewhere. Code that must not
+be instrumented for correctness reasons, such as the entry code, is annotated
+``noinstr`` instead; see `noinstr`_.
+
+
+Interface
+---------
+
+``/sys/kernel/debug/coverage/`` contains:
+
+``backend``
+ The name of the selected implementation, ``gcov`` or ``llvm``, followed by
+ ``mcdc`` when MC/DC is measured. The implementation keeps its files in the
+ directory of that name.
+
+``<name>/reset``
+ Writing to this file resets all coverage data of the implementation. It
+ does not affect KCOV.
+
+``gcov``
+ A symlink to ``/sys/kernel/debug/gcov``, where gcov keeps its data (see
+ Documentation/dev-tools/gcov.rst).
+
+``llvm/profraw``
+ The raw profile of the kernel image, for Clang's source-based code
+ coverage.
+
+``kcov``
+ A symlink to ``/sys/kernel/debug/kcov`` (see
+ Documentation/dev-tools/kcov.rst).
+
+The instrumented code updates the coverage data without synchronizing with
+readers, so reading the data while other CPUs execute instrumented code
+doesn't give an atomic snapshot, and the same applies to a reset.
+
+With Clang's source-based code coverage, convert the raw profile and create a
+report with the ``llvm-profdata`` and ``llvm-cov`` tools of the LLVM version
+that built the kernel, since the raw profile format changes between releases::
+
+ # cp /sys/kernel/debug/coverage/llvm/profraw vmlinux.profraw
+ $ llvm-profdata merge vmlinux.profraw -o vmlinux.profdata
+ $ llvm-cov report -instr-profile=vmlinux.profdata vmlinux
+ $ llvm-cov show -instr-profile=vmlinux.profdata vmlinux kernel/fork.c
+
+
+MC/DC
+-----
+
+Modified condition/decision coverage (MC/DC) verifies that each condition of a
+boolean decision has been shown to independently affect the outcome of the
+decision. It is required by safety standards such as DO-178C (avionics) and
+ISO 26262 (automotive). Enable it with ``CONFIG_COVERAGE_MCDC``:
+
+* With Clang's source-based code coverage, decisions with more than
+ ``CONFIG_LLVM_COV_MCDC_MAX_CONDITIONS`` conditions are not measured. Show
+ the results with ``llvm-cov show -show-mcdc`` and
+ ``llvm-cov report -show-mcdc-summary``.
+
+* With gcov, GCC 14 or later is required, and decisions with more than 64
+ conditions are not measured. Show the results with ``gcov --conditions``.
+
+Decisions that aren't measured still get branch coverage. To list them, build
+with ``KCFLAGS=-Wpgo-coverage`` (Clang) or
+``KCFLAGS=-Wcoverage-too-many-conditions`` (GCC). Clang only warns about them
+by default before version 22, as it can't disable these warnings.
+
+
+noinstr
+=======
+
+Code annotated ``noinstr`` must not be instrumented; this includes the code
+running on kernel entry and exit, and in NMI context. Outside of
+``instrumentation_begin()``/``instrumentation_end()`` sections, ``noinstr``
+functions may only call other ``noinstr`` functions and ``__always_inline``
+functions.
+
+``noinstr`` functions are not instrumented themselves. The compilers insert
+the code coverage instrumentation before functions get inlined though, which
+carries the counter updates of a function into the ``noinstr`` code it is
+inlined into.
+
+On x86-64, objtool takes them out of ``noinstr`` functions, including their
+``instrumentation_begin()``/``instrumentation_end()`` sections. It replaces
+the counter updates with NOPs. Clang also accesses the coverage data in ways
+that can't simply be removed, such as the load that an MC/DC bitmap update
+starts with: those instructions stay and are pointed at a piece of memory
+that nothing else uses. With Clang's gcov, a counter that gets updated
+through its address in a register is not recognized and keeps being updated.
+
+A function that is only ever inlined into ``noinstr`` code is therefore
+reported as not executed, and one that has other callers as well only counts
+the executions from those. On other architectures the counter updates stay.
+
+KCOV instruments the code after inlining and honours ``noinstr`` through the
+``no_sanitize_coverage`` attribute with Clang and GCC 12 or later; with older
+GCC, objtool removes its calls from ``noinstr`` code on x86-64.
diff --git a/Documentation/dev-tools/gcov.rst b/Documentation/dev-tools/gcov.rst
index b6910c3fc00dd..b4add0af2da2f 100644
--- a/Documentation/dev-tools/gcov.rst
+++ b/Documentation/dev-tools/gcov.rst
@@ -22,6 +22,9 @@ Possible uses:
* minimizing kernel configurations (do I need this option if the
associated code is never run?)
+See Documentation/dev-tools/coverage.rst for the options and interfaces shared
+with the other code coverage implementations.
+
.. _gcov: https://gcc.gnu.org/onlinedocs/gcc/Gcov.html
.. _lcov: https://github.com/linux-test-project/lcov
@@ -180,6 +183,31 @@ b) gcov is run on the BUILD machine
[user@build] gcov -o /tmp/coverage/tmp/out/init main.c
+MC/DC Coverage
+--------------
+
+When using GCC 14 or later with ``CONFIG_COVERAGE_MCDC=y``, Modified
+Condition/Decision Coverage (MC/DC) data is collected alongside standard
+branch coverage. MC/DC verifies that each condition in a decision
+independently affects the decision's outcome.
+
+To view MC/DC data, use::
+
+ gcov --conditions -o /sys/kernel/debug/gcov/path/to/dir file.c
+
+MC/DC coverage is required by safety standards such as DO-178C
+(avionics) and ISO 26262 (automotive).
+
+GCC's condition coverage implementation has a limit of 64 conditions per
+boolean expression, due to the use of 64-bit bitmasks internally.
+Expressions exceeding this limit cannot be instrumented. This does not
+affect the correctness of the kernel; those expressions simply will not
+have MC/DC coverage data.
+
+Note that MC/DC instrumentation increases binary size and execution
+overhead compared to standard gcov profiling.
+
+
Note on compilers
-----------------
diff --git a/Documentation/dev-tools/index.rst b/Documentation/dev-tools/index.rst
index 59cbb77b33ff4..d670c1398e495 100644
--- a/Documentation/dev-tools/index.rst
+++ b/Documentation/dev-tools/index.rst
@@ -23,6 +23,7 @@ Documentation/process/debugging/index.rst
coccinelle
context-analysis
sparse
+ coverage
kcov
gcov
kasan
diff --git a/Documentation/dev-tools/kcov.rst b/Documentation/dev-tools/kcov.rst
index 1a739290c8ecc..98a30a1a3f88a 100644
--- a/Documentation/dev-tools/kcov.rst
+++ b/Documentation/dev-tools/kcov.rst
@@ -12,6 +12,9 @@ To achieve this goal, it does not collect coverage in soft/hard interrupts
(unless remove coverage collection is enabled, see below) and from some
inherently non-deterministic parts of the kernel (e.g. scheduler, locking).
+KCOV is configured next to the other code coverage implementations, see
+Documentation/dev-tools/coverage.rst.
+
Besides collecting code coverage, KCOV can also collect comparison operands.
See the "Comparison operands collection" section for details.
diff --git a/MAINTAINERS b/MAINTAINERS
index d7910586005a1..460d4e5f1b029 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -6636,6 +6636,7 @@ F: drivers/media/platform/chips-media/coda
CODE COVERAGE
M: Sasha Levin <sashal@kernel.org>
S: Maintained
+F: Documentation/dev-tools/coverage.rst
F: kernel/coverage/Kconfig
F: kernel/coverage/Makefile
F: kernel/coverage/core.c
--
2.53.0
^ permalink raw reply related [flat|nested] 10+ messages in thread