openrisc: Add support for KProbes and Kretprobes
Subsystems (3)
A message that is not in the archive (sent off-list or not yet received): [email protected]
v3 cover openrisc: Add support for KProbes and Kretprobes
Hi,
This is v3 of the patch series to add KProbe and Kretprobe support for OpenRISC. KProbes was introduced in v1 [1] while Kretprobes was introduced in v2 [2].
In order to build the kernel with Kprobes and Kretprobes enabled, the following config options are required:
1. CONFIG_HAVE_KPROBES=y
2. CONFIG_KPROBES=y
3. CONFIG_RETHOOK=y
4. CONFIG_KRETPROBES=y
I tested the generic functionality of Kprobes and Kretprobes using the tests located at "lib/tests" [3], samples located at "samples/kprobes" [4], as well as a few test modules that I have published here [5]. The following options are required to build the samples and tests:
1. CONFIG_SAMPLES=y
2. CONFIG_SAMPLE_KPROBES=m
3. CONFIG_SAMPLE_KRETPROBES=m
4. CONFIG_KPROBES_SANITY_TEST=m
I have also added unit tests at "arch/openrisc/kernel/tests" to verify that Kprobes work properly when inserted at branch instructions, and that delay slots are handled correctly. The tests are based on the Kprobe testsuite added for RISC-V. The following options need to be enabled to build the tests:
1. CONFIG_KUNIT=y
2. CONFIG_RUNTIME_KERNEL_TESTING_MENU=y
3. CONFIG_OR_KPROBES_KUNIT=m
Below are the results of the tests and sample modules when run in my environment.
- kretprobe_example:
/home # insmod kretprobe_example.ko
Planted return probe at kernel_clone: (ptrval) /home # ls >/dev/nullkernel_clone returned 35 and took 1302450 ns to execute /home # rmmod kretprobe_example.ko kernel_clone returned 36 and took 1121200 ns to execute kretprobe at (ptrval) unregistered
Missed probing 0 instances of kernel_clone
- test_kprobes:
/home # insmod test_kprobes.ko
KTAP version 1
1..1
KTAP version 1
# Subtest: kprobes_test
# module: test_kprobes
1..5
ok 1 test_kprobe
ok 2 test_kprobes
ok 3 test_kprobe_missed
ok 4 test_kretprobe
ok 5 test_kretprobes
# kprobes_test: pass:5 fail:0 skip:0 total:5
# Totals: pass:5 fail:0 skip:0 total:5
ok 1 kprobes_test
- openrisc_test_kprobes:
/home # insmod openrisc_test_kprobes.ko
KTAP version 1
1..1
KTAP version 1
# Subtest: kprobes_openrisc
# module: openrisc_test_kprobes
1..1
ok 1 test_kprobe_openrisc
ok 1 kprobes_openrisc
v3 adds a few fixes to the patch series based on Sachiko's review comments [6]. I have listed out the differences introduced in each iteration in the following emails.
Thanks,
Sahil
[1] https://lkml.org/lkml/2026/4/8/21
[2] https://lkml.org/lkml/2026/10/1/28
[3] https://github.com/torvalds/linux/tree/master/lib/tests
[4] https://github.com/torvalds/linux/tree/master/samples/kprobes
[5] https://github.com/valdaarhun/or-dev
[6] https://sashiko.dev/#/patchset/20260930203129.51048-1-sahilcdq0%40gmail.com
Sahil Siddiq (4):
openrisc: Add utilities and clean up simulation of instructions
openrisc: Add KProbes
openrisc: Add unit tests for KProbes on branch instructions
openrisc: Add Kretprobes
arch/openrisc/Kconfig | 3 + arch/openrisc/Kconfig.debug | 30 +- arch/openrisc/configs/or1ksim_defconfig | 2 + arch/openrisc/configs/virt_defconfig | 2 + arch/openrisc/include/asm/asm.h | 22 + arch/openrisc/include/asm/break.h | 19 + arch/openrisc/include/asm/cpuinfo.h | 3 + arch/openrisc/include/asm/insn-def.h | 64 ++- arch/openrisc/include/asm/kprobes.h | 77 ++++ arch/openrisc/include/asm/spr_defs.h | 1 + arch/openrisc/kernel/Makefile | 5 +- arch/openrisc/kernel/entry.S | 16 + arch/openrisc/kernel/insn.c | 88 ++++ arch/openrisc/kernel/kprobes.c | 426 ++++++++++++++++++ arch/openrisc/kernel/rethook.c | 32 ++ arch/openrisc/kernel/rethook.h | 8 + arch/openrisc/kernel/rethook_trampoline.S | 111 +++++ arch/openrisc/kernel/setup.c | 4 + arch/openrisc/kernel/tests/Makefile | 3 + arch/openrisc/kernel/tests/test_kprobes.c | 59 +++ arch/openrisc/kernel/tests/test_kprobes.h | 24 + arch/openrisc/kernel/tests/test_kprobes_asm.S | 157 +++++++ arch/openrisc/kernel/traps.c | 82 ++-- arch/openrisc/lib/memcpy.c | 2 + arch/openrisc/lib/memset.S | 4 + arch/openrisc/mm/fault.c | 5 + samples/kprobes/kprobe_example.c | 8 + 27 files changed, 1206 insertions(+), 51 deletions(-) create mode 100644 arch/openrisc/include/asm/asm.h create mode 100644 arch/openrisc/include/asm/break.h create mode 100644 arch/openrisc/include/asm/kprobes.h create mode 100644 arch/openrisc/kernel/insn.c create mode 100644 arch/openrisc/kernel/kprobes.c create mode 100644 arch/openrisc/kernel/rethook.c create mode 100644 arch/openrisc/kernel/rethook.h create mode 100644 arch/openrisc/kernel/rethook_trampoline.S create mode 100644 arch/openrisc/kernel/tests/Makefile create mode 100644 arch/openrisc/kernel/tests/test_kprobes.c create mode 100644 arch/openrisc/kernel/tests/test_kprobes.h create mode 100644 arch/openrisc/kernel/tests/test_kprobes_asm.S
Signature · 1 line
2.55.0
Masami Hiramatsu (Google)
maintainerHi Sahil,
Can you update the series according to the Sashiko's comment[1]?
[1] https://sashiko.dev/#/patchset/20261026201240.107462-3-sahilcdq0%40gmail.com
Also, can you check your git email settings, so that the next version does *NOT* reply to the previous version.
This mail has
Message-ID: <[email protected]>
X-Mailer: git-send-email 2.55.0
In-Reply-To: <[email protected]>
References: <[email protected]>
But I can not find "[email protected]" in the LKML archive.
Also "[PATCH v3 2/4] openrisc: Add KProbes" has
Message-ID: <[email protected]>
X-Mailer: git-send-email 2.55.0
In-Reply-To: <[email protected]>
References: <[email protected]>
This should be in reply to the cover mail
"[email protected]"
Thank you,
Quoted 139 lines · Sahil Siddiq
Hi,
This is v3 of the patch series to add KProbe and Kretprobe support for OpenRISC. KProbes was introduced in v1 [1] while Kretprobes was introduced in v2 [2].
In order to build the kernel with Kprobes and Kretprobes enabled, the following config options are required:
1.CONFIG_HAVE_KPROBES=y
2.CONFIG_KPROBES=y
3.CONFIG_RETHOOK=y
4.CONFIG_KRETPROBES=yI tested the generic functionality of Kprobes and Kretprobes using the tests located at "lib/tests" [3], samples located at "
samples/kprobes" [4], as well as a few test modules that I have published here [5]. The following options are required to build the samples and tests:
1.CONFIG_SAMPLES=y
2.CONFIG_SAMPLE_KPROBES=m
3.CONFIG_SAMPLE_KRETPROBES=m
4.CONFIG_KPROBES_SANITY_TEST=mI have also added unit tests at "
arch/openrisc/kernel/tests" to verify that Kprobes work properly when inserted at branch instructions, and that delay slots are handled correctly. The tests are based on the Kprobe testsuite added for RISC-V. The following options need to be enabled to build the tests:
1.CONFIG_KUNIT=y
2.CONFIG_RUNTIME_KERNEL_TESTING_MENU=y
3.CONFIG_OR_KPROBES_KUNIT=mBelow are the results of the tests and sample modules when run in my environment.
-
kretprobe_example:/home # insmod kretprobe_example.ko
Planted return probe atkernel_clone: (ptrval) /home # ls >/dev/nullkernel_clonereturned 35 and took 1302450 ns to execute /home # rmmod kretprobe_example.kokernel_clonereturned 36 and took 1121200 ns to execute kretprobe at (ptrval) unregistered
Missed probing 0 instances ofkernel_clone-
test_kprobes:/home # insmod test_kprobes.ko
KTAP version 1
1..1
KTAP version 1
# Subtest:kprobes_test
# module:test_kprobes
1..5
ok 1test_kprobe
ok 2test_kprobes
ok 3test_kprobe_missed
ok 4test_kretprobe
ok 5test_kretprobes
#kprobes_test: pass:5 fail:0 skip:0 total:5
# Totals: pass:5 fail:0 skip:0 total:5
ok 1kprobes_test-
openrisc_test_kprobes:/home # insmod openrisc_test_kprobes.ko
KTAP version 1
1..1
KTAP version 1
# Subtest:kprobes_openrisc
# module:openrisc_test_kprobes
1..1
ok 1test_kprobe_openrisc
ok 1kprobes_openriscv3 adds a few fixes to the patch series based on Sachiko's review comments [6]. I have listed out the differences introduced in each iteration in the following emails.
Thanks,
Sahil[1] https://lkml.org/lkml/2026/4/8/21
[2] https://lkml.org/lkml/2026/10/1/28
[3] https://github.com/torvalds/linux/tree/master/lib/tests
[4] https://github.com/torvalds/linux/tree/master/samples/kprobes
[5] https://github.com/valdaarhun/or-dev
[6] https://sashiko.dev/#/patchset/20260930203129.51048-1-sahilcdq0%40gmail.comSahil Siddiq (4):
openrisc: Add utilities and clean up simulation of instructions
openrisc: Add KProbes
openrisc: Add unit tests for KProbes on branch instructions
openrisc: Add Kretprobesarch/openrisc/Kconfig | 3 + arch/openrisc/Kconfig.debug | 30 +- arch/openrisc/configs/or1ksim_defconfig | 2 + arch/openrisc/configs/virt_defconfig | 2 + arch/openrisc/include/asm/asm.h | 22 + arch/openrisc/include/asm/break.h | 19 + arch/openrisc/include/asm/cpuinfo.h | 3 + arch/openrisc/include/asm/insn-def.h | 64 ++- arch/openrisc/include/asm/kprobes.h | 77 ++++ arch/openrisc/include/asm/spr_defs.h | 1 + arch/openrisc/kernel/Makefile | 5 +- arch/openrisc/kernel/entry.S | 16 + arch/openrisc/kernel/insn.c | 88 ++++ arch/openrisc/kernel/kprobes.c | 426 ++++++++++++++++++ arch/openrisc/kernel/rethook.c | 32 ++ arch/openrisc/kernel/rethook.h | 8 + arch/openrisc/kernel/rethook_trampoline.S | 111 +++++ arch/openrisc/kernel/setup.c | 4 + arch/openrisc/kernel/tests/Makefile | 3 + arch/openrisc/kernel/tests/test_kprobes.c | 59 +++ arch/openrisc/kernel/tests/test_kprobes.h | 24 + arch/openrisc/kernel/tests/test_kprobes_asm.S | 157 +++++++ arch/openrisc/kernel/traps.c | 82 ++-- arch/openrisc/lib/memcpy.c | 2 + arch/openrisc/lib/memset.S | 4 + arch/openrisc/mm/fault.c | 5 + samples/kprobes/kprobe_example.c | 8 + 27 files changed, 1206 insertions(+), 51 deletions(-) create mode 100644 arch/openrisc/include/asm/asm.h create mode 100644 arch/openrisc/include/asm/break.h create mode 100644 arch/openrisc/include/asm/kprobes.h create mode 100644 arch/openrisc/kernel/insn.c create mode 100644 arch/openrisc/kernel/kprobes.c create mode 100644 arch/openrisc/kernel/rethook.c create mode 100644 arch/openrisc/kernel/rethook.h create mode 100644 arch/openrisc/kernel/rethook_trampoline.S create mode 100644 arch/openrisc/kernel/tests/Makefile create mode 100644 arch/openrisc/kernel/tests/test_kprobes.c create mode 100644 arch/openrisc/kernel/tests/test_kprobes.h create mode 100644 arch/openrisc/kernel/tests/test_kprobes_asm.SSignature · 1 line
2.55.0
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
Hi Masami,
Quoted 5 lines · Masami Hiramatsu (Google)
Hi Sahil,
Can you update the series according to the Sashiko's comment[1]?
[1] https://sashiko.dev/#/patchset/20261026201240.107462-3-sahilcdq0%40gmail.com
Sure, I'll make those changes along with the ones suggested by Stafford.
Quoted 15 lines
Also, can you check your git email settings, so that the next version does *NOT* reply to the previous version.
This mail has
Message-ID: <[email protected]> X-Mailer: git-send-email 2.55.0 In-Reply-To: <[email protected]> References: <[email protected]>But I can not find "[email protected]" in the LKML archive.
Also "[PATCH v3 2/4] openrisc: Add KProbes" has
Quoted 7 lines
Message-ID: <[email protected]> X-Mailer: git-send-email 2.55.0 In-Reply-To: <[email protected]> References: <[email protected]>This should be in reply to the cover mail
"[email protected]"
Oh, that's weird. Maybe I used the wrong message-id when setting "in-reply-to" using git-send-email. I'll send the next series such that it doesn't reply to the previous version.
Quoted 2 lines
Thank you,
Thanks,
Sahil
PATCH v3 1/4 openrisc: Add utilities and clean up simulation of instructions
In reply to a message not in the archiveIntroduce new instruction-related utilities and macros for OpenRISC. This is in preparation for patches that add tracing support such as KProbes and Kretprobes.
Currently, PC is first updated and then saved in the link register (r9) when simulating l.jal and l.jalr. This can result in a corrupted page table (bad page map in process). Fix this by saving PC in r9 before updating it.
Move branch simulation to its own function, simulate_branch(), so it can be reused. It's already being used by do_illegal_instruction(). It'll also be used by KProbes in the following commit.
Introduce simulate_pc() to simulate l.adrp. KProbes will require this instruction to be simulated as well. simulate_branch() and simulate_pc() need to be handled differently since branch instructions change the value of PC while l.adrp depends on PC but doesn't change its value.
Use a static key to check if delay slots are disabled. Delay slots are a part of the CPU's configuration and won't change at runtime. Since they are often enabled in an OpenRISC CPU, using a static key will reduce the overhead of checking this flag in the default case while processing KProbes inserted at branch instructions and simulating them.
---
Changes v2 -> v3:
- arch/openrisc/kernel/insn.c:
- (simulate_pc):
Handle case when rd=0
Add function to KProbe blacklist
- (simulate_branch): Likewise
- arch/openrisc/kernel/setup.c:
- (setup_arch): Set static key before calling paging_init()
- arch/openrisc/kernel/traps.c:
- (do_trap): Move handling of Kprobes in commit #2
Changes v1 -> v2:
- arch/openrisc/include/asm/cpuinfo.h: Introduce "delay_slot" static key
- arch/openrisc/include/asm/insn-def.h:
- Use macros instead of union
- Use better names for macros
- Use genmask() for masks
- arch/openrisc/kernel/insn.c:
- Use macros instead of magic values
- (simulate_pc): Update PC
- (simulate_branch): Handle rb=r9 in l.jalr simulation
- arch/openrisc/kernel/setup.c: Use "delay slot" static key
- arch/openrisc/kernel/traps.c: Use macros instead of magic values
arch/openrisc/include/asm/cpuinfo.h | 3 + arch/openrisc/include/asm/insn-def.h | 58 ++++++++++++++++-- arch/openrisc/include/asm/spr_defs.h | 1 + arch/openrisc/kernel/Makefile | 2 +- arch/openrisc/kernel/insn.c | 88 ++++++++++++++++++++++++++++ arch/openrisc/kernel/setup.c | 4 ++ arch/openrisc/kernel/traps.c | 53 +++-------------- 7 files changed, 159 insertions(+), 50 deletions(-) create mode 100644 arch/openrisc/kernel/insn.c
arch/openrisc/include/asm/cpuinfo.h +3 -0
@@ -15,6 +15,7 @@#ifndef __ASM_OPENRISC_CPUINFO_H#define __ASM_OPENRISC_CPUINFO_H +#include <linux/jump_label.h> #include <asm/spr.h> #include <asm/spr_defs.h>
@@ -34,6 +35,8 @@ struct cpuinfo_or1k {u16 coreid; }; +DECLARE_STATIC_KEY_TRUE (delay_slot); +extern struct cpuinfo_or1k cpuinfo_or1k[NR_CPUS ];extern void setup_cpuinfo (void );
arch/openrisc/include/asm/insn-def.h +54 -4
67 lines not on this page · raw message
arch/openrisc/include/asm/spr_defs.h +1 -0
@@ -179,6 +179,7 @@#define SPR_CPUCFGR_OF32S 0x00000080/* ORFPX32 supported */ #define SPR_CPUCFGR_OF64S 0x00000100/* ORFPX64 supported */ #define SPR_CPUCFGR_OV64S 0x00000200/* ORVDX64 supported */ +#define SPR_CPUCFGR_ND 0x00000400/* No delay slot */ #define SPR_CPUCFGR_RES 0xfffffc00/* Reserved */ /*
arch/openrisc/kernel/Makefile +1 -1
@@ -5,7 +5,7 @@ always-$(KBUILD_BUILTIN) := vmlinux.lds -obj-y := head.o setup.o or32_ksyms.o process.o dma.o \ +obj-y := head.o insn.o setup.o or32_ksyms.o process.o dma.o \ traps.o time.o irq.o entry.o ptrace.o signal.o \ sys_call_table.o unwinder.o cacheinfo.o
arch/openrisc/kernel/insn.c new file +88 -0
88 lines not on this page · raw message
arch/openrisc/kernel/setup.c +4 -0
@@ -252,6 +252,10 @@ void __init setup_arch(char **cmdline_p)/* perform jump_table sorting before paging_init locks down read only memory */ jump_label_init (); +/* determine if the processor supports delay slots */ +if (mfspr (SPR_CPUCFGR ) &SPR_CPUCFGR_ND ) +static_branch_disable (&delay_slot); +/* paging_init() sets up the MMU and marks all pages as reserved */ paging_init ();
arch/openrisc/kernel/traps.c +8 -45
73 lines not on this page · raw message
Signature · 1 line
2.55.0
Stafford Horne
maintainerRe: [PATCH v3 1/4] openrisc: Add utilities and clean up simulation of instructions
Hi Sahil,
Thanks for your patches, sorry its taken me time to get around to them, my year since summer has been quite hectic.
I will do the review in chunks so give me some time.
Quoted 195 lines · Sahil Siddiq
Introduce new instruction-related utilities and macros for OpenRISC. This is in preparation for patches that add tracing support such as KProbes and Kretprobes.
Currently, PC is first updated and then saved in the link register (r9) when simulating l.jal and l.jalr. This can result in a corrupted page table (bad page map in process). Fix this by saving PC in r9 before updating it.
Move branch simulation to its own function,
simulate_branch(), so it can be reused. It's already being used bydo_illegal_instruction(). It'll also be used by KProbes in the following commit.Introduce
simulate_pc()to simulate l.adrp. KProbes will require this instruction to be simulated as well.simulate_branch()andsimulate_pc()need to be handled differently since branch instructions change the value of PC while l.adrp depends on PC but doesn't change its value.Use a static key to check if delay slots are disabled. Delay slots are a part of the CPU's configuration and won't change at runtime. Since they are often enabled in an OpenRISC CPU, using a static key will reduce the overhead of checking this flag in the default case while processing KProbes inserted at branch instructions and simulating them.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/insn.c:
- (simulate_pc):
Handle case when rd=0
Add function to KProbe blacklist
- (simulate_branch): Likewise
-arch/openrisc/kernel/setup.c:
- (setup_arch): Set static key before callingpaging_init()
-arch/openrisc/kernel/traps.c:
- (do_trap): Move handling of Kprobes in commit #2Changes v1 -> v2:
-arch/openrisc/include/asm/cpuinfo.h: Introduce "delay_slot" static key
-arch/openrisc/include/asm/insn-def.h:
- Use macros instead of union
- Use better names for macros
- Usegenmask()for masks
-arch/openrisc/kernel/insn.c:
- Use macros instead of magic values
- (simulate_pc): Update PC
- (simulate_branch): Handle rb=r9 in l.jalr simulation
-arch/openrisc/kernel/setup.c: Use "delay slot" static key
-arch/openrisc/kernel/traps.c: Use macros instead of magic valuesarch/openrisc/include/asm/cpuinfo.h | 3 + arch/openrisc/include/asm/insn-def.h | 58 ++++++++++++++++-- arch/openrisc/include/asm/spr_defs.h | 1 + arch/openrisc/kernel/Makefile | 2 +- arch/openrisc/kernel/insn.c | 88 ++++++++++++++++++++++++++++ arch/openrisc/kernel/setup.c | 4 ++ arch/openrisc/kernel/traps.c | 53 +++-------------- 7 files changed, 159 insertions(+), 50 deletions(-) create mode 100644 arch/openrisc/kernel/insn.carch/openrisc/include/asm/cpuinfo.h +3
-0@@ -15,6 +15,7 @@#ifndef __ASM_OPENRISC_CPUINFO_H#define __ASM_OPENRISC_CPUINFO_H +#include <linux/jump_label.h> #include <asm/spr.h> #include <asm/spr_defs.h> @@ -34,6 +35,8 @@ struct cpuinfo_or1k {u16 coreid; }; +DECLARE_STATIC_KEY_TRUE (delay_slot); +extern struct cpuinfo_or1k cpuinfo_or1k[NR_CPUS ];extern void setup_cpuinfo (void );arch/openrisc/include/asm/insn-def.h +54
-4@@ -3,13 +3,63 @@* Copyright (C) 2025 Chen Miao */ +#include <asm/spr.h> +#include <asm/spr_defs.h> +#include <linux/bits.h> +#ifndef __ASM_OPENRISC_INSN_DEF_H#define __ASM_OPENRISC_INSN_DEF_H -/* or1k instructions are always 32 bits. */ -#define OPENRISC_INSN_SIZE 4 -/* or1k nop instruction code */ -#define OPENRISC_INSN_NOP 0x15000000U +#define OPENRISC_INSN_CSYNC 0x23000000U +#define OPENRISC_INSN_MACRC 0x18010000U +#define OPENRISC_MASK_MACRC 0xfc01ffffU +#define OPENRISC_INSN_MSYNC 0x22000000U +#define OPENRISC_INSN_NOP 0x15000000U +#define OPENRISC_INSN_PSYNC 0x22800000U +#define OPENRISC_INSN_SYS 0x20000000U +#define OPENRISC_INSN_TRAP 0x21000000U + +#define OPENRISC_OPCODE_ADRP 0x02 +#define OPENRISC_OPCODE_BF 0x04 +#define OPENRISC_OPCODE_BNF 0x03 +#define OPENRISC_OPCODE_J 0x00 +#define OPENRISC_OPCODE_JAL 0x01 +#define OPENRISC_OPCODE_JALR 0x12 +#define OPENRISC_OPCODE_JR 0x11 +#define OPENRISC_OPCODE_LWA 0x1b +#define OPENRISC_OPCODE_MFSPR 0x2d +#define OPENRISC_OPCODE_MTSPR 0x30 +#define OPENRISC_OPCODE_RFE 0x09 +#define OPENRISC_OPCODE_SWA 0x33 + +#define OPENRISC_ADRP_IMM_MASK GENMASK(18, 0) +#define OPENRISC_ADRP_OFFSET_MASK GENMASK(31, 13) +#define OPENRISC_ADRP_IMM_SHIFT 13 +#define OPENRISC_ADRP_REG_MASK GENMASK(25, 0) +#define OPENRISC_ADRP_REG_SHIFT 21 +#define OPENRISC_JUMP_IMM_MASK GENMASK(25, 0) +#define OPENRISC_JUMP_IMM_SHIFT 2 +#define OPENRISC_JUMP_REG_MASK GENMASK(15, 11) +#define OPENRISC_JUMP_REG_SHIFT 11 + +#define OPENRISC_MASK_SYS GENMASK(31, 16) +#define OPENRISC_MASK_TRAP GENMASK(31, 16) +#define OPENRISC_MASK_BCODE GENMASK(15, 0) + +#define OPENRISC_OPCODE_MASK 0x3f +#define OPENRISC_OPCODE_SHIFT 0x1a + +struct pt_regs ; + +#define OPENRISC_INSN_SIZE 4 + +static __always_inline unsigned char get_6_bit_opcode(unsigned long insn) +{ +return (insn >>OPENRISC_OPCODE_SHIFT ) &OPENRISC_OPCODE_MASK ; +} + +void simulate_pc (struct pt_regs *regs,unsigned long jmp); +void simulate_branch (struct pt_regs *regs,unsigned long jmp);#endif /* __ASM_OPENRISC_INSN_DEF_H */ arch/openrisc/include/asm/spr_defs.h +1
-0@@ -179,6 +179,7 @@#define SPR_CPUCFGR_OF32S 0x00000080/* ORFPX32 supported */ #define SPR_CPUCFGR_OF64S 0x00000100/* ORFPX64 supported */ #define SPR_CPUCFGR_OV64S 0x00000200/* ORVDX64 supported */ +#define SPR_CPUCFGR_ND 0x00000400/* No delay slot */ #define SPR_CPUCFGR_RES 0xfffffc00/* Reserved */ /* arch/openrisc/kernel/Makefile +1
-1@@ -5,7 +5,7 @@ always-$(KBUILD_BUILTIN) := vmlinux.lds -obj-y := head.o setup.o or32_ksyms.o process.o dma.o \ +obj-y := head.o insn.o setup.o or32_ksyms.o process.o dma.o \ traps.o time.o irq.o entry.o ptrace.o signal.o \ sys_call_table.o unwinder.o cacheinfo.oarch/openrisc/kernel/insn.c new file +10
-0@@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* OpenRISC instruction utils +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* OpenRISC implementation: +* Copyright (C) 2026 Sahil Siddiq <[email protected]>
arch/openrisc/kernel/insn.c line 20
Quoted 10 lines
arch/openrisc/kernel/insn.c new file +10
-0+*/ + +#include <linux/kprobes.h> +#include <linux/ptrace.h> +#include <asm/insn-def.h> +#include <asm/cpuinfo.h> + +DEFINE_STATIC_KEY_TRUE (delay_slot); + +void simulate_pc (struct pt_regs *regs,unsigned long pc_insn)
Since this simulates l.adrp, maybe the name makes more sense to be called simulate_adrp?
Quoted 24 lines
arch/openrisc/kernel/insn.c new file +24
-0+{ +int page_offset; +unsigned int rd, op; + + page_offset =sign_extend32 ( + (pc_insn &OPENRISC_ADRP_IMM_MASK ) <<OPENRISC_ADRP_IMM_SHIFT ,31 ); + rd = (pc_insn &OPENRISC_ADRP_REG_MASK ) >>OPENRISC_ADRP_REG_SHIFT ; + op =get_6_bit_opcode (pc_insn); + +switch (op) { +case OPENRISC_OPCODE_ADRP : +if (rd !=0 ) + regs->gpr[rd] = page_offset + (regs->pc &OPENRISC_ADRP_OFFSET_MASK ); + regs->pc +=OPENRISC_INSN_SIZE ; +return ; +default : +break ; + } +} +NOKPROBE_SYMBOL (simulate_pc) + +void simulate_branch(struct pt_regs *regs, unsigned long jmp_insn) +{ +int displacement;
arch/openrisc/kernel/insn.c line 54
Quoted 10 lines
arch/openrisc/kernel/insn.c new file +10
-0+unsigned int rb, op, link_offset, temp; + + displacement =sign_extend32 ( + ((jmp_insn) &OPENRISC_JUMP_IMM_MASK ) <<OPENRISC_JUMP_IMM_SHIFT ,27 ); + rb = (jmp_insn &OPENRISC_JUMP_REG_MASK ) >>OPENRISC_JUMP_REG_SHIFT ; + op =get_6_bit_opcode (jmp_insn); + link_offset =OPENRISC_INSN_SIZE ; + +if (static_branch_likely (&delay_slot)) + link_offset <<=1 ;
Why do shift left here instead of += OPENRISC_INSN_SIZE? Since logically we are adding one more insn for the delay slot, not doubling.
However, It may be more efficient to avoid using the alu and write as:
if (static_branch_likely(&delay_slot))
link_offset = 2 * OPENRISC_INSN_SIZE;
else
link_offset = OPENRISC_INSN_SIZE;what do you think?
arch/openrisc/kernel/insn.c line 56
Quoted 2 lines
arch/openrisc/kernel/insn.c new file +2
-0+switch (op) { +case OPENRISC_OPCODE_J :/* l.j */
I think these comments (/* l.j */) are no longer needed sinc you have the named macros.
Quoted 64 lines
arch/openrisc/kernel/insn.c new file +31
-0+ regs->pc += displacement; +return ; +case OPENRISC_OPCODE_JAL :/* l.jal */ + regs->gpr[9 ] = regs->pc + link_offset; + regs->pc += displacement; +return ; +case OPENRISC_OPCODE_BNF :/* l.bnf */ +if (regs->sr &SPR_SR_F ) + regs->pc += link_offset; +else + regs->pc += displacement; +return ; +case OPENRISC_OPCODE_BF :/* l.bf */ +if (regs->sr &SPR_SR_F ) + regs->pc += displacement; +else + regs->pc += link_offset; +return ; +case OPENRISC_OPCODE_JR :/* l.jr */ + regs->pc = rb ==0 ?0 : regs->gpr[rb]; +return ; +case OPENRISC_OPCODE_JALR :/* l.jalr */ + temp = regs->pc + link_offset; + regs->pc = rb ==0 ?0 : regs->gpr[rb]; + regs->gpr[9 ] = temp; +return ; +default : +break ; + } +} +NOKPROBE_SYMBOL (simulate_branch)arch/openrisc/kernel/setup.c +4
-0@@ -252,6 +252,10 @@ void __init setup_arch(char **cmdline_p)/* perform jump_table sorting before paging_init locks down read only memory */ jump_label_init (); +/* determine if the processor supports delay slots */ +if (mfspr (SPR_CPUCFGR ) &SPR_CPUCFGR_ND ) +static_branch_disable (&delay_slot); +/* paging_init() sets up the MMU and marks all pages as reserved */ paging_init ();arch/openrisc/kernel/traps.c +1
-2@@ -32,6 +32,7 @@#include <asm/bug.h> #include <asm/fpu.h> +#include <asm/insn-def.h> #include <asm/io.h> #include <asm/processor.h> #include <asm/unwinder.h> @@ -252,12 +253,12 @@ static inline int in_delay_slot(struct pt_regs *regs) insn = *((unsigned int *)regs->pc); op = insn >>26 ;switch (op) { -case 0x00 :/* l.j */ -case 0x01 :/* l.jal */
arch/openrisc/kernel/traps.c static inline int in_delay_slot(struct pt_regs *regs) · line 261
Quoted 10 lines
arch/openrisc/kernel/traps.c +6
-4-case 0x03 :/* l.bnf */ -case 0x04 :/* l.bf */ -case 0x11 :/* l.jr */ -case 0x12 :/* l.jalr */ +case OPENRISC_OPCODE_J :/* l.j */ +case OPENRISC_OPCODE_JAL :/* l.jal */ +case OPENRISC_OPCODE_BNF :/* l.bnf */ +case OPENRISC_OPCODE_BF :/* l.bf */ +case OPENRISC_OPCODE_JR :/* l.jr */ +case OPENRISC_OPCODE_JALR :/* l.jalr */
Nice cleanup, again I think comments can be removed now.
Quoted 55 lines
arch/openrisc/kernel/traps.c +1
-39return 1 ;default :return 0 ;@@ -269,47 +270,9 @@ static inline int in_delay_slot(struct pt_regs *regs)static inline void adjust_pc (struct pt_regs *regs,unsigned long address) { -int displacement; -unsigned int rb, op, jmp; -if (unlikely (in_delay_slot (regs))) {/* In delay slot, instruction at pc is a branch, simulate it */ - jmp = *((unsigned int *)regs->pc); - - displacement =sign_extend32 (((jmp) &0x3ffffff ) <<2 ,27 ); - rb = (jmp &0x0000ffff ) >>11 ; - op = jmp >>26 ; - -switch (op) { -case 0x00 :/* l.j */ - regs->pc += displacement; -return ; -case 0x01 :/* l.jal */ - regs->pc += displacement; - regs->gpr[9 ] = regs->pc +8 ; -return ; -case 0x03 :/* l.bnf */ -if (regs->sr &SPR_SR_F ) - regs->pc +=8 ; -else - regs->pc += displacement; -return ; -case 0x04 :/* l.bf */ -if (regs->sr &SPR_SR_F ) - regs->pc += displacement; -else - regs->pc +=8 ; -return ; -case 0x11 :/* l.jr */ - regs->pc = regs->gpr[rb]; -return ; -case 0x12 :/* l.jalr */ - regs->pc = regs->gpr[rb]; - regs->gpr[9 ] = regs->pc +8 ; -return ; -default : -break ; - } +simulate_branch (regs, *((unsigned int *)regs->pc)); }else { regs->pc +=4 ; }Signature · 1 line
2.55.0
Re: [PATCH v3 1/4] openrisc: Add utilities and clean up simulation of instructions
Hi Stafford,
Quoted 4 lines · Stafford Horne
Hi Sahil,
Thanks for your patches, sorry its taken me time to get around to them, my year since summer has been quite hectic.
No worries. I completely understand :)
Quoted 1 line
I will do the review in chunks so give me some time.
Thank you for the review.
Quoted 84 lines · Sahil Siddiq
Quoted 83 lines
Introduce new instruction-related utilities and macros for OpenRISC. This is in preparation for patches that add tracing support such as KProbes and Kretprobes.
Currently, PC is first updated and then saved in the link register (r9) when simulating l.jal and l.jalr. This can result in a corrupted page table (bad page map in process). Fix this by saving PC in r9 before updating it.
Move branch simulation to its own function,
simulate_branch(), so it can be reused. It's already being used bydo_illegal_instruction(). It'll also be used by KProbes in the following commit.Introduce
simulate_pc()to simulate l.adrp. KProbes will require this instruction to be simulated as well.simulate_branch()andsimulate_pc()need to be handled differently since branch instructions change the value of PC while l.adrp depends on PC but doesn't change its value.Use a static key to check if delay slots are disabled. Delay slots are a part of the CPU's configuration and won't change at runtime. Since they are often enabled in an OpenRISC CPU, using a static key will reduce the overhead of checking this flag in the default case while processing KProbes inserted at branch instructions and simulating them.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/insn.c:
- (simulate_pc):
Handle case when rd=0
Add function to KProbe blacklist
- (simulate_branch): Likewise
-arch/openrisc/kernel/setup.c:
- (setup_arch): Set static key before callingpaging_init()
-arch/openrisc/kernel/traps.c:
- (do_trap): Move handling of Kprobes in commit #2Changes v1 -> v2:
-arch/openrisc/include/asm/cpuinfo.h: Introduce "delay_slot" static key
-arch/openrisc/include/asm/insn-def.h:
- Use macros instead of union
- Use better names for macros
- Usegenmask()for masks
-arch/openrisc/kernel/insn.c:
- Use macros instead of magic values
- (simulate_pc): Update PC
- (simulate_branch): Handle rb=r9 in l.jalr simulation
-arch/openrisc/kernel/setup.c: Use "delay slot" static key
-arch/openrisc/kernel/traps.c: Use macros instead of magic valuesarch/openrisc/include/asm/cpuinfo.h | 3 + arch/openrisc/include/asm/insn-def.h | 58 ++++++++++++++++-- arch/openrisc/include/asm/spr_defs.h | 1 + arch/openrisc/kernel/Makefile | 2 +- arch/openrisc/kernel/insn.c | 88 ++++++++++++++++++++++++++++ arch/openrisc/kernel/setup.c | 4 ++ arch/openrisc/kernel/traps.c | 53 +++-------------- 7 files changed, 159 insertions(+), 50 deletions(-)create mode 100644
arch/openrisc/kernel/insn.c[...]
arch/openrisc/kernel/insn.c new file +15
-0@@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* OpenRISC instruction utils +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* OpenRISC implementation: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#include <linux/kprobes.h> +#include <linux/ptrace.h> +#include <asm/insn-def.h>
Quoted 8 lines
arch/openrisc/kernel/insn.c line 20
Quoted 5 lines
arch/openrisc/kernel/insn.c new file +5
-0+#include <asm/cpuinfo.h> + +DEFINE_STATIC_KEY_TRUE (delay_slot); + +void simulate_pc (struct pt_regs *regs,unsigned long pc_insn)Since this simulates l.adrp, maybe the name makes more sense to be called
simulate_adrp?
Sure, I'll rename it.
Quoted 29 lines
Quoted 29 lines
arch/openrisc/kernel/insn.c new file +29
-0+{ +int page_offset; +unsigned int rd, op; + + page_offset =sign_extend32 ( + (pc_insn &OPENRISC_ADRP_IMM_MASK ) <<OPENRISC_ADRP_IMM_SHIFT ,31 ); + rd = (pc_insn &OPENRISC_ADRP_REG_MASK ) >>OPENRISC_ADRP_REG_SHIFT ; + op =get_6_bit_opcode (pc_insn); + +switch (op) { +case OPENRISC_OPCODE_ADRP : +if (rd !=0 ) + regs->gpr[rd] = page_offset + (regs->pc &OPENRISC_ADRP_OFFSET_MASK ); + regs->pc +=OPENRISC_INSN_SIZE ; +return ; +default : +break ; + } +} +NOKPROBE_SYMBOL (simulate_pc) + +void simulate_branch(struct pt_regs *regs, unsigned long jmp_insn) +{ +int displacement; +unsigned int rb, op, link_offset, temp; + + displacement =sign_extend32 ( + ((jmp_insn) &OPENRISC_JUMP_IMM_MASK ) <<OPENRISC_JUMP_IMM_SHIFT ,27 ); + rb = (jmp_insn &OPENRISC_JUMP_REG_MASK ) >>OPENRISC_JUMP_REG_SHIFT ;
Quoted 8 lines
arch/openrisc/kernel/insn.c line 54
Quoted 5 lines
arch/openrisc/kernel/insn.c new file +5
-0+ op =get_6_bit_opcode (jmp_insn); + link_offset =OPENRISC_INSN_SIZE ; + +if (static_branch_likely (&delay_slot)) + link_offset <<=1 ;Why do shift left here instead of +=
OPENRISC_INSN_SIZE? Since logically we are adding one more insn for the delay slot, not doubling.
Since link_offset is initialized to OPENRISC_INSN_SIZE, shifting it to the left by 1 would update link_offset to 2 * OPENRISC_INSN_SIZE. This is a little more obscure than explicitly setting it to 2 * OPENRISC_INSN_SIZE. Initially, I thought the left shift operator might be less expensive than multiplying.
I was going through mor1kx's design and noticed there's also a pipelined implementation for the multiplier [1]. But it looks like the implementation for shifting is simpler and can be done in one cycle. Please let me know if my understanding is incorrect here.
Quoted 8 lines
However, It may be more efficient to avoid using the alu and write as:
if (static_branch_likely(&delay_slot)) link_offset = 2 * OPENRISC_INSN_SIZE; else link_offset = OPENRISC_INSN_SIZE;what do you think?
I am not sure if I have understood the alu part. WIll it be more efficient because 2 * OPENRISC_INSN_SIZE will be optimized by the compiler to simply be a single number? So no alu operation will be required, just one store operation?
Quoted 6 lines
arch/openrisc/kernel/insn.c line 56
Quoted 3 lines
arch/openrisc/kernel/insn.c new file +2
-0+switch (op) { +case OPENRISC_OPCODE_J :/* l.j */ I think these comments (/* l.j */) are no longer needed sinc you have the named macros.
Got it, I'll remove the comments.
Quoted 68 lines
Quoted 68 lines
arch/openrisc/kernel/insn.c new file +31
-0+ regs->pc += displacement; +return ; +case OPENRISC_OPCODE_JAL :/* l.jal */ + regs->gpr[9 ] = regs->pc + link_offset; + regs->pc += displacement; +return ; +case OPENRISC_OPCODE_BNF :/* l.bnf */ +if (regs->sr &SPR_SR_F ) + regs->pc += link_offset; +else + regs->pc += displacement; +return ; +case OPENRISC_OPCODE_BF :/* l.bf */ +if (regs->sr &SPR_SR_F ) + regs->pc += displacement; +else + regs->pc += link_offset; +return ; +case OPENRISC_OPCODE_JR :/* l.jr */ + regs->pc = rb ==0 ?0 : regs->gpr[rb]; +return ; +case OPENRISC_OPCODE_JALR :/* l.jalr */ + temp = regs->pc + link_offset; + regs->pc = rb ==0 ?0 : regs->gpr[rb]; + regs->gpr[9 ] = temp; +return ; +default : +break ; + } +} +NOKPROBE_SYMBOL (simulate_branch)arch/openrisc/kernel/setup.c +4
-0@@ -252,6 +252,10 @@ void __init setup_arch(char **cmdline_p)/* perform jump_table sorting before paging_init locks down read only memory */ jump_label_init (); +/* determine if the processor supports delay slots */ +if (mfspr (SPR_CPUCFGR ) &SPR_CPUCFGR_ND ) +static_branch_disable (&delay_slot); +/* paging_init() sets up the MMU and marks all pages as reserved */ paging_init ();arch/openrisc/kernel/traps.c +1
-6@@ -32,6 +32,7 @@#include <asm/bug.h> #include <asm/fpu.h> +#include <asm/insn-def.h> #include <asm/io.h> #include <asm/processor.h> #include <asm/unwinder.h> @@ -252,12 +253,12 @@ static inline int in_delay_slot(struct pt_regs *regs) insn = *((unsigned int *)regs->pc); op = insn >>26 ;switch (op) { -case 0x00 :/* l.j */ -case 0x01 :/* l.jal */ -case 0x03 :/* l.bnf */ -case 0x04 :/* l.bf */ -case 0x11 :/* l.jr */ -case 0x12 :/* l.jalr */
Quoted 8 lines
arch/openrisc/kernel/traps.c static inline int in_delay_slot(struct pt_regs *regs) · line 261
Quoted 6 lines
arch/openrisc/kernel/traps.c +6
-0+case OPENRISC_OPCODE_J :/* l.j */ +case OPENRISC_OPCODE_JAL :/* l.jal */ +case OPENRISC_OPCODE_BNF :/* l.bnf */ +case OPENRISC_OPCODE_BF :/* l.bf */ +case OPENRISC_OPCODE_JR :/* l.jr */ +case OPENRISC_OPCODE_JALR :/* l.jalr */ Nice cleanup, again I think comments can be removed now.
Sure, I'll remove these comments as well.
Quoted 47 lines
Quoted 47 lines
arch/openrisc/kernel/traps.c +0
-38return 1 ;default :return 0 ;@@ -269,47 +270,9 @@ static inline int in_delay_slot(struct pt_regs *regs)static inline void adjust_pc (struct pt_regs *regs,unsigned long address) { -int displacement; -unsigned int rb, op, jmp; -if (unlikely (in_delay_slot (regs))) {/* In delay slot, instruction at pc is a branch, simulate it */ - jmp = *((unsigned int *)regs->pc); - - displacement =sign_extend32 (((jmp) &0x3ffffff ) <<2 ,27 ); - rb = (jmp &0x0000ffff ) >>11 ; - op = jmp >>26 ; - -switch (op) { -case 0x00 :/* l.j */ - regs->pc += displacement; -return ; -case 0x01 :/* l.jal */ - regs->pc += displacement; - regs->gpr[9 ] = regs->pc +8 ; -return ; -case 0x03 :/* l.bnf */ -if (regs->sr &SPR_SR_F ) - regs->pc +=8 ; -else - regs->pc += displacement; -return ; -case 0x04 :/* l.bf */ -if (regs->sr &SPR_SR_F ) - regs->pc += displacement; -else - regs->pc +=8 ; -return ; -case 0x11 :/* l.jr */ - regs->pc = regs->gpr[rb]; -return ; -case 0x12 :/* l.jalr */ - regs->pc = regs->gpr[rb]; - regs->gpr[9 ] = regs->pc +8 ; -return ; -default : -break ;
Quoted 8 lines
Quoted 8 lines
arch/openrisc/kernel/traps.c +1
-1- } +simulate_branch (regs, *((unsigned int *)regs->pc)); }else { regs->pc +=4 ; }Signature · 1 line
2.55.0
Thanks,
Sahil
[1] https://github.com/openrisc/mor1kx/blob/master/rtl/verilog/mor1kx_execute_alu.v#L224-L377
Stafford Horne
maintainerRe: [PATCH v3 1/4] openrisc: Add utilities and clean up simulation of instructions
Quoted 147 lines · Sahil
Hi Stafford,
Quoted 4 lines · Stafford Horne
Hi Sahil,
Thanks for your patches, sorry its taken me time to get around to them, my year since summer has been quite hectic.
No worries. I completely understand :)
Quoted 1 line
I will do the review in chunks so give me some time.
Thank you for the review.
Quoted 84 lines · Sahil Siddiq
Quoted 83 lines
Introduce new instruction-related utilities and macros for OpenRISC. This is in preparation for patches that add tracing support such as KProbes and Kretprobes.
Currently, PC is first updated and then saved in the link register (r9) when simulating l.jal and l.jalr. This can result in a corrupted page table (bad page map in process). Fix this by saving PC in r9 before updating it.
Move branch simulation to its own function,
simulate_branch(), so it can be reused. It's already being used bydo_illegal_instruction(). It'll also be used by KProbes in the following commit.Introduce
simulate_pc()to simulate l.adrp. KProbes will require this instruction to be simulated as well.simulate_branch()andsimulate_pc()need to be handled differently since branch instructions change the value of PC while l.adrp depends on PC but doesn't change its value.Use a static key to check if delay slots are disabled. Delay slots are a part of the CPU's configuration and won't change at runtime. Since they are often enabled in an OpenRISC CPU, using a static key will reduce the overhead of checking this flag in the default case while processing KProbes inserted at branch instructions and simulating them.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/insn.c:
- (simulate_pc):
Handle case when rd=0
Add function to KProbe blacklist
- (simulate_branch): Likewise
-arch/openrisc/kernel/setup.c:
- (setup_arch): Set static key before callingpaging_init()
-arch/openrisc/kernel/traps.c:
- (do_trap): Move handling of Kprobes in commit #2Changes v1 -> v2:
-arch/openrisc/include/asm/cpuinfo.h: Introduce "delay_slot" static key
-arch/openrisc/include/asm/insn-def.h:
- Use macros instead of union
- Use better names for macros
- Usegenmask()for masks
-arch/openrisc/kernel/insn.c:
- Use macros instead of magic values
- (simulate_pc): Update PC
- (simulate_branch): Handle rb=r9 in l.jalr simulation
-arch/openrisc/kernel/setup.c: Use "delay slot" static key
-arch/openrisc/kernel/traps.c: Use macros instead of magic valuesarch/openrisc/include/asm/cpuinfo.h | 3 + arch/openrisc/include/asm/insn-def.h | 58 ++++++++++++++++-- arch/openrisc/include/asm/spr_defs.h | 1 + arch/openrisc/kernel/Makefile | 2 +- arch/openrisc/kernel/insn.c | 88 ++++++++++++++++++++++++++++ arch/openrisc/kernel/setup.c | 4 ++ arch/openrisc/kernel/traps.c | 53 +++-------------- 7 files changed, 159 insertions(+), 50 deletions(-)create mode 100644
arch/openrisc/kernel/insn.c[...]
arch/openrisc/kernel/insn.c new file +15
-0@@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* OpenRISC instruction utils +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* OpenRISC implementation: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#include <linux/kprobes.h> +#include <linux/ptrace.h> +#include <asm/insn-def.h> Quoted 8 lines
arch/openrisc/kernel/insn.c line 20
Quoted 5 lines
arch/openrisc/kernel/insn.c new file +5
-0+#include <asm/cpuinfo.h> + +DEFINE_STATIC_KEY_TRUE (delay_slot); + +void simulate_pc (struct pt_regs *regs,unsigned long pc_insn)Since this simulates l.adrp, maybe the name makes more sense to be called
simulate_adrp?Sure, I'll rename it.
Quoted 29 lines
Quoted 29 lines
arch/openrisc/kernel/insn.c new file +29
-0+{ +int page_offset; +unsigned int rd, op; + + page_offset =sign_extend32 ( + (pc_insn &OPENRISC_ADRP_IMM_MASK ) <<OPENRISC_ADRP_IMM_SHIFT ,31 ); + rd = (pc_insn &OPENRISC_ADRP_REG_MASK ) >>OPENRISC_ADRP_REG_SHIFT ; + op =get_6_bit_opcode (pc_insn); + +switch (op) { +case OPENRISC_OPCODE_ADRP : +if (rd !=0 ) + regs->gpr[rd] = page_offset + (regs->pc &OPENRISC_ADRP_OFFSET_MASK ); + regs->pc +=OPENRISC_INSN_SIZE ; +return ; +default : +break ; + } +} +NOKPROBE_SYMBOL (simulate_pc) + +void simulate_branch(struct pt_regs *regs, unsigned long jmp_insn) +{ +int displacement; +unsigned int rb, op, link_offset, temp; + + displacement =sign_extend32 ( + ((jmp_insn) &OPENRISC_JUMP_IMM_MASK ) <<OPENRISC_JUMP_IMM_SHIFT ,27 ); + rb = (jmp_insn &OPENRISC_JUMP_REG_MASK ) >>OPENRISC_JUMP_REG_SHIFT ;Quoted 8 lines
arch/openrisc/kernel/insn.c line 54
Quoted 5 lines
arch/openrisc/kernel/insn.c new file +5
-0+ op =get_6_bit_opcode (jmp_insn); + link_offset =OPENRISC_INSN_SIZE ; + +if (static_branch_likely (&delay_slot)) + link_offset <<=1 ;Why do shift left here instead of +=
OPENRISC_INSN_SIZE? Since logically we are adding one more insn for the delay slot, not doubling.
Quoted 8 lines
Since
link_offsetis initialized toOPENRISC_INSN_SIZE, shifting it to the left by 1 would updatelink_offsetto 2 *OPENRISC_INSN_SIZE. This is a little more obscure than explicitly setting it to 2 *OPENRISC_INSN_SIZE. Initially, I thought the left shift operator might be less expensive than multiplying.I was going through mor1kx's design and noticed there's also a pipelined implementation for the multiplier [1]. But it looks like the implementation for shifting is simpler and can be done in one cycle. Please let me know if my understanding is incorrect here.
That's correct, but my suggestion was to use += OPENRISC_INSN_SIZE instead of 2 *.
Quoted 7 lines
Quoted 7 lines
However, It may be more efficient to avoid using the alu and write as:
if (static_branch_likely(&delay_slot)) link_offset = 2 * OPENRISC_INSN_SIZE; else link_offset = OPENRISC_INSN_SIZE;
Quoted 5 lines
Quoted 1 line
what do you think?
I am not sure if I have understood the alu part. WIll it be more efficient because 2 *
OPENRISC_INSN_SIZEwill be optimized by the compiler to simply be a single number? So no alu operation will be required, just one store operation?
Yup, since 2 * OPENRISC_INSN_SIZE is a constant expression the compiler will replace it with 8. Then the above code would be just one store operation, something like:
if (static_branch_likely(&delay_slot))
link_offset = 8;
else
link_offset = 4;Quoted 8 lines
Quoted 6 lines
arch/openrisc/kernel/insn.c line 56
Quoted 3 lines
arch/openrisc/kernel/insn.c new file +2
-0+switch (op) { +case OPENRISC_OPCODE_J :/* l.j */ I think these comments (/* l.j */) are no longer needed sinc you have the named macros.
Got it, I'll remove the comments.
[snip]
Thanks,
-Stafford
Re: [PATCH v3 1/4] openrisc: Add utilities and clean up simulation of instructions
Quoted 63 lines · Stafford Horne
Quoted 37 lines · Sahil
Hi Stafford,
Quoted 4 lines · Stafford Horne
Hi Sahil,
Thanks for your patches, sorry its taken me time to get around to them, my year since summer has been quite hectic.
No worries. I completely understand :)
Quoted 1 line
I will do the review in chunks so give me some time.
Thank you for the review.
Quoted 14 lines · Sahil Siddiq
Quoted 13 lines
Introduce new instruction-related utilities and macros for OpenRISC. This is in preparation for patches that add tracing support such as KProbes and Kretprobes.
[...]arch/openrisc/kernel/insn.c new file +9
-0+ +void simulate_branch (struct pt_regs *regs,unsigned long jmp_insn) +{ +int displacement; +unsigned int rb, op, link_offset, temp; + + displacement =sign_extend32 ( + ((jmp_insn) &OPENRISC_JUMP_IMM_MASK ) <<OPENRISC_JUMP_IMM_SHIFT ,27 ); + rb = (jmp_insn &OPENRISC_JUMP_REG_MASK ) >>OPENRISC_JUMP_REG_SHIFT ;Quoted 8 lines
arch/openrisc/kernel/insn.c line 54
Quoted 5 lines
arch/openrisc/kernel/insn.c new file +5
-0+ op =get_6_bit_opcode (jmp_insn); + link_offset =OPENRISC_INSN_SIZE ; + +if (static_branch_likely (&delay_slot)) + link_offset <<=1 ;Why do shift left here instead of +=
OPENRISC_INSN_SIZE? Since logically we are adding one more insn for the delay slot, not doubling.Quoted 8 lines
Since
link_offsetis initialized toOPENRISC_INSN_SIZE, shifting it to the left by 1 would updatelink_offsetto 2 *OPENRISC_INSN_SIZE. This is a little more obscure than explicitly setting it to 2 *OPENRISC_INSN_SIZE. Initially, I thought the left shift operator might be less expensive than multiplying.I was going through mor1kx's design and noticed there's also a pipelined implementation for the multiplier [1]. But it looks like the implementation for shifting is simpler and can be done in one cycle. Please let me know if my understanding is incorrect here.
That's correct, but my suggestion was to use +=
OPENRISC_INSN_SIZEinstead of 2 *.Quoted 7 lines
Quoted 7 lines
However, It may be more efficient to avoid using the alu and write as:
if (static_branch_likely(&delay_slot)) link_offset = 2 * OPENRISC_INSN_SIZE; else link_offset = OPENRISC_INSN_SIZE;Quoted 5 lines
Quoted 1 line
what do you think?
I am not sure if I have understood the alu part. WIll it be more efficient because 2 *
OPENRISC_INSN_SIZEwill be optimized by the compiler to simply be a single number? So no alu operation will be required, just one store operation?
Quoted 9 lines
Yup, since 2 *
OPENRISC_INSN_SIZEis a constant expression the compiler will replace it with 8. Then the above code would be just one store operation, something like:if (static_branch_likely(&delay_slot)) link_offset = 8; else link_offset = 4;
Got it. Thank you for the clarification. Based on our conversation in commit #3 regarding delay slots, it should now be fine to remove the static key and handle delay slots unconditionally.
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
Review
Quoted 3 lines
(quoted diff) +2
-0+ switch (op) { + case OPENRISC_OPCODE_J: /* l.j */I think these comments (/* l.j */) are no longer needed sinc you have the named macros.
Quoted 6 lines
Quoted 1 line
Got it, I'll remove the comments.
[snip]
Thanks,
-Stafford
Thanks,
Sahil
PATCH v3 2/4 openrisc: Add KProbes
In reply to a message not in the archiveAdd KProbes support for OpenRISC. This work is primarily based on similar work done for LoongArch, MIPS and RISC-V.
KProbes make it possible to trap at almost any address in the kernel to collect performance/debugging info.
---
Changes v2 -> v3:
- arch/openrisc/kernel/kprobes.c:
- (kprobe_local_irq_save): New function
- (kprobe_local_irq_restore): Likewise
- (arch_prepare_kprobe): Use copy_from_kernel_nofault()
- (post_kprobe_handler): Enable preemption before returning early for reentered KProbe
- (setup_singlestep): Disable IRQs by toggling bits in SR register
- (kprobe_breakpoint_handler): Use result from get_kernel_nofault()
- (kprobe_fault_handler):
Enable preemption after handling reentered KProbe
Restore IRQs by toggling bits in SR register
Changes v1 -> v2:
- arch/openrisc/include/asm/kprobes.h:
- (struct prev_kprobe): Add restore_pc
- (struct kprobe_ctlblk): Move restore_pc from global "struct arch_specific_insn"
- arch/openrisc/kernel/kprobes.c:
- Use macros instead of magic values
- Use "get_kernel_nofault" instead of directly dereferencing address
- (insns_need_simulation): Use "daley slot" static key
- (arch_prepare_kprobe): Prevent KProbe insertion if instruction in delay slot also requires simulation
- (save_previous_kprobe): Use "restore_pc"
- (restore_previous_kprobe): Likewise
- (post_kprobe_handler): Don't re-enable preemption if KProbe is nested
- (setup_singlestep): Use "restore_pc"
- (reenter_kprobe): Return false in case of unrecoverable KProbe
- (kprobe_singlestep_handler): Enable interrupt in pt_regs->sr
- (kprobe_fault_handler): Likewise
arch/openrisc/Kconfig | 1 + arch/openrisc/configs/or1ksim_defconfig | 2 + arch/openrisc/configs/virt_defconfig | 2 + arch/openrisc/include/asm/asm.h | 22 ++ arch/openrisc/include/asm/break.h | 19 ++ arch/openrisc/include/asm/insn-def.h | 6 + arch/openrisc/include/asm/kprobes.h | 77 +++++ arch/openrisc/kernel/Makefile | 1 + arch/openrisc/kernel/entry.S | 16 + arch/openrisc/kernel/kprobes.c | 426 ++++++++++++++++++++++++ arch/openrisc/kernel/traps.c | 29 ++ arch/openrisc/lib/memcpy.c | 2 + arch/openrisc/lib/memset.S | 4 + arch/openrisc/mm/fault.c | 5 + samples/kprobes/kprobe_example.c | 8 + 15 files changed, 620 insertions(+) create mode 100644 arch/openrisc/include/asm/asm.h create mode 100644 arch/openrisc/include/asm/break.h create mode 100644 arch/openrisc/include/asm/kprobes.h create mode 100644 arch/openrisc/kernel/kprobes.c
arch/openrisc/Kconfig +1 -0
@@ -27,6 +27,7 @@ config OPENRISC select HAVE_ARCH_JUMP_LABEL select HAVE_ARCH_JUMP_LABEL_RELATIVE select HAVE_PCI + select HAVE_KPROBES select HAVE_UID16 select HAVE_PAGE_SIZE_8KB select HAVE_REGS_AND_STACK_ACCESS_API
arch/openrisc/configs/or1ksim_defconfig +2 -0
@@ -10,7 +10,9 @@ CONFIG_EXPERT=y # CONFIG_KALLSYMS is not set CONFIG_BUILTIN_DTB_NAME="or1ksim" CONFIG_HZ_100=y +CONFIG_OPENRISC=y CONFIG_JUMP_LABEL=y +CONFIG_KPROBES=y CONFIG_MODULES=y # CONFIG_BLOCK is not set CONFIG_SLUB_TINY=y
arch/openrisc/configs/virt_defconfig +2 -0
@@ -11,8 +11,10 @@ CONFIG_OPENRISC_HAVE_INST_SEXT=y CONFIG_NR_CPUS=8 CONFIG_SMP=y CONFIG_HZ_100=y +CONFIG_OPENRISC=y # CONFIG_OPENRISC_NO_SPR_SR_DSX is not set CONFIG_JUMP_LABEL=y +CONFIG_KPROBES=y # CONFIG_COMPAT_BRK is not set CONFIG_NET=y CONFIG_PACKET=y
arch/openrisc/include/asm/asm.h new file +22 -0
@@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* Macros for OpenRISC asm +* +* Linux architectural port borrowing nearly verbatim from +* LoongArch and Arm. All original copyrights apply as per +* the original source declaration. +*/ + +#ifndef __ASM_ASM_H +#define __ASM_ASM_H + +#ifdef CONFIG_KPROBES +#define _ASM_NOKPROBE (symbol) \ + .pushsection "_kprobe_blacklist", "aw"; \ + .long symbol; \ + .popsection +#else +#define _ASM_NOKPROBE (symbol) +#endif + +#endif /* __ASM_ASM_H */
arch/openrisc/include/asm/break.h new file +19 -0
@@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* OpenRISC trap codes used internally by the kernel +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* Modifications for the OpenRISC architecture: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#ifndef __ASM_BREAK_H +#define __ASM_BREAK_H + +#define BRK_KPROBE_BP 512/* Kprobe break */ +#define BRK_KPROBE_SSTEPBP 1024/* Kprobe single-step software implementation */ + +#endif /* __ASM_BREAK_H */
arch/openrisc/include/asm/insn-def.h +6 -0
@@ -54,6 +54,12 @@ struct pt_regs;#define OPENRISC_INSN_SIZE 4 +/* Helpers for working with l.trap */ +static inline unsigned long __emit_trap (unsigned long code) +{ +return (code &OPENRISC_MASK_BCODE ) |OPENRISC_INSN_TRAP ; +} + static __always_inline unsigned char get_6_bit_opcode(unsigned long insn) {return (insn >>OPENRISC_OPCODE_SHIFT ) &OPENRISC_OPCODE_MASK ;
arch/openrisc/include/asm/kprobes.h new file +77 -0
77 lines not on this page · raw message
arch/openrisc/kernel/Makefile +1 -0
@@ -14,6 +14,7 @@ obj-$(CONFIG_SMP) += smp.o sync-timer.o obj-$(CONFIG_STACKTRACE) += stacktrace.o obj-$(CONFIG_MODULES) += module.o obj-$(CONFIG_OF) += prom.o +obj-$(CONFIG_KPROBES) += kprobes.o obj-y += patching.o clean:
arch/openrisc/kernel/entry.S +16 -0
@@ -15,6 +15,7 @@ #include <linux/linkage.h> #include <linux/pgtable.h> +#include <asm/asm.h> #include <asm/processor.h> #include <asm/unistd.h> #include <asm/thread_info.h>
@@ -640,6 +641,7 @@ ENTRY(_sys_call_handler) /* r30 is the only register we clobber in the fast path */ /* r30 already saved */ /* l.sw PT_GPR30(r1),r30 */ +_ASM_NOKPROBE(_sys_call_handler) _syscall_check_trace_enter: /* syscalls run with interrupts enabled */
@@ -652,12 +654,14 @@ _syscall_check_trace_enter: l.sfne r30,r0 l.bf _syscall_trace_enter l.nop +_ASM_NOKPROBE(_syscall_check_trace_enter) _syscall_check: /* Ensure that the syscall number is reasonable */ l.sfgeui r11,__NR_syscalls l.bf _syscall_badsys l.nop +_ASM_NOKPROBE(_syscall_check) _syscall_call: l.movhi r29,hi(sys_call_table)
@@ -668,12 +672,14 @@ _syscall_call: l.jalr r29 l.nop +_ASM_NOKPROBE(_syscall_call) _syscall_return: /* All syscalls return here... just pay attention to ret_from_fork * which does it in a round-about way. */ l.sw PT_GPR11(r1),r11 // save return value +_ASM_NOKPROBE(_syscall_return) #if 0 _syscall_debug:
@@ -708,6 +714,7 @@ _syscall_check_trace_leave: l.sfne r30,r0 l.bf _syscall_trace_leave l.nop +_ASM_NOKPROBE(_syscall_check_trace_leave) /* This is where the exception-return code begins... interrupts need to be * disabled the rest of the way here because we can't afford to miss any
@@ -744,6 +751,7 @@ _syscall_check_work: /* _work_pending needs to be called with interrupts disabled */ l.j _work_pending l.nop +_ASM_NOKPROBE(_syscall_check_work) _syscall_resume_userspace: // ENABLE_INTERRUPTS(r29)
@@ -800,6 +808,7 @@ _syscall_resume_userspace: l.mtspr r0,r13,SPR_EPCR_BASE l.mtspr r0,r15,SPR_ESR_BASE l.rfe +_ASM_NOKPROBE(_syscall_resume_userspace) /* End of hot path! * Keep the below tracing and error handling out of the hot path...
@@ -829,6 +838,7 @@ _syscall_trace_enter: l.j _syscall_check l.lwz r8,PT_GPR8(r1) +_ASM_NOKPROBE(_syscall_trace_enter) _syscall_trace_leave: l.jal do_syscall_trace_leave
@@ -836,6 +846,7 @@ _syscall_trace_leave: l.j _syscall_check_work l.nop +_ASM_NOKPROBE(_syscall_trace_leave) _syscall_badsys: /* Here we effectively pretend to have executed an imaginary
@@ -845,6 +856,7 @@ _syscall_badsys: */ l.j _syscall_return l.addi r11,r0,-ENOSYS +_ASM_NOKPROBE(_syscall_badsys) /******* END SYSCALL HANDLING *******/
@@ -870,6 +882,7 @@ EXCEPTION_ENTRY(_trap_handler) l.j _ret_from_exception l.nop +_ASM_NOKPROBE(_trap_handler) /* ---[ 0xf00: Reserved exception ]-------------------------------------- */
@@ -1004,6 +1017,8 @@ ENTRY(_ret_from_exception) l.nop l.j _resume_userspace l.nop +_ASM_NOKPROBE(_ret_from_exception) +_ASM_NOKPROBE(_ret_from_intr) ENTRY(ret_from_fork) l.jal schedule_tail
@@ -1038,6 +1053,7 @@ ENTRY(ret_from_fork) l.j _syscall_return l.nop +_ASM_NOKPROBE(ret_from_fork) /* ========================================================[ switch ] === */
arch/openrisc/kernel/kprobes.c new file +426 -0
426 lines not on this page · raw message
arch/openrisc/kernel/traps.c +29 -0
@@ -30,10 +30,12 @@#include <linux/kallsyms.h> #include <linux/uaccess.h> +#include <asm/break.h> #include <asm/bug.h> #include <asm/fpu.h> #include <asm/insn-def.h> #include <asm/io.h> +#include <asm/kprobes.h> #include <asm/processor.h> #include <asm/unwinder.h> #include <asm/sections.h>
@@ -216,10 +218,37 @@ asmlinkage void do_trap(struct pt_regs *regs, unsigned long address)if (user_mode (regs)) {force_sig_fault (SIGTRAP ,TRAP_BRKPT , (void __user *)regs->pc); }else { +unsigned long trap, bcode; + +if (get_kernel_nofault (trap, (unsigned long *)regs->pc) <0 ) +return ; + +/* +* Trap instruction was probably removed and no further processing +* is required. +*/ +if ((trap &OPENRISC_MASK_TRAP ) !=OPENRISC_INSN_TRAP ) +return ; + + bcode = (trap &OPENRISC_MASK_BCODE ); +switch (bcode) { +case BRK_KPROBE_BP : +if (kprobe_breakpoint_handler (regs)) +return ; +break ; +case BRK_KPROBE_SSTEPBP : +if (kprobe_singlestep_handler (regs)) +return ; +break ; +default : +break ; + } +pr_emerg ("KERNEL: Illegal trap exception 0x%.8lx\n" , regs->pc);die ("Die:" , regs,SIGILL ); } } +NOKPROBE_SYMBOL (do_trap) asmlinkage void do_unaligned_access(struct pt_regs *regs, unsigned long address) {
arch/openrisc/lib/memcpy.c +2 -0
@@ -16,6 +16,7 @@#include <linux/export.h> +#include <linux/kprobes.h> #include <linux/string.h> #ifdef CONFIG_OR1K_1200
@@ -122,4 +123,5 @@ void *memcpy(void *dest, __const void *src, __kernel_size_t n) }#endif +NOKPROBE_SYMBOL (memcpy);EXPORT_SYMBOL (memcpy);
arch/openrisc/lib/memset.S +4 -0
@@ -9,6 +9,8 @@ * Copyright (C) 2015 Olof Kindgren <[email protected]> */ +#include <asm/asm.h> + .global memset .type memset, @function memset:
@@ -92,3 +94,5 @@ memset: 4: l.jr r9 l.ori r11, r3, 0 + +_ASM_NOKPROBE(memset)
arch/openrisc/mm/fault.c +5 -0
@@ -14,6 +14,7 @@#include <linux/mm.h> #include <linux/interrupt.h> #include <linux/extable.h> +#include <linux/kprobes.h> #include <linux/sched/signal.h> #include <linux/perf_event.h>
@@ -55,6 +56,9 @@ asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long address, tsk = current; +if (kprobe_page_fault (regs, vector)) +return ; +/* * We fault-in kernel-space virtual memory on-demand. The * 'reference' page table is init_mm.pgd.
@@ -351,3 +355,4 @@ asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long address,return ; } } +NOKPROBE_SYMBOL (do_page_fault)
samples/kprobes/kprobe_example.c +8 -0
@@ -59,6 +59,10 @@ static int __kprobes handler_pre(struct kprobe *p, struct pt_regs *regs)pr_info ("<%s> p->addr = 0x%p, era = 0x%lx, estat = 0x%lx\n" , p->symbol_name, p->addr, regs->csr_era, regs->csr_estat);#endif +#ifdef CONFIG_OPENRISC +pr_info ("<%s> p->addr = 0x%p, pc = 0x%lx, status = 0x%lx\n" , + p->symbol_name, p->addr, regs->pc, regs->sr); +#endif /* A dump_stack() here will give a stack backtrace */ return 0 ;
@@ -100,6 +104,10 @@ static void __kprobes handler_post(struct kprobe *p, struct pt_regs *regs,pr_info ("<%s> p->addr = 0x%p, estat = 0x%lx\n" , p->symbol_name, p->addr, regs->csr_estat);#endif +#ifdef CONFIG_OPENRISC +pr_info ("<%s> p->addr = 0x%p, status = 0x%lx\n" , + p->symbol_name, p->addr, regs->sr); +#endif }static int __init kprobe_init (void )
Signature · 1 line
2.55.0
Re: [PATCH v3 2/4] openrisc: Add KProbes
Hi,
I have two queries in this commit.
Quoted 20 lines · Sahil Siddiq
Add KProbes support for OpenRISC. This work is primarily based on similar work done for LoongArch, MIPS and RISC-V.
KProbes make it possible to trap at almost any address in the kernel to collect performance/debugging info.
[...]
arch/openrisc/include/asm/kprobes.h new file +6
-0@@ -0,0 +1,77 @@ + +struct prev_kprobe { +struct kprobe *kp; +unsigned int status; +unsigned long restore_pc; +};
arch/openrisc/include/asm/kprobes.h line 58
Quoted 10 lines
arch/openrisc/include/asm/kprobes.h new file +10
-0+ +/* per-cpu kprobe control block */ +struct kprobe_ctlblk { +unsigned int kprobe_status; +unsigned long irq_flags; +/* address of next instruction in case of SSOL */ +unsigned long restore_pc; +struct prev_kprobe prev_kprobe; +}; +
There was a review comment from Sashiko about saving "irq_flags" in "struct prev_kprobe". I am not sure if that's actually required.
My understanding is that a KProbe will be reentered if a probe is hit before single-stepping (e.g. a probe in the pre-handler) or after it (e.g. a probe in the post-handler). If a KProbe is reentered before single-stepping, nothing will be present in kprobe_ctlblk.irq_flags that requires restoration. So, it doesn't need to be saved in prev_kprobe. And if the KProbe is reentered after single-stepping, by that point the value in kprobe_ctlblk.irq_flags should have already been restored (i.e. IRQs should be reenabled by then) and so it shouldn't need saving in prev_kprobe.
Could you please let me know if I am missing something, or if my reasoning is sound?
Quoted 14 lines
[...]
arch/openrisc/kernel/kprobes.c new file +6
-0@@ -0,0 +1,426 @@ + +int kprobe_fault_handler (struct pt_regs *regs,int trapnr) +{ +struct kprobe *cur =kprobe_running (); +struct kprobe_ctlblk *kcb =get_kprobe_ctlblk (); +
arch/openrisc/kernel/kprobes.c line 408
Quoted 10 lines
arch/openrisc/kernel/kprobes.c new file +10
-0+switch (kcb->kprobe_status) { +case KPROBE_HIT_SS : +case KPROBE_REENTER : +/* +* The instruction being single-stepped caused a page fault. +* Reset the current KProbe and set PC to the probe's address. +* Then allow the page fault handler to continue as usual. +*/ +instruction_pointer_set (regs, (unsigned long )cur->addr); +
There was another review comment from Sashiko. It stated that in the case of a page fault which is triggered in the delay slot of a jump-and-link instruction, resetting PC to the branch instruction can corrupt the state. It theorized that this is due to the modification made to regs->gpr[9] (the link register) in "simulate_branch()".
I haven't really understood why the state would get corrupted in this case. Rewinding PC to the branch instruction implies it'll get executed again. If it gets re-executed, the value in regs->gpr[9] should also get re-evaluated and it should hold the correct value after re-execution.
arch/openrisc/kernel/kprobes.c line 420
Quoted 13 lines
arch/openrisc/kernel/kprobes.c new file +12
-0+if (kcb->kprobe_status ==KPROBE_REENTER ) +restore_previous_kprobe (kcb); +else +reset_current_kprobe (); + +kprobe_local_irq_restore (kcb, regs); +preempt_enable_no_resched (); +break ; + } + +return 0 ; +}
Thanks,
Sahil
[1] https://sashiko.dev/#/patchset/20260407185650.79816-1-sahilcdq0%40gmail.com?part=2 (1st comment)
[2] https://sashiko.dev/#/patchset/20260930203129.51048-1-sahilcdq0%40gmail.com?part=2 (6th comment)
[email protected]
AI reviewRe: [PATCH v3 2/4] openrisc: Add KProbes
In reply to Sahil SiddiqThank you for your contribution! Sashiko AI review found 8 potential issue(s) to consider: - [Critical] openrisc: kprobes: kprobe_local_irq_restore() clobbers SR condition flags - [High] openrisc…
Thank you for your contribution! Sashiko AI review found 8 potential issue(s) to consider:
- [Critical] openrisc: kprobes: kprobe_local_irq_restore() clobbers SR condition flags
- [High] openrisc: kprobes: save_previous_kprobe() fails to preserve irq_flags
- [High] openrisc: kprobes: uninitialized next_insn and unvalidated delay slot
- [High] openrisc: mm: do_page_fault() calls kprobe_page_fault() before vmalloc_fault
- [High] openrisc: kprobes: broken fault recovery in kprobe_fault_handler()
- [High] openrisc: kprobes: missing SMP icache invalidation on text patching
- [High] openrisc: kprobes: missing _ASM_NOKPROBE on exception return and fault paths
- [Medium] openrisc: kprobes: kprobe_breakpoint_handler() fallthrough on reentry error --
commit 6ecc71ed745d7593292c3d83156be5a2c1382625
Author: Sahil Siddiq <[email protected]>
openrisc: Add KProbes
This commit adds KProbes support for the OpenRISC architecture, including instruction simulation for branches and PC-relative instructions, out-of-line single-stepping using software breakpoints, and trap/fault handler integration.
Quoted 4 lines
arch/openrisc/kernel/entry.S +0
-0
[ ... ]
arch/openrisc/kernel/entry.S ENTRY(_ret_from_exception) · line 1021
Quoted 6 lines
arch/openrisc/kernel/entry.S +2
-0@@ -1004,6 +1017,8 @@ ENTRY(_ret_from_exception) l.nop l.j _resume_userspace l.nop +_ASM_NOKPROBE(_ret_from_exception) +_ASM_NOKPROBE(_ret_from_intr)
[Severity: High]
Are the remaining exception return labels and low-level fault entry stubs also supposed to be blacklisted with _ASM_NOKPROBE?
_ASM_NOKPROBE(symbol) only blacklists the symbol range up to the next symbol in kallsyms. In arch/openrisc/kernel/entry.S, _ret_from_exception immediately branches backwards to _restore_all (taken on all kernel-mode exception returns, including _trap_handler) or jumps backwards to _resume_userspace and _work_pending:
arch/openrisc/kernel/entry.S:
_resume_userspace:
...
_work_pending:
...
_restore_all:
...
RESTORE_ALL
ENTRY(_ret_from_intr)
ENTRY(_ret_from_exception)
l.lwz r4,PT_SR(r1)
l.andi r3,r4,SPR_SR_SM
l.sfeqi r3,0
l.bnf _restore_all
l.nop
l.j _resume_userspace
l.nop
_ASM_NOKPROBE(_ret_from_exception)
_ASM_NOKPROBE(_ret_from_intr)Because _resume_userspace, _work_pending, _restore_all, and skip_hardirqs_on are separate symbols preceding _ret_from_exception, they are not covered by _ASM_NOKPROBE(_ret_from_exception). Probing _restore_all causes _trap_handler to trap recursively on return and clobbers SPR_EPCR_BASE, SPR_ESR_BASE, and r1 inside RESTORE_ALL.
Similarly, the page-fault and exception entry stubs in arch/openrisc/kernel/entry.S (_dtlb_miss_page_fault_handler, _data_page_fault_handler, _itlb_miss_page_fault_handler, _insn_page_fault_handler, _bus_fault_handler, _illegal_instruction_handler, _alignment_handler, _external_irq_handler, and _timer_handler) and the MMU-off TLB miss handlers in arch/openrisc/kernel/head.S (dtlb_miss_handler and itlb_miss_handler, which live in .text and execute before SPR_EPCR_BASE and SPR_ESR_BASE are saved) lack _ASM_NOKPROBE annotations.
[ ... ]
Quoted 6 lines
arch/openrisc/kernel/kprobes.c new file +0
-0@@ -0,0 +1,426 @@
[ ... ]
Quoted 47 lines
arch/openrisc/kernel/kprobes.c new file +47
-0+int arch_prepare_kprobe (struct kprobe *p) +{ +kprobe_opcode_t insn; +kprobe_opcode_t prev_insn, next_insn; +bool exec_delay_slot = false; + +/* Attempt to probe at unaligned address */ +if ((unsigned long )p->addr &0x3 ) +return -EILSEQ ; + +if (unlikely (copy_from_kernel_nofault (&insn, p->addr,OPENRISC_INSN_SIZE ))) +return -EFAULT ; + + p->opcode = insn; + +if (insn_not_supported (insn)) { +pr_notice ("Can't insert KProbe at blacklisted instruction.\n" ); +return -EINVAL ; + } + +if (copy_from_kernel_nofault (&prev_insn, p->addr -1 , +OPENRISC_INSN_SIZE ) ==0 &&is_branch_insn (prev_insn)) { +if (static_branch_likely (&delay_slot)) { +pr_notice ("Can't insert KProbe in delay slot.\n" ); +return -EINVAL ; + } + } + +if (copy_from_kernel_nofault (&next_insn, p->addr +1 ,OPENRISC_INSN_SIZE ) ==0 && +insns_need_simulation (next_insn, &exec_delay_slot) &&is_branch_insn (insn)) { +if (static_branch_likely (&delay_slot)) { +pr_notice ("Can't insert KProbe if following instruction is in a delay slot and depends on PC.\n" ); +return -EINVAL ; + } + } + +if (insns_need_simulation (insn, &exec_delay_slot) && !exec_delay_slot) { + p->ainsn.insn =NULL ; + }else { +/* +* Single step probed instruction or, in case of branch instructions, single +* step instruction in delay slot. +*/ + p->ainsn.insn =get_insn_slot (); +if (!p->ainsn.insn) +return -ENOMEM ; +
arch/openrisc/kernel/kprobes.c line 159
Quoted 10 lines
arch/openrisc/kernel/kprobes.c new file +10
-0+if (exec_delay_slot) +patch_insn_write (p->ainsn.insn, next_insn); +else +patch_insn_write (p->ainsn.insn, p->opcode); +patch_insn_write (&p->ainsn.insn[1 ],KPROBE_SSTEPBP_INSN ); + } + +return 0 ; +} +NOKPROBE_SYMBOL (arch_prepare_kprobe);
[Severity: High]
Can arch_prepare_kprobe() patch uninitialized stack bytes or unsupported delay-slot instructions into p->ainsn.insn?
There appear to be three issues with how prev_insn and next_insn are validated in arch_prepare_kprobe():
1. next_insn is declared uninitialized on the stack. When p->addr points to a branch instruction with delay slots enabled and copy_from_kernel_nofault(&next_insn, p->addr + 1, OPENRISC_INSN_SIZE) returns an error, the first if statement simply evaluates to false without returning -EFAULT. Subsequent execution calls insns_need_simulation(insn, &exec_delay_slot), which sets exec_delay_slot = true, and then writes the uninitialized next_insn variable into the executable slot via patch_insn_write(p->ainsn.insn, next_insn).
2. When exec_delay_slot is true, next_insn is placed into p->ainsn.insn[0] to be single-stepped out of line, but insn_not_supported(next_insn) is never checked. A branch whose delay slot contains an instruction rejected by insn_not_supported() (such as l.mfspr, l.mtspr, l.lwa, l.swa, l.trap, l.sys, or l.rfe) will bypass the instruction blacklist.
3. Reading prev_insn from p->addr - 1 via copy_from_kernel_nofault() inspects patched kernel text directly without checking get_kprobe(p->addr - 1). If an armed kprobe already exists on a branch instruction at p->addr - 1, the memory at p->addr - 1 holds KPROBE_BP_INSN rather than the original branch opcode, so is_branch_insn(prev_insn) returns false and allows a second kprobe to be registered inside the branch's delay slot at p->addr.
Quoted 4 lines
arch/openrisc/kernel/kprobes.c new file +4
-0+ +void arch_arm_kprobe (struct kprobe *p) +{ +patch_insn_write (p->addr,KPROBE_BP_INSN );
arch/openrisc/kernel/kprobes.c line 173
Quoted 10 lines
arch/openrisc/kernel/kprobes.c new file +10
-0+flush_insn_slot (p); +} +NOKPROBE_SYMBOL (arch_arm_kprobe); + +void arch_disarm_kprobe (struct kprobe *p) +{ +patch_insn_write (p->addr, p->opcode); +flush_insn_slot (p); +} +NOKPROBE_SYMBOL (arch_disarm_kprobe);
[Severity: High]
How are instruction caches synchronized across CPUs on SMP when kprobes are prepared, armed, or disarmed?
In arch/openrisc/include/asm/kprobes.h, flush_insn_slot(p) is defined as a no-op:
#define flush_insn_slot(p) do { } while (0)And patch_insn_write() only flushes the local CPU's dcache and icache via local SPR writes. On SMP systems (such as virt_defconfig where CONFIG_SMP=y and CONFIG_KPROBES=y), remote CPUs can retain stale instructions in their icache.
In particular, if CPU A disarms a kprobe via arch_disarm_kprobe(), CPU B may still fetch the stale KPROBE_BP_INSN from its local icache and enter do_trap():
arch/openrisc/kernel/traps.c:do_trap() {
...
if (get_kernel_nofault(trap, (unsigned long *)regs->pc) < 0)
return;
/*
* Trap instruction was probably removed and no further processing
* is required.
*/
if ((trap & OPENRISC_MASK_TRAP) != OPENRISC_INSN_TRAP)
return;
...
}Because get_kernel_nofault() reads the restored non-trap opcode from the dcache, do_trap() returns to the same regs->pc without invalidating the local icache, causing CPU B to trap repeatedly in an infinite loop on the stale icache line.
[ ... ]
Quoted 5 lines
arch/openrisc/kernel/kprobes.c new file +5
-0+static void save_previous_kprobe (struct kprobe_ctlblk *kcb) +{ + kcb->prev_kprobe.kp =kprobe_running (); + kcb->prev_kprobe.status = kcb->kprobe_status; + kcb->prev_kprobe.restore_pc = kcb->restore_pc;
arch/openrisc/kernel/kprobes.c line 204
Quoted 10 lines
arch/openrisc/kernel/kprobes.c new file +10
-0+} +NOKPROBE_SYMBOL (save_previous_kprobe); + +static void restore_previous_kprobe (struct kprobe_ctlblk *kcb) +{ + kcb->kprobe_status = kcb->prev_kprobe.status; + kcb->restore_pc = kcb->prev_kprobe.restore_pc; +set_current_kprobe (kcb->prev_kprobe.kp); +} +NOKPROBE_SYMBOL (restore_previous_kprobe);
[Severity: High]
Should struct prev_kprobe and save_previous_kprobe() also save and restore kcb->irq_flags?
When an outer kprobe enters setup_singlestep(), kprobe_local_irq_save() stores the original interrupt-enabled regs->sr into kcb->irq_flags and clears SPR_SR_IEE | SPR_SR_TEE in regs->sr. If a nested kprobe is then hit while kcb->kprobe_status is KPROBE_HIT_SS, reenter_kprobe() calls setup_singlestep(p, regs, kcb, 1), which calls save_previous_kprobe(kcb) and then kprobe_local_irq_save(kcb, regs).
Because save_previous_kprobe() does not preserve kcb->irq_flags, the nested kprobe_local_irq_save() overwrites kcb->irq_flags with the nested trap's regs->sr (which has SPR_SR_IEE | SPR_SR_TEE cleared). When the outer kprobe later completes single-stepping in kprobe_singlestep_handler(), kprobe_local_irq_restore() restores the clobbered kcb->irq_flags, leaving local interrupts and timer ticks permanently disabled on that CPU.
Also, in kprobe_fault_handler(), restore_previous_kprobe(kcb) is called before kprobe_local_irq_restore(kcb, regs), which would restore the outer kprobe's irq_flags into kcb before restoring the inner faulted kprobe's irq_flags into regs->sr.
Quoted 13 lines
arch/openrisc/kernel/kprobes.c new file +13
-0+ +/* +* kprobe_local_irq_(save|restore) disable/enable interrupts +* on exiting from the exception handler respectively. This is +* achieved by toggling the IEE and TEE bits in regs->sr with +* the changes taking effect after returning from the exception +* handler. +* +* Interrupts need to be disabled for the period during which an +* instruction is single-stepped. +*/ +static void __kprobes kprobe_local_irq_save (struct kprobe_ctlblk *kcb, +struct pt_regs *regs)
arch/openrisc/kernel/kprobes.c line 227
Quoted 10 lines
arch/openrisc/kernel/kprobes.c new file +10
-0+{ + kcb->irq_flags = regs->sr; + regs->sr = (regs->sr & ~(SPR_SR_IEE |SPR_SR_TEE )) |ARCH_IRQ_DISABLED ; +} + +static void __kprobes kprobe_local_irq_restore (struct kprobe_ctlblk *kcb, +struct pt_regs *regs) +{ + regs->sr = kcb->irq_flags; +}
[Severity: Critical]
Does kprobe_local_irq_restore() clobber architectural condition flags updated by the single-stepped instruction?
On OpenRISC, regs->sr (the Supervision Register) contains not only the interrupt enable bits (SPR_SR_IEE | SPR_SR_TEE) but also the ALU and comparison status flags: SPR_SR_F (condition flag), SPR_SR_CY (carry flag), and SPR_SR_OV (overflow flag).
In setup_singlestep(), kprobe_local_irq_save() snapshots the entire pre-instruction regs->sr into kcb->irq_flags. After the instruction in cur->ainsn.insn[0] is single-stepped and updates SPR_SR_F, SPR_SR_CY, or SPR_SR_OV, kprobe_singlestep_handler() calls kprobe_local_irq_restore(), which overwrites the entire regs->sr with the pre-instruction kcb->irq_flags.
Whenever a kprobe is placed on a comparison instruction (such as l.sfeq or l.sfne), a flag-modifying arithmetic instruction, or a branch with such an instruction in its delay slot, the flag update is lost and subsequent conditional branches (l.bf / l.bnf) or conditional moves (l.cmov) can take the wrong path. Should kprobe_local_irq_save() and kprobe_local_irq_restore() only save and restore the (SPR_SR_IEE | SPR_SR_TEE) bits in regs->sr?
[ ... ]
Quoted 47 lines
arch/openrisc/kernel/kprobes.c new file +47
-0+bool kprobe_breakpoint_handler (struct pt_regs *regs) +{ +struct kprobe *p, *curr_kprobe; +struct kprobe_ctlblk *kcb; +kprobe_opcode_t *addr = (kprobe_opcode_t *)regs->pc; +kprobe_opcode_t insn; + +/* +* We don't want to be preempted for the entire +* duration of kprobe processing. +*/ +preempt_disable (); + + kcb =get_kprobe_ctlblk (); + curr_kprobe =kprobe_running (); + p =get_kprobe (addr); +if (p) { +if (curr_kprobe) { +if (reenter_kprobe (p, regs, kcb)) +return true; + }else { +/* Probe hit */ +set_current_kprobe (p); + kcb->kprobe_status =KPROBE_HIT_ACTIVE ; +/* +* If there's no pre-handler or it returns 0, continue +* processing the KProbe as usual. A non-zero return +* value implies the saved registers have been modified +* and the execution path might deviate from what's +* expected. Reset the KProbe and return. +*/ +if (!p->pre_handler || !p->pre_handler (p, regs)) { +setup_singlestep (p, regs, kcb,0 ); + }else { +reset_current_kprobe (); +preempt_enable_no_resched (); + } +return true; + } + } + +/* +* The breakpoint instruction was removed right after we hit it +* possibly by another cpu. If the original instruction was also +* a trap instruction then return to the trap handler for further +* processing, else no further processing is required. +*/
arch/openrisc/kernel/kprobes.c line 374
Quoted 10 lines
arch/openrisc/kernel/kprobes.c new file +10
-0+if (get_kernel_nofault (insn, addr) <0 + || (insn &OPENRISC_MASK_TRAP ) !=OPENRISC_INSN_TRAP ) { +preempt_enable_no_resched (); +return true; + } + +preempt_enable_no_resched (); +return false; +} +NOKPROBE_SYMBOL (kprobe_breakpoint_handler);
[Severity: Medium]
What happens in kprobe_breakpoint_handler() when reenter_kprobe() returns false?
If curr_kprobe is non-NULL and reenter_kprobe(p, regs, kcb) returns false (for example, when kcb->kprobe_status == KPROBE_REENTER), execution falls out of the if (p) block into the disarmed-breakpoint check at the bottom of kprobe_breakpoint_handler(). If the probe is concurrently disarmed or if get_kernel_nofault() fails, kprobe_breakpoint_handler() will return true instead of failing; otherwise it returns false with current_kprobe still set and the outer kprobe's preempt_disable() still held.
[ ... ]
Quoted 18 lines
arch/openrisc/kernel/kprobes.c new file +18
-0+int kprobe_fault_handler (struct pt_regs *regs,int trapnr) +{ +struct kprobe *cur =kprobe_running (); +struct kprobe_ctlblk *kcb =get_kprobe_ctlblk (); + +switch (kcb->kprobe_status) { +case KPROBE_HIT_SS : +case KPROBE_REENTER : +/* +* The instruction being single-stepped caused a page fault. +* Reset the current KProbe and set PC to the probe's address. +* Then allow the page fault handler to continue as usual. +*/ +instruction_pointer_set (regs, (unsigned long )cur->addr); + +if (kcb->kprobe_status ==KPROBE_REENTER ) +restore_previous_kprobe (kcb); +else
arch/openrisc/kernel/kprobes.c line 421
Quoted 10 lines
arch/openrisc/kernel/kprobes.c new file +10
-0+reset_current_kprobe (); + +kprobe_local_irq_restore (kcb, regs); +preempt_enable_no_resched (); +break ; + } + +return 0 ; +} +NOKPROBE_SYMBOL (kprobe_fault_handler);
[Severity: High]
Does kprobe_fault_handler() need to handle faults during KPROBE_HIT_ACTIVE / KPROBE_HIT_SSDONE and faults on delay-slot instructions?
There look to be a few issues in kprobe_fault_handler():
1. KPROBE_HIT_ACTIVE and KPROBE_HIT_SSDONE are not handled in the switch statement. If a user-registered pre_handler or post_handler (such as a BPF or ftrace kprobe handler) triggers a page fault via copy_from_kernel_nofault() or copy_from_user_nofault(), kprobe_fault_handler() does not invoke fixup_exception() / search_exception_tables() and returns 0. In task context, do_page_fault() in arch/openrisc/mm/fault.c then re-enables interrupts and calls mmap_read_lock(mm) while preemption and pagefaults are disabled.
2. In the KPROBE_HIT_SS and KPROBE_REENTER cases, regs->pc is unconditionally set to (unsigned long)cur->addr. However, if cur->opcode is a branch instruction with delay slots enabled, setup_singlestep() has already run simulate_branch() (updating regs->pc and overwriting r9 for l.jal / l.jalr), and the instruction being single-stepped in cur->ainsn.insn[0] is the delay-slot instruction from cur->addr + 1. Rewinding regs->pc to cur->addr means exception table lookups in do_page_fault() search for the branch address cur->addr instead of the faulting delay-slot address cur->addr + 1, or re-execute the branch with r9 already overwritten.
3. Under KPROBE_HIT_SS and KPROBE_REENTER, kprobe_fault_handler() does not verify that cur->ainsn.insn is non-NULL and that instruction_pointer(regs) matches (unsigned long)cur->ainsn.insn before rewinding regs->pc.
[ ... ]
Quoted 13 lines
arch/openrisc/mm/fault.c +1
-0@@ -14,6 +14,7 @@#include <linux/mm.h> #include <linux/interrupt.h> #include <linux/extable.h> +#include <linux/kprobes.h> #include <linux/sched/signal.h> #include <linux/perf_event.h>
arch/openrisc/mm/fault.c asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long address, · line 64
Quoted 9 lines
arch/openrisc/mm/fault.c +3
-0@@ -55,6 +56,9 @@ asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long address, tsk = current; +if (kprobe_page_fault (regs, vector)) +return ; +/* * We fault-in kernel-space virtual memory on-demand. The * 'reference' page table is init_mm.pgd.
[Severity: High]
Should kprobe_page_fault() be called after the vmalloc_fault check in do_page_fault()?
In arch/openrisc/mm/fault.c, vmalloc mappings are lazily synchronized from init_mm.pgd into current_pgd[cpu] via the vmalloc_fault path right below this check:
arch/openrisc/mm/fault.c:do_page_fault() {
...
if (kprobe_page_fault(regs, vector))
return;
...
if (address >= VMALLOC_START &&
(vector != 0x300 && vector != 0x400) &&
!user_mode(regs))
goto vmalloc_fault;
...
}Because kprobe SSOL instruction pages (p->ainsn.insn) are allocated from vmalloc space via get_insn_slot(), the first time a process hits a kprobe and jumps to p->ainsn.insn (or single-steps an instruction that accesses vmalloc or module memory), an ITLB/DTLB miss triggers do_page_fault() to lazily populate current_pgd[cpu] from init_mm.pgd.
Calling kprobe_page_fault() before the vmalloc_fault check causes kprobe_fault_handler() to intercept this lazy vmalloc fault while in KPROBE_HIT_SS, abort single-stepping, reset regs->pc back to cur->addr, and skip post_handler. Once vmalloc_fault finishes updating the PGD and returns, execution resumes at cur->addr and hits the kprobe breakpoint a second time (and if cur->addr was a branch instruction such as l.jalr r9, simulate_branch() already overwrote r9 before the ITLB miss on p->ainsn.insn).
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Stafford Horne
maintainerRe: [PATCH v3 2/4] openrisc: Add KProbes
In reply to Sahil SiddiqQuoted 75 lines · Sahil Siddiq
Add KProbes support for OpenRISC. This work is primarily based on similar work done for LoongArch, MIPS and RISC-V.
KProbes make it possible to trap at almost any address in the kernel to collect performance/debugging info.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/kprobes.c:
- (kprobe_local_irq_save): New function
- (kprobe_local_irq_restore): Likewise
- (arch_prepare_kprobe): Usecopy_from_kernel_nofault()
- (post_kprobe_handler): Enable preemption before returning early for reentered KProbe
- (setup_singlestep): Disable IRQs by toggling bits in SR register
- (kprobe_breakpoint_handler): Use result fromget_kernel_nofault()
- (kprobe_fault_handler):
Enable preemption after handling reentered KProbe
Restore IRQs by toggling bits in SR registerChanges v1 -> v2:
-arch/openrisc/include/asm/kprobes.h:
- (structprev_kprobe): Addrestore_pc
- (structkprobe_ctlblk): Moverestore_pcfrom global "structarch_specific_insn"
-arch/openrisc/kernel/kprobes.c:
- Use macros instead of magic values
- Use "get_kernel_nofault" instead of directly dereferencing address
- (insns_need_simulation): Use "daley slot" static key
- (arch_prepare_kprobe): Prevent KProbe insertion if instruction in delay slot also requires simulation
- (save_previous_kprobe): Use "restore_pc"
- (restore_previous_kprobe): Likewise
- (post_kprobe_handler): Don't re-enable preemption if KProbe is nested
- (setup_singlestep): Use "restore_pc"
- (reenter_kprobe): Return false in case of unrecoverable KProbe
- (kprobe_singlestep_handler): Enable interrupt inpt_regs->sr
- (kprobe_fault_handler): Likewisearch/openrisc/Kconfig | 1 + arch/openrisc/configs/or1ksim_defconfig | 2 + arch/openrisc/configs/virt_defconfig | 2 + arch/openrisc/include/asm/asm.h | 22 ++ arch/openrisc/include/asm/break.h | 19 ++ arch/openrisc/include/asm/insn-def.h | 6 + arch/openrisc/include/asm/kprobes.h | 77 +++++ arch/openrisc/kernel/Makefile | 1 + arch/openrisc/kernel/entry.S | 16 + arch/openrisc/kernel/kprobes.c | 426 ++++++++++++++++++++++++ arch/openrisc/kernel/traps.c | 29 ++ arch/openrisc/lib/memcpy.c | 2 + arch/openrisc/lib/memset.S | 4 + arch/openrisc/mm/fault.c | 5 + samples/kprobes/kprobe_example.c | 8 + 15 files changed, 620 insertions(+) create mode 100644 arch/openrisc/include/asm/asm.h create mode 100644 arch/openrisc/include/asm/break.h create mode 100644 arch/openrisc/include/asm/kprobes.h create mode 100644 arch/openrisc/kernel/kprobes.carch/openrisc/Kconfig +1
-0@@ -27,6 +27,7 @@ config OPENRISC select HAVE_ARCH_JUMP_LABEL select HAVE_ARCH_JUMP_LABEL_RELATIVE select HAVE_PCI + select HAVE_KPROBES select HAVE_UID16 select HAVE_PAGE_SIZE_8KB select HAVE_REGS_AND_STACK_ACCESS_APIarch/openrisc/configs/or1ksim_defconfig +0
-0
arch/openrisc/configs/or1ksim_defconfig CONFIG_EXPERT=y · line 13
Quoted 4 lines
arch/openrisc/configs/or1ksim_defconfig +1
-0@@ -10,7 +10,9 @@ CONFIG_EXPERT=y # CONFIG_KALLSYMS is not set CONFIG_BUILTIN_DTB_NAME="or1ksim" CONFIG_HZ_100=y +CONFIG_OPENRISC=y
I am not sure this is needed, did you generate this file with make savedefconfig? I thought CONFIG_OPENRISC would be set for every openrisc build by default so not needed in the *_defconfig.
Quoted 145 lines
arch/openrisc/configs/or1ksim_defconfig +1
-0CONFIG_JUMP_LABEL=y +CONFIG_KPROBES=y CONFIG_MODULES=y # CONFIG_BLOCK is not set CONFIG_SLUB_TINY=yarch/openrisc/configs/virt_defconfig +2
-0@@ -11,8 +11,10 @@ CONFIG_OPENRISC_HAVE_INST_SEXT=y CONFIG_NR_CPUS=8 CONFIG_SMP=y CONFIG_HZ_100=y +CONFIG_OPENRISC=y # CONFIG_OPENRISC_NO_SPR_SR_DSX is not set CONFIG_JUMP_LABEL=y +CONFIG_KPROBES=y # CONFIG_COMPAT_BRK is not set CONFIG_NET=y CONFIG_PACKET=yarch/openrisc/include/asm/asm.h new file +22
-0@@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* Macros for OpenRISC asm +* +* Linux architectural port borrowing nearly verbatim from +* LoongArch and Arm. All original copyrights apply as per +* the original source declaration. +*/ + +#ifndef __ASM_ASM_H +#define __ASM_ASM_H + +#ifdef CONFIG_KPROBES +#define _ASM_NOKPROBE (symbol) \ + .pushsection "_kprobe_blacklist", "aw"; \ + .long symbol; \ + .popsection +#else +#define _ASM_NOKPROBE (symbol) +#endif + +#endif /* __ASM_ASM_H */ arch/openrisc/include/asm/break.h new file +19
-0@@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* OpenRISC trap codes used internally by the kernel +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* Modifications for the OpenRISC architecture: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#ifndef __ASM_BREAK_H +#define __ASM_BREAK_H + +#define BRK_KPROBE_BP 512/* Kprobe break */ +#define BRK_KPROBE_SSTEPBP 1024/* Kprobe single-step software implementation */ + +#endif /* __ASM_BREAK_H */ arch/openrisc/include/asm/insn-def.h +6
-0@@ -54,6 +54,12 @@ struct pt_regs;#define OPENRISC_INSN_SIZE 4 +/* Helpers for working with l.trap */ +static inline unsigned long __emit_trap (unsigned long code) +{ +return (code &OPENRISC_MASK_BCODE ) |OPENRISC_INSN_TRAP ; +} + static __always_inline unsigned char get_6_bit_opcode(unsigned long insn) {return (insn >>OPENRISC_OPCODE_SHIFT ) &OPENRISC_OPCODE_MASK ;arch/openrisc/include/asm/kprobes.h new file +49
-0@@ -0,0 +1,77 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* OpenRISC Linux +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* OpenRISC implementation: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#ifndef __ASM_OPENRISC_KPROBES_H +#define __ASM_OPENRISC_KPROBES_H + +#include <asm-generic/kprobes.h> + +#ifdef CONFIG_KPROBES +#include <asm/break.h> +#include <asm/cacheflush.h> + +#define __ARCH_WANT_KPROBES_INSN_SLOT + +struct pt_regs ; +struct kprobe ; + +typedef u32 kprobe_opcode_t ; + +/* +* MAX_INSN_SIZE is used as the number of slots in an executable +* page for single-stepping out of line (SSOL). We need two slots +* since we single-step using software breakpoints. The probed +* instruction is placed in the first slot with a breakpoint +* instruction in the second slot. +*/ +#define MAX_INSN_SIZE 2 + +/* Architecture specific copy of original instruction */ +struct arch_specific_insn { +/* copy of original instruction */ +kprobe_opcode_t *insn; +}; + +struct prev_kprobe { +struct kprobe *kp; +unsigned int status; +unsigned long restore_pc; +}; +
arch/openrisc/include/asm/kprobes.h line 59
Quoted 10 lines
arch/openrisc/include/asm/kprobes.h new file +10
-0+/* per-cpu kprobe control block */ +struct kprobe_ctlblk { +unsigned int kprobe_status; +unsigned long irq_flags; +/* address of next instruction in case of SSOL */ +unsigned long restore_pc; +struct prev_kprobe prev_kprobe; +}; + +#define flush_insn_slot (p) do { } while (0)
On openrisc I think we need to implement flush_insn_slot. As our copy's only affect data caches instruction caches may end up being stale. This is really hard to detect as context switches invalidate a lot of the instruction cache lines, but not all.
I fixed this for text patching recently with commit aca063c90245 ("openrisc: Fix jump_label smp syncing")
Quoted 43 lines
arch/openrisc/include/asm/kprobes.h new file +18
-0+#define kretprobe_blacklist_size 0 + +void arch_remove_kprobe (struct kprobe *p); +int kprobe_fault_handler (struct pt_regs *regs,int trapnr); +bool kprobe_breakpoint_handler (struct pt_regs *regs); +bool kprobe_singlestep_handler (struct pt_regs *regs); +#else /* !CONFIG_KPROBES */ +static inline bool kprobe_breakpoint_handler (struct pt_regs *regs) +{ +return false; +} + +static inline bool kprobe_singlestep_handler (struct pt_regs *regs) +{ +return false; +} +#endif /* CONFIG_KPROBES */ +#endif /* __ASM_OPENRISC_KPROBES_H */ arch/openrisc/kernel/Makefile +1
-0@@ -14,6 +14,7 @@ obj-$(CONFIG_SMP) += smp.o sync-timer.o obj-$(CONFIG_STACKTRACE) += stacktrace.o obj-$(CONFIG_MODULES) += module.o obj-$(CONFIG_OF) += prom.o +obj-$(CONFIG_KPROBES) += kprobes.o obj-y += patching.o clean:arch/openrisc/kernel/entry.S +1
-0@@ -15,6 +15,7 @@ #include <linux/linkage.h> #include <linux/pgtable.h> +#include <asm/asm.h> #include <asm/processor.h> #include <asm/unistd.h> #include <asm/thread_info.h>
arch/openrisc/kernel/entry.S ENTRY(_sys_call_handler) · line 644
Quoted 4 lines
arch/openrisc/kernel/entry.S +1
-0@@ -640,6 +641,7 @@ ENTRY(_sys_call_handler) /* r30 is the only register we clobber in the fast path */ /* r30 already saved */ /* l.sw PT_GPR30(r1),r30 */ +_ASM_NOKPROBE(_sys_call_handler)
How is this working for these not function symbols? _ASM_NOKPROBE registers a sybmol (in this case just a macro address) into the _kprobe_blacklist. I think withing kprobe.c it uses these _kprobe_blacklist entries to detect ranges that cannot be probed. However, in this case I think you are not able to get range information.
Quoted 123 lines
arch/openrisc/kernel/entry.S +14
-0_syscall_check_trace_enter: /* syscalls run with interrupts enabled */@@ -652,12 +654,14 @@ _syscall_check_trace_enter: l.sfne r30,r0 l.bf _syscall_trace_enter l.nop +_ASM_NOKPROBE(_syscall_check_trace_enter) _syscall_check: /* Ensure that the syscall number is reasonable */ l.sfgeui r11,__NR_syscalls l.bf _syscall_badsys l.nop +_ASM_NOKPROBE(_syscall_check) _syscall_call: l.movhi r29,hi(sys_call_table)@@ -668,12 +672,14 @@ _syscall_call: l.jalr r29 l.nop +_ASM_NOKPROBE(_syscall_call) _syscall_return: /* All syscalls return here... just pay attention to ret_from_fork * which does it in a round-about way. */ l.sw PT_GPR11(r1),r11 // save return value +_ASM_NOKPROBE(_syscall_return) #if 0 _syscall_debug:@@ -708,6 +714,7 @@ _syscall_check_trace_leave: l.sfne r30,r0 l.bf _syscall_trace_leave l.nop +_ASM_NOKPROBE(_syscall_check_trace_leave) /* This is where the exception-return code begins... interrupts need to be * disabled the rest of the way here because we can't afford to miss any@@ -744,6 +751,7 @@ _syscall_check_work: /* _work_pending needs to be called with interrupts disabled */ l.j _work_pending l.nop +_ASM_NOKPROBE(_syscall_check_work) _syscall_resume_userspace: // ENABLE_INTERRUPTS(r29)@@ -800,6 +808,7 @@ _syscall_resume_userspace: l.mtspr r0,r13,SPR_EPCR_BASE l.mtspr r0,r15,SPR_ESR_BASE l.rfe +_ASM_NOKPROBE(_syscall_resume_userspace) /* End of hot path! * Keep the below tracing and error handling out of the hot path...@@ -829,6 +838,7 @@ _syscall_trace_enter: l.j _syscall_check l.lwz r8,PT_GPR8(r1) +_ASM_NOKPROBE(_syscall_trace_enter) _syscall_trace_leave: l.jal do_syscall_trace_leave@@ -836,6 +846,7 @@ _syscall_trace_leave: l.j _syscall_check_work l.nop +_ASM_NOKPROBE(_syscall_trace_leave) _syscall_badsys: /* Here we effectively pretend to have executed an imaginary@@ -845,6 +856,7 @@ _syscall_badsys: */ l.j _syscall_return l.addi r11,r0,-ENOSYS +_ASM_NOKPROBE(_syscall_badsys) /******* END SYSCALL HANDLING *******/@@ -870,6 +882,7 @@ EXCEPTION_ENTRY(_trap_handler) l.j _ret_from_exception l.nop +_ASM_NOKPROBE(_trap_handler) /* ---[ 0xf00: Reserved exception ]-------------------------------------- */@@ -1004,6 +1017,8 @@ ENTRY(_ret_from_exception) l.nop l.j _resume_userspace l.nop +_ASM_NOKPROBE(_ret_from_exception) +_ASM_NOKPROBE(_ret_from_intr) ENTRY(ret_from_fork) l.jal schedule_tail@@ -1038,6 +1053,7 @@ ENTRY(ret_from_fork) l.j _syscall_return l.nop +_ASM_NOKPROBE(ret_from_fork) /* ========================================================[ switch ] === */arch/openrisc/kernel/kprobes.c new file +12
-0@@ -0,0 +1,426 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Kernel probes (KProbes) for OpenRISC +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* OpenRISC implementation: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ +
arch/openrisc/kernel/kprobes.c line 22
Quoted 10 lines
arch/openrisc/kernel/kprobes.c new file +10
-0+#include <linux/kprobes.h> +#include <asm/cpuinfo.h> +#include <asm/insn-def.h> +#include <asm/text-patching.h> + +DEFINE_PER_CPU(struct kprobe *, current_kprobe); +DEFINE_PER_CPU(struct kprobe_ctlblk, kprobe_ctlblk); + +#define KPROBE_BP_INSN __emit_trap(BRK_KPROBE_BP) +#define KPROBE_SSTEPBP_INSN __emit_trap(BRK_KPROBE_SSTEPBP)
Could you maybe add a comment about why these instructions are not supported?
Quoted 538 lines
arch/openrisc/kernel/kprobes.c new file +403
-0+static bool insn_not_supported (kprobe_opcode_t insn) +{ +switch (insn) { +case OPENRISC_INSN_CSYNC : +case OPENRISC_INSN_MSYNC : +case OPENRISC_INSN_PSYNC : +return true; + } + +if ((insn &OPENRISC_MASK_TRAP ) ==OPENRISC_INSN_TRAP ) +return true; + +if ((insn &OPENRISC_MASK_SYS ) ==OPENRISC_INSN_SYS ) +return true; + +if ((insn &OPENRISC_MASK_MACRC ) ==OPENRISC_INSN_MACRC ) +return true; + +unsigned char opcode =get_6_bit_opcode (insn); + +switch (opcode) { +case OPENRISC_OPCODE_RFE : +case OPENRISC_OPCODE_LWA : +case OPENRISC_OPCODE_MFSPR : +case OPENRISC_OPCODE_MTSPR : +case OPENRISC_OPCODE_SWA : +return true; + } + +return false; +} +NOKPROBE_SYMBOL (insn_not_supported) + +static bool is_branch_insn(kprobe_opcode_t insn) +{ +unsigned char opcode =get_6_bit_opcode (insn); + +switch (opcode) { +case OPENRISC_OPCODE_BF : +case OPENRISC_OPCODE_BNF : +case OPENRISC_OPCODE_J : +case OPENRISC_OPCODE_JAL : +case OPENRISC_OPCODE_JALR : +case OPENRISC_OPCODE_JR : +return true; + } + +return false; +} +NOKPROBE_SYMBOL (is_branch_insn) + +static bool is_pc_insn(kprobe_opcode_t insn) +{ +unsigned char opcode =get_6_bit_opcode (insn); + +if (opcode ==OPENRISC_OPCODE_ADRP ) +return true; + +return false; +} +NOKPROBE_SYMBOL (is_pc_insn) + +static bool insns_need_simulation(kprobe_opcode_t insn, bool *exec_delay_slot) +{ + *exec_delay_slot = false; + +if (is_branch_insn (insn)) { +if (static_branch_likely (&delay_slot)) + *exec_delay_slot = true; +return true; + } + +if (is_pc_insn (insn)) +return true; + +return false; +} +NOKPROBE_SYMBOL (insns_need_simulation) + +int arch_prepare_kprobe(struct kprobe *p) +{ +kprobe_opcode_t insn; +kprobe_opcode_t prev_insn, next_insn; +bool exec_delay_slot = false; + +/* Attempt to probe at unaligned address */ +if ((unsigned long )p->addr &0x3 ) +return -EILSEQ ; + +if (unlikely (copy_from_kernel_nofault (&insn, p->addr,OPENRISC_INSN_SIZE ))) +return -EFAULT ; + + p->opcode = insn; + +if (insn_not_supported (insn)) { +pr_notice ("Can't insert KProbe at blacklisted instruction.\n" ); +return -EINVAL ; + } + +if (copy_from_kernel_nofault (&prev_insn, p->addr -1 , +OPENRISC_INSN_SIZE ) ==0 &&is_branch_insn (prev_insn)) { +if (static_branch_likely (&delay_slot)) { +pr_notice ("Can't insert KProbe in delay slot.\n" ); +return -EINVAL ; + } + } + +if (copy_from_kernel_nofault (&next_insn, p->addr +1 ,OPENRISC_INSN_SIZE ) ==0 && +insns_need_simulation (next_insn, &exec_delay_slot) &&is_branch_insn (insn)) { +if (static_branch_likely (&delay_slot)) { +pr_notice ("Can't insert KProbe if following instruction is in a delay slot and depends on PC.\n" ); +return -EINVAL ; + } + } + +if (insns_need_simulation (insn, &exec_delay_slot) && !exec_delay_slot) { + p->ainsn.insn =NULL ; + }else { +/* +* Single step probed instruction or, in case of branch instructions, single +* step instruction in delay slot. +*/ + p->ainsn.insn =get_insn_slot (); +if (!p->ainsn.insn) +return -ENOMEM ; + +if (exec_delay_slot) +patch_insn_write (p->ainsn.insn, next_insn); +else +patch_insn_write (p->ainsn.insn, p->opcode); +patch_insn_write (&p->ainsn.insn[1 ],KPROBE_SSTEPBP_INSN ); + } + +return 0 ; +} +NOKPROBE_SYMBOL (arch_prepare_kprobe); + +void arch_arm_kprobe (struct kprobe *p) +{ +patch_insn_write (p->addr,KPROBE_BP_INSN ); +flush_insn_slot (p); +} +NOKPROBE_SYMBOL (arch_arm_kprobe); + +void arch_disarm_kprobe (struct kprobe *p) +{ +patch_insn_write (p->addr, p->opcode); +flush_insn_slot (p); +} +NOKPROBE_SYMBOL (arch_disarm_kprobe); + +void arch_remove_kprobe (struct kprobe *p) +{ +if (p->ainsn.insn) { +free_insn_slot (p->ainsn.insn,0 ); + p->ainsn.insn =NULL ; + } +} +NOKPROBE_SYMBOL (arch_remove_kprobe); + +static void set_current_kprobe (struct kprobe *p) +{ +__this_cpu_write (current_kprobe, p); +} +NOKPROBE_SYMBOL (set_current_kprobe); + +static void save_previous_kprobe (struct kprobe_ctlblk *kcb) +{ + kcb->prev_kprobe.kp =kprobe_running (); + kcb->prev_kprobe.status = kcb->kprobe_status; + kcb->prev_kprobe.restore_pc = kcb->restore_pc; +} +NOKPROBE_SYMBOL (save_previous_kprobe); + +static void restore_previous_kprobe (struct kprobe_ctlblk *kcb) +{ + kcb->kprobe_status = kcb->prev_kprobe.status; + kcb->restore_pc = kcb->prev_kprobe.restore_pc; +set_current_kprobe (kcb->prev_kprobe.kp); +} +NOKPROBE_SYMBOL (restore_previous_kprobe); + +/* +* kprobe_local_irq_(save|restore) disable/enable interrupts +* on exiting from the exception handler respectively. This is +* achieved by toggling the IEE and TEE bits in regs->sr with +* the changes taking effect after returning from the exception +* handler. +* +* Interrupts need to be disabled for the period during which an +* instruction is single-stepped. +*/ +static void __kprobes kprobe_local_irq_save (struct kprobe_ctlblk *kcb, +struct pt_regs *regs) +{ + kcb->irq_flags = regs->sr; + regs->sr = (regs->sr & ~(SPR_SR_IEE |SPR_SR_TEE )) |ARCH_IRQ_DISABLED ; +} + +static void __kprobes kprobe_local_irq_restore (struct kprobe_ctlblk *kcb, +struct pt_regs *regs) +{ + regs->sr = kcb->irq_flags; +} + +static void post_kprobe_handler (struct kprobe *cur,struct kprobe_ctlblk *kcb, +struct pt_regs *regs) +{ +instruction_pointer_set (regs, kcb->restore_pc); + +if (kcb->kprobe_status ==KPROBE_REENTER ) { +restore_previous_kprobe (kcb); +preempt_enable_no_resched (); +return ; + } + + kcb->kprobe_status =KPROBE_HIT_SSDONE ; + +if (cur->post_handler) + cur->post_handler (cur, regs,0 ); + +reset_current_kprobe (); +preempt_enable_no_resched (); +} +NOKPROBE_SYMBOL (post_kprobe_handler); + +static void setup_singlestep (struct kprobe *p,struct pt_regs *regs, +struct kprobe_ctlblk *kcb,int reenter) +{ +kprobe_opcode_t insn; + +if (reenter) { +save_previous_kprobe (kcb); +set_current_kprobe (p); + kcb->kprobe_status =KPROBE_REENTER ; + }else { + kcb->kprobe_status =KPROBE_HIT_SS ; + } + +/* Emulate instruction if required. */ + insn = p->opcode; +if (is_pc_insn (insn)) { +simulate_pc (regs, insn); + kcb->restore_pc = regs->pc; +/* No SSOL is required here, so call post-process immediately. */ +post_kprobe_handler (p, kcb, regs); +return ; + } + +if (is_branch_insn (insn)) { +simulate_branch (regs, insn); +/* Save target addr before updating PC to SSOL slot */ + kcb->restore_pc = regs->pc; + }else + kcb->restore_pc = regs->pc +OPENRISC_INSN_SIZE ; + +if (p->ainsn.insn) { +/* Disable IRQs before single stepping */ +kprobe_local_irq_save (kcb, regs); +instruction_pointer_set (regs, (unsigned long )p->ainsn.insn); + }else { +/* +* The instruction is a branch but delay slots are disabled. +* Simply call the post-handler. +*/ +post_kprobe_handler (p, kcb, regs); + } +} +NOKPROBE_SYMBOL (setup_singlestep); + +static bool reenter_kprobe (struct kprobe *p,struct pt_regs *regs, +struct kprobe_ctlblk *kcb) +{ +switch (kcb->kprobe_status) { +case KPROBE_HIT_SS : +case KPROBE_HIT_SSDONE : +case KPROBE_HIT_ACTIVE : +kprobes_inc_nmissed_count (p); +setup_singlestep (p, regs, kcb,1 ); +break ; +case KPROBE_REENTER : +pr_warn ("Unrecoverable KProbe detected.\n" ); +dump_kprobe (p); +WARN_ON_ONCE (1 ); +return false; +default : +WARN_ON (1 ); +return false; + } + +return true; +} +NOKPROBE_SYMBOL (reenter_kprobe); + +bool kprobe_breakpoint_handler (struct pt_regs *regs) +{ +struct kprobe *p, *curr_kprobe; +struct kprobe_ctlblk *kcb; +kprobe_opcode_t *addr = (kprobe_opcode_t *)regs->pc; +kprobe_opcode_t insn; + +/* +* We don't want to be preempted for the entire +* duration of kprobe processing. +*/ +preempt_disable (); + + kcb =get_kprobe_ctlblk (); + curr_kprobe =kprobe_running (); + p =get_kprobe (addr); +if (p) { +if (curr_kprobe) { +if (reenter_kprobe (p, regs, kcb)) +return true; + }else { +/* Probe hit */ +set_current_kprobe (p); + kcb->kprobe_status =KPROBE_HIT_ACTIVE ; +/* +* If there's no pre-handler or it returns 0, continue +* processing the KProbe as usual. A non-zero return +* value implies the saved registers have been modified +* and the execution path might deviate from what's +* expected. Reset the KProbe and return. +*/ +if (!p->pre_handler || !p->pre_handler (p, regs)) { +setup_singlestep (p, regs, kcb,0 ); + }else { +reset_current_kprobe (); +preempt_enable_no_resched (); + } +return true; + } + } + +/* +* The breakpoint instruction was removed right after we hit it +* possibly by another cpu. If the original instruction was also +* a trap instruction then return to the trap handler for further +* processing, else no further processing is required. +*/ +if (get_kernel_nofault (insn, addr) <0 + || (insn &OPENRISC_MASK_TRAP ) !=OPENRISC_INSN_TRAP ) { +preempt_enable_no_resched (); +return true; + } + +preempt_enable_no_resched (); +return false; +} +NOKPROBE_SYMBOL (kprobe_breakpoint_handler); + +bool kprobe_singlestep_handler (struct pt_regs *regs) +{ +struct kprobe *cur =kprobe_running (); +struct kprobe_ctlblk *kcb =get_kprobe_ctlblk (); +unsigned long addr =instruction_pointer (regs); + +if (cur && (kcb->kprobe_status & (KPROBE_HIT_SS |KPROBE_REENTER )) && + ((unsigned long )&cur->ainsn.insn[1 ] == addr)) { +/* Single stepping has been completed. Enable IRQs. */ +kprobe_local_irq_restore (kcb, regs); +post_kprobe_handler (cur, kcb, regs); +return true; + } + +return false; +} +NOKPROBE_SYMBOL (kprobe_singlestep_handler); + +int kprobe_fault_handler (struct pt_regs *regs,int trapnr) +{ +struct kprobe *cur =kprobe_running (); +struct kprobe_ctlblk *kcb =get_kprobe_ctlblk (); + +switch (kcb->kprobe_status) { +case KPROBE_HIT_SS : +case KPROBE_REENTER : +/* +* The instruction being single-stepped caused a page fault. +* Reset the current KProbe and set PC to the probe's address. +* Then allow the page fault handler to continue as usual. +*/ +instruction_pointer_set (regs, (unsigned long )cur->addr); + +if (kcb->kprobe_status ==KPROBE_REENTER ) +restore_previous_kprobe (kcb); +else +reset_current_kprobe (); + +kprobe_local_irq_restore (kcb, regs); +preempt_enable_no_resched (); +break ; + } + +return 0 ; +} +NOKPROBE_SYMBOL (kprobe_fault_handler); + +int __init arch_init_kprobes (void ) +{ +return 0 ; +}arch/openrisc/kernel/traps.c +29
-0@@ -30,10 +30,12 @@#include <linux/kallsyms.h> #include <linux/uaccess.h> +#include <asm/break.h> #include <asm/bug.h> #include <asm/fpu.h> #include <asm/insn-def.h> #include <asm/io.h> +#include <asm/kprobes.h> #include <asm/processor.h> #include <asm/unwinder.h> #include <asm/sections.h> @@ -216,10 +218,37 @@ asmlinkage void do_trap(struct pt_regs *regs, unsigned long address)if (user_mode (regs)) {force_sig_fault (SIGTRAP ,TRAP_BRKPT , (void __user *)regs->pc); }else { +unsigned long trap, bcode; + +if (get_kernel_nofault (trap, (unsigned long *)regs->pc) <0 ) +return ; + +/* +* Trap instruction was probably removed and no further processing +* is required. +*/ +if ((trap &OPENRISC_MASK_TRAP ) !=OPENRISC_INSN_TRAP ) +return ; + + bcode = (trap &OPENRISC_MASK_BCODE ); +switch (bcode) { +case BRK_KPROBE_BP : +if (kprobe_breakpoint_handler (regs)) +return ; +break ; +case BRK_KPROBE_SSTEPBP : +if (kprobe_singlestep_handler (regs)) +return ; +break ; +default : +break ; + } +pr_emerg ("KERNEL: Illegal trap exception 0x%.8lx\n" , regs->pc);die ("Die:" , regs,SIGILL ); } } +NOKPROBE_SYMBOL (do_trap) asmlinkage void do_unaligned_access(struct pt_regs *regs, unsigned long address) {arch/openrisc/lib/memcpy.c +2
-0@@ -16,6 +16,7 @@#include <linux/export.h> +#include <linux/kprobes.h> #include <linux/string.h> #ifdef CONFIG_OR1K_1200 @@ -122,4 +123,5 @@ void *memcpy(void *dest, __const void *src, __kernel_size_t n) }#endif +NOKPROBE_SYMBOL (memcpy);EXPORT_SYMBOL (memcpy);arch/openrisc/lib/memset.S +4
-0@@ -9,6 +9,8 @@ * Copyright (C) 2015 Olof Kindgren <[email protected]> */ +#include <asm/asm.h> + .global memset .type memset, @function memset:@@ -92,3 +94,5 @@ memset: 4: l.jr r9 l.ori r11, r3, 0 + +_ASM_NOKPROBE(memset)arch/openrisc/mm/fault.c +5
-0@@ -14,6 +14,7 @@#include <linux/mm.h> #include <linux/interrupt.h> #include <linux/extable.h> +#include <linux/kprobes.h> #include <linux/sched/signal.h> #include <linux/perf_event.h> @@ -55,6 +56,9 @@ asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long address, tsk = current; +if (kprobe_page_fault (regs, vector)) +return ; +/* * We fault-in kernel-space virtual memory on-demand. The * 'reference' page table is init_mm.pgd. @@ -351,3 +355,4 @@ asmlinkage void do_page_fault(struct pt_regs *regs, unsigned long address,return ; } } +NOKPROBE_SYMBOL (do_page_fault)samples/kprobes/kprobe_example.c +4
-0@@ -59,6 +59,10 @@ static int __kprobes handler_pre(struct kprobe *p, struct pt_regs *regs)pr_info ("<%s> p->addr = 0x%p, era = 0x%lx, estat = 0x%lx\n" , p->symbol_name, p->addr, regs->csr_era, regs->csr_estat);#endif +#ifdef CONFIG_OPENRISC +pr_info ("<%s> p->addr = 0x%p, pc = 0x%lx, status = 0x%lx\n" , + p->symbol_name, p->addr, regs->pc, regs->sr); +#endif /* A dump_stack() here will give a stack backtrace */ return 0 ;
samples/kprobes/kprobe_example.c static void __kprobes handler_post(struct kprobe *p, struct pt_regs *regs, · line 113
Quoted 10 lines
samples/kprobes/kprobe_example.c +4
-0@@ -100,6 +104,10 @@ static void __kprobes handler_post(struct kprobe *p, struct pt_regs *regs,pr_info ("<%s> p->addr = 0x%p, estat = 0x%lx\n" , p->symbol_name, p->addr, regs->csr_estat);#endif +#ifdef CONFIG_OPENRISC +pr_info ("<%s> p->addr = 0x%p, status = 0x%lx\n" , + p->symbol_name, p->addr, regs->sr); +#endif }static int __init kprobe_init (void )
I think this is looking pretty good.
Thank You,
-Stafford
Re: [PATCH v3 2/4] openrisc: Add KProbes
Quoted 76 lines · Stafford Horne
Quoted 75 lines · Sahil Siddiq
Add KProbes support for OpenRISC. This work is primarily based on similar work done for LoongArch, MIPS and RISC-V.
KProbes make it possible to trap at almost any address in the kernel to collect performance/debugging info.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/kprobes.c:
- (kprobe_local_irq_save): New function
- (kprobe_local_irq_restore): Likewise
- (arch_prepare_kprobe): Usecopy_from_kernel_nofault()
- (post_kprobe_handler): Enable preemption before returning early for reentered KProbe
- (setup_singlestep): Disable IRQs by toggling bits in SR register
- (kprobe_breakpoint_handler): Use result fromget_kernel_nofault()
- (kprobe_fault_handler):
Enable preemption after handling reentered KProbe
Restore IRQs by toggling bits in SR registerChanges v1 -> v2:
-arch/openrisc/include/asm/kprobes.h:
- (structprev_kprobe): Addrestore_pc
- (structkprobe_ctlblk): Moverestore_pcfrom global "structarch_specific_insn"
-arch/openrisc/kernel/kprobes.c:
- Use macros instead of magic values
- Use "get_kernel_nofault" instead of directly dereferencing address
- (insns_need_simulation): Use "daley slot" static key
- (arch_prepare_kprobe): Prevent KProbe insertion if instruction in delay slot also requires simulation
- (save_previous_kprobe): Use "restore_pc"
- (restore_previous_kprobe): Likewise
- (post_kprobe_handler): Don't re-enable preemption if KProbe is nested
- (setup_singlestep): Use "restore_pc"
- (reenter_kprobe): Return false in case of unrecoverable KProbe
- (kprobe_singlestep_handler): Enable interrupt inpt_regs->sr
- (kprobe_fault_handler): Likewisearch/openrisc/Kconfig | 1 + arch/openrisc/configs/or1ksim_defconfig | 2 + arch/openrisc/configs/virt_defconfig | 2 + arch/openrisc/include/asm/asm.h | 22 ++ arch/openrisc/include/asm/break.h | 19 ++ arch/openrisc/include/asm/insn-def.h | 6 + arch/openrisc/include/asm/kprobes.h | 77 +++++ arch/openrisc/kernel/Makefile | 1 + arch/openrisc/kernel/entry.S | 16 + arch/openrisc/kernel/kprobes.c | 426 ++++++++++++++++++++++++ arch/openrisc/kernel/traps.c | 29 ++ arch/openrisc/lib/memcpy.c | 2 + arch/openrisc/lib/memset.S | 4 + arch/openrisc/mm/fault.c | 5 + samples/kprobes/kprobe_example.c | 8 + 15 files changed, 620 insertions(+)create mode 100644
arch/openrisc/include/asm/asm.hcreate mode 100644arch/openrisc/include/asm/break.hcreate mode 100644arch/openrisc/include/asm/kprobes.hcreate mode 100644arch/openrisc/kernel/kprobes.carch/openrisc/Kconfig +1
-0@@ -27,6 +27,7 @@ config OPENRISC select HAVE_ARCH_JUMP_LABEL select HAVE_ARCH_JUMP_LABEL_RELATIVE select HAVE_PCI + select HAVE_KPROBES select HAVE_UID16 select HAVE_PAGE_SIZE_8KB select HAVE_REGS_AND_STACK_ACCESS_APIarch/openrisc/configs/or1ksim_defconfig +0
-0@@ -10,7 +10,9 @@ CONFIG_EXPERT=y
Quoted 9 lines
arch/openrisc/configs/or1ksim_defconfig CONFIG_EXPERT=y · line 13
Quoted 4 lines
arch/openrisc/configs/or1ksim_defconfig +1
-0# CONFIG_KALLSYMS is not set CONFIG_BUILTIN_DTB_NAME="or1ksim" CONFIG_HZ_100=y +CONFIG_OPENRISC=yI am not sure this is needed, did you generate this file with make savedefconfig? I thought
CONFIG_OPENRISCwould be set for every openrisc build by default so not needed in the*_defconfig.
Ah, yes. I hadn't noticed that CONFIG_OPENRISC is set automatically. This does not need to be set manually. I'll remove it from both defconfig files.
Quoted 161 lines
Quoted 145 lines
arch/openrisc/configs/or1ksim_defconfig +1
-0CONFIG_JUMP_LABEL=y +CONFIG_KPROBES=y CONFIG_MODULES=y # CONFIG_BLOCK is not set CONFIG_SLUB_TINY=yarch/openrisc/configs/virt_defconfig +2
-0@@ -11,8 +11,10 @@ CONFIG_OPENRISC_HAVE_INST_SEXT=y CONFIG_NR_CPUS=8 CONFIG_SMP=y CONFIG_HZ_100=y +CONFIG_OPENRISC=y # CONFIG_OPENRISC_NO_SPR_SR_DSX is not set CONFIG_JUMP_LABEL=y +CONFIG_KPROBES=y # CONFIG_COMPAT_BRK is not set CONFIG_NET=y CONFIG_PACKET=yarch/openrisc/include/asm/asm.h new file +22
-0@@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* Macros for OpenRISC asm +* +* Linux architectural port borrowing nearly verbatim from +* LoongArch and Arm. All original copyrights apply as per +* the original source declaration. +*/ + +#ifndef __ASM_ASM_H +#define __ASM_ASM_H + +#ifdef CONFIG_KPROBES +#define _ASM_NOKPROBE (symbol) \ + .pushsection "_kprobe_blacklist", "aw"; \ + .long symbol; \ + .popsection +#else +#define _ASM_NOKPROBE (symbol) +#endif + +#endif /* __ASM_ASM_H */ arch/openrisc/include/asm/break.h new file +19
-0@@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* OpenRISC trap codes used internally by the kernel +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* Modifications for the OpenRISC architecture: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#ifndef __ASM_BREAK_H +#define __ASM_BREAK_H + +#define BRK_KPROBE_BP 512/* Kprobe break */ +#define BRK_KPROBE_SSTEPBP 1024/* Kprobe single-step software implementation */ + +#endif /* __ASM_BREAK_H */ arch/openrisc/include/asm/insn-def.h +6
-0@@ -54,6 +54,12 @@ struct pt_regs;#define OPENRISC_INSN_SIZE 4 +/* Helpers for working with l.trap */ +static inline unsigned long __emit_trap (unsigned long code) +{ +return (code &OPENRISC_MASK_BCODE ) |OPENRISC_INSN_TRAP ; +} + static __always_inline unsigned char get_6_bit_opcode(unsigned long insn) {return (insn >>OPENRISC_OPCODE_SHIFT ) &OPENRISC_OPCODE_MASK ;arch/openrisc/include/asm/kprobes.h new file +49
-0@@ -0,0 +1,77 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* OpenRISC Linux +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* OpenRISC implementation: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#ifndef __ASM_OPENRISC_KPROBES_H +#define __ASM_OPENRISC_KPROBES_H + +#include <asm-generic/kprobes.h> + +#ifdef CONFIG_KPROBES +#include <asm/break.h> +#include <asm/cacheflush.h> + +#define __ARCH_WANT_KPROBES_INSN_SLOT + +struct pt_regs ; +struct kprobe ; + +typedef u32 kprobe_opcode_t ; + +/* +* MAX_INSN_SIZE is used as the number of slots in an executable +* page for single-stepping out of line (SSOL). We need two slots +* since we single-step using software breakpoints. The probed +* instruction is placed in the first slot with a breakpoint +* instruction in the second slot. +*/ +#define MAX_INSN_SIZE 2 + +/* Architecture specific copy of original instruction */ +struct arch_specific_insn { +/* copy of original instruction */ +kprobe_opcode_t *insn; +}; + +struct prev_kprobe { +struct kprobe *kp; +unsigned int status; +unsigned long restore_pc; +}; +arch/openrisc/include/asm/kprobes.h line 59
Quoted 10 lines
arch/openrisc/include/asm/kprobes.h new file +10
-0+/* per-cpu kprobe control block */ +struct kprobe_ctlblk { +unsigned int kprobe_status; +unsigned long irq_flags; +/* address of next instruction in case of SSOL */ +unsigned long restore_pc; +struct prev_kprobe prev_kprobe; +}; + +#define flush_insn_slot (p) do { } while (0)On openrisc I think we need to implement
flush_insn_slot. As our copy's only affect data caches instruction caches may end up being stale. This is really hard to detect as context switches invalidate a lot of the instruction cache lines, but not all.
Quoted 2 lines
I fixed this for text patching recently with commit
aca063c90245("openrisc: Fixjump_labelsmp syncing")
Understood. In the same commit [1], you have also mentioned that invalidating all the cache lines is less expensive than keeping track of which line needs to be invalidated.
In case of KProbes, where a KProbe at a specific instruction is armed or disarmed:
void arch_arm_kprobe(struct kprobe *p) {
patch_insn_write(p->addr, KPROBE_BP_INSN);
flush_insn_slot(p);
}void arch_disarm_kprobe(struct kprobe *p) {
patch_insn_write(p->addr, p->opcode);
flush_insn_slot(p);
}Should only that page be invalidated? Or is it ok to invalidate all lines?
Quoted 38 lines
Quoted 38 lines
arch/openrisc/include/asm/kprobes.h new file +18
-0+#define kretprobe_blacklist_size 0 + +void arch_remove_kprobe (struct kprobe *p); +int kprobe_fault_handler (struct pt_regs *regs,int trapnr); +bool kprobe_breakpoint_handler (struct pt_regs *regs); +bool kprobe_singlestep_handler (struct pt_regs *regs); +#else /* !CONFIG_KPROBES */ +static inline bool kprobe_breakpoint_handler (struct pt_regs *regs) +{ +return false; +} + +static inline bool kprobe_singlestep_handler (struct pt_regs *regs) +{ +return false; +} +#endif /* CONFIG_KPROBES */ +#endif /* __ASM_OPENRISC_KPROBES_H */ arch/openrisc/kernel/Makefile +1
-0@@ -14,6 +14,7 @@ obj-$(CONFIG_SMP) += smp.o sync-timer.o obj-$(CONFIG_STACKTRACE) += stacktrace.o obj-$(CONFIG_MODULES) += module.o obj-$(CONFIG_OF) += prom.o +obj-$(CONFIG_KPROBES) += kprobes.o obj-y += patching.o clean:arch/openrisc/kernel/entry.S +0
-0@@ -15,6 +15,7 @@ #include <linux/linkage.h> #include <linux/pgtable.h>
Quoted 15 lines
arch/openrisc/kernel/entry.S ENTRY(_sys_call_handler) · line 644
Quoted 9 lines
arch/openrisc/kernel/entry.S +2
-0+#include <asm/asm.h> #include <asm/processor.h> #include <asm/unistd.h> #include <asm/thread_info.h>@@ -640,6 +641,7 @@ ENTRY(_sys_call_handler) /* r30 is the only register we clobber in the fast path */ /* r30 already saved */ /* l.sw PT_GPR30(r1),r30 */ +_ASM_NOKPROBE(_sys_call_handler)How is this working for these not function symbols?
_ASM_NOKPROBEregisters a sybmol (in this case just a macro address) into the_kprobe_blacklist. I think withingkprobe.cit uses these_kprobe_blacklistentries to detect ranges that cannot be probed. However, in this case I think you are not able to get range information.
_ASM_NOKPROBE and NOKPROBE_SYMBOL (for functions in C) expand to the same thing functionally. The kernel treats these labels as symbols as well. I verified this using "nm".
When a KProbe is registered using an address instead of the symbol_name, "register_kprobe()" [2] at kernel/kprobes.c indirectly calls "within_kprobe_blacklist()" [3] which performs "kprobe_lookup_name()". It then checks if that name is in the blacklist. This blacklist includes the names of the asm functions as well.
I wrote this test module [4] to verify that an address in memcpy's range, for example, is also blacklisted.
Quoted 127 lines
Quoted 127 lines
arch/openrisc/kernel/entry.S +14
-0_syscall_check_trace_enter: /* syscalls run with interrupts enabled */@@ -652,12 +654,14 @@ _syscall_check_trace_enter: l.sfne r30,r0 l.bf _syscall_trace_enter l.nop +_ASM_NOKPROBE(_syscall_check_trace_enter) _syscall_check: /* Ensure that the syscall number is reasonable */ l.sfgeui r11,__NR_syscalls l.bf _syscall_badsys l.nop +_ASM_NOKPROBE(_syscall_check) _syscall_call: l.movhi r29,hi(sys_call_table)@@ -668,12 +672,14 @@ _syscall_call: l.jalr r29 l.nop +_ASM_NOKPROBE(_syscall_call) _syscall_return: /* All syscalls return here... just pay attention to ret_from_fork * which does it in a round-about way. */ l.sw PT_GPR11(r1),r11 // save return value +_ASM_NOKPROBE(_syscall_return) #if 0 _syscall_debug:@@ -708,6 +714,7 @@ _syscall_check_trace_leave: l.sfne r30,r0 l.bf _syscall_trace_leave l.nop +_ASM_NOKPROBE(_syscall_check_trace_leave) /* This is where the exception-return code begins... interrupts need to be * disabled the rest of the way here because we can't afford to miss any@@ -744,6 +751,7 @@ _syscall_check_work: /* _work_pending needs to be called with interrupts disabled */ l.j _work_pending l.nop +_ASM_NOKPROBE(_syscall_check_work) _syscall_resume_userspace: // ENABLE_INTERRUPTS(r29)@@ -800,6 +808,7 @@ _syscall_resume_userspace: l.mtspr r0,r13,SPR_EPCR_BASE l.mtspr r0,r15,SPR_ESR_BASE l.rfe +_ASM_NOKPROBE(_syscall_resume_userspace) /* End of hot path! * Keep the below tracing and error handling out of the hot path...@@ -829,6 +838,7 @@ _syscall_trace_enter: l.j _syscall_check l.lwz r8,PT_GPR8(r1) +_ASM_NOKPROBE(_syscall_trace_enter) _syscall_trace_leave: l.jal do_syscall_trace_leave@@ -836,6 +846,7 @@ _syscall_trace_leave: l.j _syscall_check_work l.nop +_ASM_NOKPROBE(_syscall_trace_leave) _syscall_badsys: /* Here we effectively pretend to have executed an imaginary@@ -845,6 +856,7 @@ _syscall_badsys: */ l.j _syscall_return l.addi r11,r0,-ENOSYS +_ASM_NOKPROBE(_syscall_badsys) /******* END SYSCALL HANDLING *******/@@ -870,6 +882,7 @@ EXCEPTION_ENTRY(_trap_handler) l.j _ret_from_exception l.nop +_ASM_NOKPROBE(_trap_handler) /* ---[ 0xf00: Reserved exception ]-------------------------------------- */@@ -1004,6 +1017,8 @@ ENTRY(_ret_from_exception) l.nop l.j _resume_userspace l.nop +_ASM_NOKPROBE(_ret_from_exception) +_ASM_NOKPROBE(_ret_from_intr) ENTRY(ret_from_fork) l.jal schedule_tail@@ -1038,6 +1053,7 @@ ENTRY(ret_from_fork) l.j _syscall_return l.nop +_ASM_NOKPROBE(ret_from_fork) /* ========================================================[ switch ] === */arch/openrisc/kernel/kprobes.c new file +16
-0@@ -0,0 +1,426 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Kernel probes (KProbes) for OpenRISC +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* OpenRISC implementation: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#include <linux/kprobes.h> +#include <asm/cpuinfo.h> +#include <asm/insn-def.h> +#include <asm/text-patching.h>
Quoted 8 lines
arch/openrisc/kernel/kprobes.c line 22
Quoted 6 lines
arch/openrisc/kernel/kprobes.c new file +6
-0+ +DEFINE_PER_CPU(struct kprobe *, current_kprobe); +DEFINE_PER_CPU(struct kprobe_ctlblk, kprobe_ctlblk); + +#define KPROBE_BP_INSN __emit_trap(BRK_KPROBE_BP) +#define KPROBE_SSTEPBP_INSN __emit_trap(BRK_KPROBE_SSTEPBP)Could you maybe add a comment about why these instructions are not supported?
Sure, I'll do that.
Quoted 9 lines
Quoted 3 lines
[...]
static int
__initkprobe_init(void)I think this is looking pretty good.
Thank You,
-Stafford
Thanks,
Sahil
[1] https://github.com/torvalds/linux/commit/1be031de802ba486a7605b52eda825f128b026e2
[2] https://github.com/torvalds/linux/blob/master/kernel/kprobes.c#L2002
[3] https://github.com/torvalds/linux/blob/master/kernel/kprobes.c#L1730
[4] https://github.com/valdaarhun/or-dev/blob/main/home/kprobes_blacklist.c
Stafford Horne
maintainerRe: [PATCH v3 2/4] openrisc: Add KProbes
Quoted 4 lines · Sahil
Quoted 3 lines · Stafford Horne
Quoted 2 lines · Sahil Siddiq
Add KProbes support for OpenRISC. This work is primarily based on similar work done for LoongArch, MIPS and RISC-V.
[snip]
Quoted 1 line
Quoted 1 line
Quoted 1 line
+++
b/arch/openrisc/include/asm/kprobes.h
[snip]
Quoted 22 lines
Quoted 9 lines
Quoted 1 line
+#define
flush_insn_slot(p)do { } while (0)On openrisc I think we need to implement
flush_insn_slot. As our copy's only affect data caches instruction caches may end up being stale. This is really hard to detect as context switches invalidate a lot of the instruction cache lines, but not all.I fixed this for text patching recently with commit
aca063c90245("openrisc: Fixjump_labelsmp syncing")Understood. In the same commit [1], you have also mentioned that invalidating all the cache lines is less expensive than keeping track of which line needs to be invalidated.
In case of KProbes, where a KProbe at a specific instruction is armed or disarmed:
void arch_arm_kprobe(struct kprobe *p) { patch_insn_write(p->addr, KPROBE_BP_INSN); flush_insn_slot(p); }
Quoted 7 lines
void arch_disarm_kprobe(struct kprobe *p) { patch_insn_write(p->addr, p->opcode); flush_insn_slot(p); }Should only that page be invalidated? Or is it ok to invalidate all lines?
I think you only need to flush the part of the kprobe data structure that has code that is updated, for example p->addr. Since you have all of that information tracked for you in the kprobe structures it should be pretty simple. That was not the case for text patching.
Note, I had a look this is needed for init_aggr_kprobe() which copies code from one prope to another.
Note 2, for arch_arm_kprobe/arch_disarm_kprobe we use patch_insn_write which internally does a icache invalidation alredy. So I think the call to flush_insn_slot() in arch_disarm_kprobe()/arch_arm_kprobe() is not needed.
Quoted 56 lines
Quoted 43 lines
Quoted 43 lines
arch/openrisc/include/asm/kprobes.h new file +18
-0+#define kretprobe_blacklist_size 0 + +void arch_remove_kprobe (struct kprobe *p); +int kprobe_fault_handler (struct pt_regs *regs,int trapnr); +bool kprobe_breakpoint_handler (struct pt_regs *regs); +bool kprobe_singlestep_handler (struct pt_regs *regs); +#else /* !CONFIG_KPROBES */ +static inline bool kprobe_breakpoint_handler (struct pt_regs *regs) +{ +return false; +} + +static inline bool kprobe_singlestep_handler (struct pt_regs *regs) +{ +return false; +} +#endif /* CONFIG_KPROBES */ +#endif /* __ASM_OPENRISC_KPROBES_H */ arch/openrisc/kernel/Makefile +1
-0@@ -14,6 +14,7 @@ obj-$(CONFIG_SMP) += smp.o sync-timer.o obj-$(CONFIG_STACKTRACE) += stacktrace.o obj-$(CONFIG_MODULES) += module.o obj-$(CONFIG_OF) += prom.o +obj-$(CONFIG_KPROBES) += kprobes.o obj-y += patching.o clean:arch/openrisc/kernel/entry.S +1
-0@@ -15,6 +15,7 @@ #include <linux/linkage.h> #include <linux/pgtable.h> +#include <asm/asm.h> #include <asm/processor.h> #include <asm/unistd.h> #include <asm/thread_info.h>@@ -640,6 +641,7 @@ ENTRY(_sys_call_handler) /* r30 is the only register we clobber in the fast path */ /* r30 already saved */Quoted 8 lines
arch/openrisc/kernel/entry.S ENTRY(_sys_call_handler) · line 644
Quoted 2 lines
arch/openrisc/kernel/entry.S +1
-0/* l.sw PT_GPR30(r1),r30 */ +_ASM_NOKPROBE(_sys_call_handler)How is this working for these not function symbols?
_ASM_NOKPROBEregisters a sybmol (in this case just a macro address) into the_kprobe_blacklist. I think withingkprobe.cit uses these_kprobe_blacklistentries to detect ranges that cannot be probed. However, in this case I think you are not able to get range information.
_ASM_NOKPROBEandNOKPROBE_SYMBOL(for functions in C) expand to the same thing functionally. The kernel treats these labels as symbols as well. I verified this using "nm".
Quoted 8 lines
When a KProbe is registered using an address instead of the
symbol_name, "register_kprobe()" [2] atkernel/kprobes.cindirectly calls "within_kprobe_blacklist()" [3] which performs "kprobe_lookup_name()". It then checks if that name is in the blacklist. This blacklist includes the names of the asm functions as well.I wrote this test module [4] to verify that an address in memcpy's range, for example, is also blacklisted.
Right, I think for C functions this is fine. But for OpenRISC assembly I think we do not provide enough info for this to work correctly.
For example above _sys_call_handler, is just a label.
In other architectures they do something like this:
SYM_CODE_START(handle_syscall)
UNWIND_HINT_UNDEFINED
csrrd t0, PERCPU_BASE_KS
...
bl do_syscall
STACKLEAK_ERASE
RESTORE_ALL_AND_RET
SYM_CODE_END(handle_syscall)
_ASM_NOKPROBE(handle_syscall)
The SYM_CODE_START/SYM_CODE_END macros or similar are not used in OpenRISC, I think we need something to define the beginning and end of our asm macros in order for this to work.
-Stafford
[snip]
Quoted 8 lines
Thanks,
Sahil[1] https://github.com/torvalds/linux/commit/1be031de802ba486a7605b52eda825f128b026e2
[2] https://github.com/torvalds/linux/blob/master/kernel/kprobes.c#L2002
[3] https://github.com/torvalds/linux/blob/master/kernel/kprobes.c#L1730
[4] https://github.com/valdaarhun/or-dev/blob/main/home/kprobes_blacklist.c
Re: [PATCH v3 2/4] openrisc: Add KProbes
Quoted 47 lines · Stafford Horne
Quoted 4 lines · Sahil
Quoted 3 lines · Stafford Horne
Quoted 2 lines · Sahil Siddiq
Add KProbes support for OpenRISC. This work is primarily based on similar work done for LoongArch, MIPS and RISC-V.
[snip]
Quoted 1 line
Quoted 1 line
Quoted 1 line
+++
b/arch/openrisc/include/asm/kprobes.h[snip]
Quoted 22 lines
Quoted 9 lines
Quoted 1 line
+#define
flush_insn_slot(p)do { } while (0)On openrisc I think we need to implement
flush_insn_slot. As our copy's only affect data caches instruction caches may end up being stale. This is really hard to detect as context switches invalidate a lot of the instruction cache lines, but not all.I fixed this for text patching recently with commit
aca063c90245("openrisc: Fixjump_labelsmp syncing")Understood. In the same commit [1], you have also mentioned that invalidating all the cache lines is less expensive than keeping track of which line needs to be invalidated.
In case of KProbes, where a KProbe at a specific instruction is armed or disarmed:
void arch_arm_kprobe(struct kprobe *p) { patch_insn_write(p->addr, KPROBE_BP_INSN); flush_insn_slot(p); }Quoted 7 lines
void arch_disarm_kprobe(struct kprobe *p) { patch_insn_write(p->addr, p->opcode); flush_insn_slot(p); }Should only that page be invalidated? Or is it ok to invalidate all lines?
I think you only need to flush the part of the kprobe data structure that has code that is updated, for example
p->addr. Since you have all of that information tracked for you in the kprobe structures it should be pretty simple. That was not the case for text patching.
Quoted 7 lines
Note, I had a look this is needed for
init_aggr_kprobe()which copies code from one prope to another.Note 2, for arch_arm_kprobe/arch_disarm_kprobe we use
patch_insn_writewhich internally does a icache invalidation alredy. So I think the call toflush_insn_slot()in arch_disarm_kprobe()/arch_arm_kprobe() is not needed.
Got it, thank you for the clarification.
Quoted 78 lines
Quoted 56 lines
Quoted 43 lines
Quoted 43 lines
arch/openrisc/include/asm/kprobes.h new file +18
-0+#define kretprobe_blacklist_size 0 + +void arch_remove_kprobe (struct kprobe *p); +int kprobe_fault_handler (struct pt_regs *regs,int trapnr); +bool kprobe_breakpoint_handler (struct pt_regs *regs); +bool kprobe_singlestep_handler (struct pt_regs *regs); +#else /* !CONFIG_KPROBES */ +static inline bool kprobe_breakpoint_handler (struct pt_regs *regs) +{ +return false; +} + +static inline bool kprobe_singlestep_handler (struct pt_regs *regs) +{ +return false; +} +#endif /* CONFIG_KPROBES */ +#endif /* __ASM_OPENRISC_KPROBES_H */ arch/openrisc/kernel/Makefile +1
-0@@ -14,6 +14,7 @@ obj-$(CONFIG_SMP) += smp.o sync-timer.o obj-$(CONFIG_STACKTRACE) += stacktrace.o obj-$(CONFIG_MODULES) += module.o obj-$(CONFIG_OF) += prom.o +obj-$(CONFIG_KPROBES) += kprobes.o obj-y += patching.o clean:arch/openrisc/kernel/entry.S +1
-0@@ -15,6 +15,7 @@ #include <linux/linkage.h> #include <linux/pgtable.h> +#include <asm/asm.h> #include <asm/processor.h> #include <asm/unistd.h> #include <asm/thread_info.h>@@ -640,6 +641,7 @@ ENTRY(_sys_call_handler) /* r30 is the only register we clobber in the fast path */ /* r30 already saved */Quoted 8 lines
arch/openrisc/kernel/entry.S ENTRY(_sys_call_handler) · line 644
Quoted 2 lines
arch/openrisc/kernel/entry.S +1
-0/* l.sw PT_GPR30(r1),r30 */ +_ASM_NOKPROBE(_sys_call_handler)How is this working for these not function symbols?
_ASM_NOKPROBEregisters a sybmol (in this case just a macro address) into the_kprobe_blacklist. I think withingkprobe.cit uses these_kprobe_blacklistentries to detect ranges that cannot be probed. However, in this case I think you are not able to get range information.
_ASM_NOKPROBEandNOKPROBE_SYMBOL(for functions in C) expand to the same thing functionally. The kernel treats these labels as symbols as well. I verified this using "nm".Quoted 8 lines
When a KProbe is registered using an address instead of the
symbol_name, "register_kprobe()" [2] atkernel/kprobes.cindirectly calls "within_kprobe_blacklist()" [3] which performs "kprobe_lookup_name()". It then checks if that name is in the blacklist. This blacklist includes the names of the asm functions as well.I wrote this test module [4] to verify that an address in memcpy's range, for example, is also blacklisted.
Right, I think for C functions this is fine. But for OpenRISC assembly I think we do not provide enough info for this to work correctly.
For example above
_sys_call_handler, is just a label.In other architectures they do something like this:
SYM_CODE_START(handle_syscall)
UNWIND_HINT_UNDEFINED
csrrd t0,PERCPU_BASE_KS
...
bldo_syscall
Quoted 8 lines
STACKLEAK_ERASE
RESTORE_ALL_AND_RET
SYM_CODE_END(handle_syscall)
_ASM_NOKPROBE(handle_syscall)The SYM_CODE_START/SYM_CODE_END macros or similar are not used in OpenRISC, I think we need something to define the beginning and end of our asm macros in order for this to work.
Sorry, I am still not very clear here. My understanding from the implementation of kprobe_lookup_name [1] is that the kernel determines which function's/symbol's range an address belongs to by fetching the symbol that appears before and after this address in its sequence of symbols (kallsyms_seqs_of_names [2]). Since the kernel is treating the labels of asm functions also as symbols, it already has the symbol's offset.
In OpenRISC, some symbols like _sys_call_handler are wrapped in ENTRY() which is identical to SYM_FUNC_START() [3], while other labels don't have this wrapper. Labels without the wrapper are being treated as local symbols while those with ENTRY() are being treated as global symbols.
I agree that none of the non-C functions are suffixed with SYM_*_END() which is where the symbol's size/range is being set [4]. But I don't think this is required when the kernel performs a lookup on the address to get the corresponding symbol. Please let me know what your thoughts are.
Quoted 13 lines
-Stafford
[snip]
Quoted 8 lines
Thanks,
Sahil[1] https://github.com/torvalds/linux/commit/1be031de802ba486a7605b52eda825f128b026e2
[2] https://github.com/torvalds/linux/blob/master/kernel/kprobes.c#L2002
[3] https://github.com/torvalds/linux/blob/master/kernel/kprobes.c#L1730
[4] https://github.com/valdaarhun/or-dev/blob/main/home/kprobes_blacklist.c
Thanks,
Sahil
[1] https://elixir.bootlin.com/linux/v7.3.1/source/kernel/kallsyms.c#L170-L224
[2] https://elixir.bootlin.com/linux/v7.3.1/source/kernel/kallsyms.c#L160
[3] https://elixir.bootlin.com/linux/v7.3.1/source/include/linux/linkage.h#L122
[4] https://elixir.bootlin.com/linux/v7.3.1/source/include/linux/linkage.h#L165
PATCH v3 3/4 openrisc: Add unit tests for KProbes on branch instructions
In reply to a message not in the archiveTests already exist lib/tests to verify the generic functionality of KProbes. Add unit tests to verify that KProbes work on instructions that require simulation in the OpenRISC ISA, and that the corresponding delay slots are handled correctly.
---
Changes v2 -> v3:
- arch/openrisc/kernel/tests/test_kprobes_asm.S:
- (test_kprobes_*): Set value in r11 register to 0 prior to running tests
- (test_kprobes_adrp):
Place function at page-aligned address
Use PAGE_SIZE macro instead of magic number
Move value in r13 to r11 before exiting
Changes v1 -> v2: New commit
arch/openrisc/Kconfig.debug | 30 +++- arch/openrisc/kernel/Makefile | 1 + arch/openrisc/kernel/tests/Makefile | 3 + arch/openrisc/kernel/tests/test_kprobes.c | 59 +++++++ arch/openrisc/kernel/tests/test_kprobes.h | 24 +++ arch/openrisc/kernel/tests/test_kprobes_asm.S | 157 ++++++++++++++++++ 6 files changed, 273 insertions(+), 1 deletion(-) create mode 100644 arch/openrisc/kernel/tests/Makefile create mode 100644 arch/openrisc/kernel/tests/test_kprobes.c create mode 100644 arch/openrisc/kernel/tests/test_kprobes.h create mode 100644 arch/openrisc/kernel/tests/test_kprobes_asm.S
arch/openrisc/Kconfig.debug +29 -1
@@ -1,2 +1,30 @@ # SPDX-License-Identifier: GPL-2.0-only -# dummy file, do not delete +menu "openrisc Testing" + +menuconfig RUNTIME_KERNEL_TESTING_MENU + bool "openrisc kernel runtime testing" + default y + help + Enable openrisc kernel runtime testing. With this option, one can + build and run tests to verify the correctness of relevant components + in the kernel at runtime. + +if RUNTIME_KERNEL_TESTING_MENU + +config OR_KPROBES_KUNIT + tristate "KUnit test for kprobes on openrisc" + depends on KUNIT + depends on KPROBES + default KUNIT_ALL_TESTS + help + Enable testing of KProbes in OpenRISC for instructions that + require simulation. When further changes related to probes or + tracing are added to OpenRISC's port, these tests can help + verify that instruction simulation and processing of delay slots + continue to work as expected. + + If unsure, say N + +endif # RUNTIME_KERNEL_TESTING_MENU + +endmenu # "openrisc Testing"
arch/openrisc/kernel/Makefile +1 -0
@@ -15,6 +15,7 @@ obj-$(CONFIG_STACKTRACE) += stacktrace.o obj-$(CONFIG_MODULES) += module.o obj-$(CONFIG_OF) += prom.o obj-$(CONFIG_KPROBES) += kprobes.o +obj-$(CONFIG_OR_KPROBES_KUNIT) += tests/ obj-y += patching.o clean:
arch/openrisc/kernel/tests/Makefile new file +3 -0
@@ -0,0 +1,3 @@ +obj-$(CONFIG_OR_KPROBES_KUNIT) += openrisc_test_kprobes.o + +openrisc_test_kprobes-objs := test_kprobes.o test_kprobes_asm.o
arch/openrisc/kernel/tests/test_kprobes.c new file +59 -0
59 lines not on this page · raw message
arch/openrisc/kernel/tests/test_kprobes.h new file +24 -0
@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* Unit tests borrowed liberally from similar work of RISC-V. All +* original copyrights apply as per the original source declaration. +*/ + +#ifndef TEST_KPROBES_H +#define TEST_KPROBES_H + +#define KPROBE_TEST_MAGIC 0xDEADC0DE +#define KPROBE_TEST_MAGIC_LOWER 0x0000C0DE +#define KPROBE_TEST_MAGIC_UPPER 0x0000DEAD + +#ifndef __ASSEMBLER__ + +/* array of addresses to install kprobes */ +extern void *test_kprobes_addresses[]; + +/* array of functions that return KPROBE_TEST_MAGIC */ +extern unsigned long (*test_kprobes_functions[])(void ); + +#endif /* __ASSEMBLER__ */ + +#endif /* TEST_KPROBES_H */
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +157 -0
157 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v3 3/4] openrisc: Add unit tests for KProbes on branch instructions
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] openrisc: kprobes test probes l.addi instead of forward l.j in test_kprobes_j() - [Medium]…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] openrisc: kprobes test probes l.addi instead of forward l.j in test_kprobes_j()
- [Medium] openrisc: kprobes test leaves r13 stale, misplaces label, and lacks fallthrough returns --
commit d7000f832374f65f339afc3c16fe2e9e5cfe971f
Author: Sahil Siddiq <[email protected]>
openrisc: Add unit tests for KProbes on branch instructions
This commit adds KUnit tests for OpenRISC KProbes to verify instruction simulation and delay slot handling for branch, jump, and page-relative address calculation instructions.
Quoted 6 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +0
-0@@ -0,0 +1,157 @@
[ ... ]
arch/openrisc/kernel/tests/test_kprobes_asm.S line 19
Quoted 5 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +5
-0+SYM_FUNC_START(test_kprobes_j) +test_kprobes_j_addr1: + l.addi r11,r0,0 + l.j 2f + l.nop
[Severity: Medium]
Should test_kprobes_j_addr1 be placed after l.addi r11,r0,0 and immediately before l.j 2f?
When test_kprobe_openrisc() in arch/openrisc/kernel/tests/test_kprobes.c iterates over test_kprobes_addresses[] and calls register_kprobe(), test_kprobes_j_addr1 currently points to l.addi r11,r0,0 instead of the forward jump instruction l.j 2f. As a result, the kprobe is installed on l.addi rather than testing branch simulation on the forward l.j instruction.
Quoted 79 lines
+1: l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +78
-0+ l.addi r11,r13,0 + l.jr r9 + l.nop +2: l.movhi r13,KPROBE_TEST_MAGIC_UPPER +test_kprobes_j_addr2: + l.j 1b + l.nop +SYM_FUNC_END(test_kprobes_j) + +SYM_FUNC_START(test_kprobes_jal) + l.addi r11,r0,0 + l.addi r15,r9,0 +test_kprobes_jal_addr1: + l.jal 2f + l.nop +1: l.movhi r13,KPROBE_TEST_MAGIC_UPPER + l.jr r9 + l.nop +test_kprobes_jal_addr2: +2: l.jal 1b + l.nop + l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.addi r9,r15,0 + l.jr r9 + l.nop +SYM_FUNC_END(test_kprobes_jal) + +SYM_FUNC_START(test_kprobes_jr) + l.addi r11,r0,0 + l.movhi r15,hi(2f) + l.ori r15,r15,lo(2f) +test_kprobes_jr_addr1: + l.jr r15 + l.nop +1: l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.jr r9 + l.nop +2: l.movhi r13,KPROBE_TEST_MAGIC_UPPER + l.movhi r15,hi(1b) + l.ori r15,r15,lo(1b) +test_kprobes_jr_addr2: + l.jr r15 + l.nop +SYM_FUNC_END(test_kprobes_jr) + +SYM_FUNC_START(test_kprobes_jalr) + l.addi r11,r0,0 + l.addi r15,r9,0 + l.movhi r17,hi(2f) + l.ori r17,r17,lo(2f) +test_kprobes_jalr_addr1: + l.jalr r17 + l.nop +1: l.movhi r13,KPROBE_TEST_MAGIC_UPPER + l.jr r9 + l.nop +2: l.movhi r17,hi(1b) + l.ori r17,r17,lo(1b) +test_kprobes_jalr_addr2: + l.jalr r17 + l.nop + l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.addi r9,r15,0 + l.jr r9 + l.nop +SYM_FUNC_END(test_kprobes_jalr) + +SYM_FUNC_START(test_kprobes_branch) + l.addi r11,r0,0 + l.addi r15,r0,1 + l.addi r17,r0,0 + l.sfgts r15,r17 +test_kprobes_branch_addr1: + l.bf 2f + l.nop
arch/openrisc/kernel/tests/test_kprobes_asm.S line 108
Quoted 10 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +10
-0+1: l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.jr r9 + l.nop +2: l.movhi r13,KPROBE_TEST_MAGIC_UPPER + l.sfeq r15,r17 +test_kprobes_branch_addr2: + l.bnf 1b + l.nop +SYM_FUNC_END(test_kprobes_branch)
[Severity: Medium]
Can stale values in r13 and missing fallthrough returns in test_kprobes_j(), test_kprobes_jal(), test_kprobes_jr(), test_kprobes_jalr(), and test_kprobes_branch() cause false passes or execution past function boundaries if branch simulation fails?
First, each of these functions initializes r11 to 0 at entry:
l.addi r11,r0,0
However, they construct KPROBE_TEST_MAGIC in r13 using l.movhi and l.ori, and then copy r13 into r11 before returning:
l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER
l.addi r11,r13,0Unlike test_kprobes_adrp(), these five functions do not clear r13 on entry. Because the preceding test function in test_kprobe_openrisc() leaves 0xDEADC0DE in r13, if a simulated branch (such as l.jal 1b at test_kprobes_jal_addr2, l.jr r15 at test_kprobes_jr_addr1, l.jalr r17 at test_kprobes_jalr_addr2, or l.bf 2f at test_kprobes_branch_addr1) fails to branch and falls through to label 1 (or the instructions following the call), l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER preserves the upper bits of r13 from the previous test, overwrites r11 with 0xDEADC0DE, and returns a false success.
Second, in test_kprobes_j(), test_kprobes_jr(), and test_kprobes_branch(), there is no return sequence (l.jr r9; l.nop) after the backward branch at test_kprobes_j_addr2, test_kprobes_jr_addr2, and test_kprobes_branch_addr2. If one of those backward branches is not taken, execution will fall off the end of the function into the next function in .text (or, after test_kprobes_branch(), into the .align PAGE_SIZE zero-padding where 0x00000000 encodes l.j 0, an infinite self-jump) instead of returning to test_kprobe_openrisc() with a failure value in r11.
Would it make sense to clear r13 on entry in all test functions and add a fallthrough return after the backward branches?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Stafford Horne
maintainerRe: [PATCH v3 3/4] openrisc: Add unit tests for KProbes on branch instructions
In reply to Sahil SiddiqQuoted 196 lines · Sahil Siddiq
Tests already exist lib/tests to verify the generic functionality of KProbes. Add unit tests to verify that KProbes work on instructions that require simulation in the OpenRISC ISA, and that the corresponding delay slots are handled correctly.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/tests/test_kprobes_asm.S:
- (test_kprobes_*): Set value in r11 register to 0 prior to running tests
- (test_kprobes_adrp):
Place function at page-aligned address
UsePAGE_SIZEmacro instead of magic number
Move value in r13 to r11 before exitingChanges v1 -> v2: New commit
arch/openrisc/Kconfig.debug | 30 +++- arch/openrisc/kernel/Makefile | 1 + arch/openrisc/kernel/tests/Makefile | 3 + arch/openrisc/kernel/tests/test_kprobes.c | 59 +++++++ arch/openrisc/kernel/tests/test_kprobes.h | 24 +++ arch/openrisc/kernel/tests/test_kprobes_asm.S | 157 ++++++++++++++++++ 6 files changed, 273 insertions(+), 1 deletion(-) create mode 100644 arch/openrisc/kernel/tests/Makefile create mode 100644 arch/openrisc/kernel/tests/test_kprobes.c create mode 100644 arch/openrisc/kernel/tests/test_kprobes.h create mode 100644 arch/openrisc/kernel/tests/test_kprobes_asm.Sarch/openrisc/Kconfig.debug +29
-1@@ -1,2 +1,30 @@ # SPDX-License-Identifier: GPL-2.0-only -# dummy file, do not delete +menu "openrisc Testing" + +menuconfig RUNTIME_KERNEL_TESTING_MENU + bool "openrisc kernel runtime testing" + default y + help + Enable openrisc kernel runtime testing. With this option, one can + build and run tests to verify the correctness of relevant components + in the kernel at runtime. + +if RUNTIME_KERNEL_TESTING_MENU + +config OR_KPROBES_KUNIT + tristate "KUnit test for kprobes on openrisc" + depends on KUNIT + depends on KPROBES + default KUNIT_ALL_TESTS + help + Enable testing of KProbes in OpenRISC for instructions that + require simulation. When further changes related to probes or + tracing are added to OpenRISC's port, these tests can help + verify that instruction simulation and processing of delay slots + continue to work as expected. + + If unsure, say N + +endif # RUNTIME_KERNEL_TESTING_MENU + +endmenu # "openrisc Testing"arch/openrisc/kernel/Makefile +1
-0@@ -15,6 +15,7 @@ obj-$(CONFIG_STACKTRACE) += stacktrace.o obj-$(CONFIG_MODULES) += module.o obj-$(CONFIG_OF) += prom.o obj-$(CONFIG_KPROBES) += kprobes.o +obj-$(CONFIG_OR_KPROBES_KUNIT) += tests/ obj-y += patching.o clean:arch/openrisc/kernel/tests/Makefile new file +3
-0@@ -0,0 +1,3 @@ +obj-$(CONFIG_OR_KPROBES_KUNIT) += openrisc_test_kprobes.o + +openrisc_test_kprobes-objs := test_kprobes.o test_kprobes_asm.oarch/openrisc/kernel/tests/test_kprobes.c new file +59
-0@@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* KProbe unit tests for OpenRISC +* +* Unit tests borrowed liberally from similar work of RISC-V. All +* original copyrights apply as per the original source declaration. +*/ + +// #include <linux/kernel.h> +#include <linux/kprobes.h> +#include <kunit/test.h> +#include "test_kprobes.h" + +static void test_kprobe_openrisc (struct kunit *test) +{ +unsigned int num_kprobe =0 ; +unsigned long (*func)(void ); +struct kprobe *kp; +int i; + +while (test_kprobes_addresses[num_kprobe]) + num_kprobe++; + + kp =kcalloc (num_kprobe,sizeof (struct kprobe ),GFP_KERNEL ); +KUNIT_EXPECT_TRUE (test, kp); +if (!kp) +return ; + +for (i =0 ; i < num_kprobe; ++i) { + kp[i].addr = test_kprobes_addresses[i]; +KUNIT_EXPECT_EQ (test,0 ,register_kprobe (&kp[i])); + } + +for (i =0 ;; ++i) { + func = test_kprobes_functions[i]; +if (!func) +break ; +KUNIT_EXPECT_EQ_MSG (test,KPROBE_TEST_MAGIC ,func (),"function %d broken" , i); + } + +for (i =0 ; i < num_kprobe; ++i) +unregister_kprobe (&kp[i]); +kfree (kp); +} + +static struct kunit_case kprobes_testcases[] = { +KUNIT_CASE (test_kprobe_openrisc), + {} +}; + +static struct kunit_suite kprobes_test_suite = { + .name ="kprobes_openrisc" , + .test_cases = kprobes_testcases, +}; + +kunit_test_suites (&kprobes_test_suite); + +MODULE_LICENSE ("GPL" ); +MODULE_DESCRIPTION ("KUnit test for OpenRISC KProbes" );arch/openrisc/kernel/tests/test_kprobes.h new file +24
-0@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* Unit tests borrowed liberally from similar work of RISC-V. All +* original copyrights apply as per the original source declaration. +*/ + +#ifndef TEST_KPROBES_H +#define TEST_KPROBES_H + +#define KPROBE_TEST_MAGIC 0xDEADC0DE +#define KPROBE_TEST_MAGIC_LOWER 0x0000C0DE +#define KPROBE_TEST_MAGIC_UPPER 0x0000DEAD + +#ifndef __ASSEMBLER__ + +/* array of addresses to install kprobes */ +extern void *test_kprobes_addresses[]; + +/* array of functions that return KPROBE_TEST_MAGIC */ +extern unsigned long (*test_kprobes_functions[])(void ); + +#endif /* __ASSEMBLER__ */ + +#endif /* TEST_KPROBES_H */ arch/openrisc/kernel/tests/test_kprobes_asm.S new file +9
-0@@ -0,0 +1,157 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * KProbes unit tests for OpenRISC + * + * Unit tests borrowed liberally from similar work of RISC-V. All + * original copyrights apply as per the original source declaration. + */ + +#include <linux/linkage.h>
arch/openrisc/kernel/tests/test_kprobes_asm.S line 19
Quoted 10 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +10
-0+#include <asm/asm.h> +#include <asm/page.h> + +#include "test_kprobes.h" + +SYM_FUNC_START(test_kprobes_j) +test_kprobes_j_addr1: + l.addi r11,r0,0 + l.j 2f + l.nop
Just a tiny comment here about indenting the delay slots.
You could also use the delayslots here, for example:
l.j 2f l.addi r11,r0,0
Quoted 141 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +138
-0+1: l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.jr r9 + l.nop +2: l.movhi r13,KPROBE_TEST_MAGIC_UPPER +test_kprobes_j_addr2: + l.j 1b + l.nop +SYM_FUNC_END(test_kprobes_j) + +SYM_FUNC_START(test_kprobes_jal) + l.addi r11,r0,0 + l.addi r15,r9,0 +test_kprobes_jal_addr1: + l.jal 2f + l.nop +1: l.movhi r13,KPROBE_TEST_MAGIC_UPPER + l.jr r9 + l.nop +test_kprobes_jal_addr2: +2: l.jal 1b + l.nop + l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.addi r9,r15,0 + l.jr r9 + l.nop +SYM_FUNC_END(test_kprobes_jal) + +SYM_FUNC_START(test_kprobes_jr) + l.addi r11,r0,0 + l.movhi r15,hi(2f) + l.ori r15,r15,lo(2f) +test_kprobes_jr_addr1: + l.jr r15 + l.nop +1: l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.jr r9 + l.nop +2: l.movhi r13,KPROBE_TEST_MAGIC_UPPER + l.movhi r15,hi(1b) + l.ori r15,r15,lo(1b) +test_kprobes_jr_addr2: + l.jr r15 + l.nop +SYM_FUNC_END(test_kprobes_jr) + +SYM_FUNC_START(test_kprobes_jalr) + l.addi r11,r0,0 + l.addi r15,r9,0 + l.movhi r17,hi(2f) + l.ori r17,r17,lo(2f) +test_kprobes_jalr_addr1: + l.jalr r17 + l.nop +1: l.movhi r13,KPROBE_TEST_MAGIC_UPPER + l.jr r9 + l.nop +2: l.movhi r17,hi(1b) + l.ori r17,r17,lo(1b) +test_kprobes_jalr_addr2: + l.jalr r17 + l.nop + l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.addi r9,r15,0 + l.jr r9 + l.nop +SYM_FUNC_END(test_kprobes_jalr) + +SYM_FUNC_START(test_kprobes_branch) + l.addi r11,r0,0 + l.addi r15,r0,1 + l.addi r17,r0,0 + l.sfgts r15,r17 +test_kprobes_branch_addr1: + l.bf 2f + l.nop +1: l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.jr r9 + l.nop +2: l.movhi r13,KPROBE_TEST_MAGIC_UPPER + l.sfeq r15,r17 +test_kprobes_branch_addr2: + l.bnf 1b + l.nop +SYM_FUNC_END(test_kprobes_branch) + + .align PAGE_SIZE +SYM_FUNC_START(test_kprobes_adrp) + l.addi r11,r0,0 + l.addi r13,r0,0 + l.addi r15,r9,0 + l.addi r17,r0,-PAGE_SIZE + l.jal 1f + l.nop +1: l.and r19,r9,r17 +test_kprobes_adrp_addr: + l.adrp r21,0 + l.sfeq r21,r19 + l.bnf 2f + l.nop + l.movhi r13,KPROBE_TEST_MAGIC_UPPER + l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 +2: l.addi r9,r15,0 + l.jr r9 + l.nop +SYM_FUNC_END(test_kprobes_adrp) + + .section .rodata +SYM_DATA_START(test_kprobes_addresses) + .word test_kprobes_j_addr1 + .word test_kprobes_j_addr2 + .word test_kprobes_jal_addr1 + .word test_kprobes_jal_addr2 + .word test_kprobes_jr_addr1 + .word test_kprobes_jr_addr2 + .word test_kprobes_jalr_addr1 + .word test_kprobes_jalr_addr2 + .word test_kprobes_branch_addr1 + .word test_kprobes_branch_addr2 + .word test_kprobes_adrp_addr + .word 0 +SYM_DATA_END(test_kprobes_addresses) + + .section .rodata +SYM_DATA_START(test_kprobes_functions) + .word test_kprobes_j + .word test_kprobes_jal + .word test_kprobes_jr + .word test_kprobes_jalr + .word test_kprobes_branch + .word test_kprobes_adrp + .word 0 +SYM_DATA_END(test_kprobes_functions)Signature · 1 line
2.55.0
Re: [PATCH v3 3/4] openrisc: Add unit tests for KProbes on branch instructions
Quoted 50 lines · Stafford Horne
Quoted 49 lines · Sahil Siddiq
Tests already exist lib/tests to verify the generic functionality of KProbes. Add unit tests to verify that KProbes work on instructions that require simulation in the OpenRISC ISA, and that the corresponding delay slots are handled correctly.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/tests/test_kprobes_asm.S:
- (test_kprobes_*): Set value in r11 register to 0 prior to running tests
- (test_kprobes_adrp):
Place function at page-aligned address
UsePAGE_SIZEmacro instead of magic number
Move value in r13 to r11 before exitingChanges v1 -> v2: New commit
arch/openrisc/Kconfig.debug | 30 +++- arch/openrisc/kernel/Makefile | 1 + arch/openrisc/kernel/tests/Makefile | 3 + arch/openrisc/kernel/tests/test_kprobes.c | 59 +++++++ arch/openrisc/kernel/tests/test_kprobes.h | 24 +++ arch/openrisc/kernel/tests/test_kprobes_asm.S | 157 ++++++++++++++++++ 6 files changed, 273 insertions(+), 1 deletion(-)create mode 100644
arch/openrisc/kernel/tests/Makefilecreate mode 100644arch/openrisc/kernel/tests/test_kprobes.ccreate mode 100644arch/openrisc/kernel/tests/test_kprobes.hcreate mode 100644arch/openrisc/kernel/tests/test_kprobes_asm.S[...]
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +13
-0@@ -0,0 +1,157 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * KProbes unit tests for OpenRISC + * + * Unit tests borrowed liberally from similar work of RISC-V. All + * original copyrights apply as per the original source declaration. + */ + +#include <linux/linkage.h> +#include <asm/asm.h> +#include <asm/page.h> + +#include "test_kprobes.h"
Quoted 8 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S line 19
Quoted 6 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +6
-0+ +SYM_FUNC_START(test_kprobes_j) +test_kprobes_j_addr1: + l.addi r11,r0,0 + l.j 2f + l.nopJust a tiny comment here about indenting the delay slots.
Got it, I'll indent this.
Quoted 4 lines
You could also use the delayslots here, for example:
l.j 2f l.addi r11,r0,0
I initially thought of that too. But then I thought by keeping l.addi before l.j, I would also be able to test this for the case when there are no delay slots. I can reshuffle the instructions if that test isn't required. Please let me know what your thoughts are.
Quoted 5 lines
Quoted 5 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +5
-0+1: l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.jr r9 + l.nop +2: l.movhi r13,KPROBE_TEST_MAGIC_UPPER
Quoted 8 lines
Quoted 8 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +4
-0+test_kprobes_j_addr2: + l.j 1b + l.nop +SYM_FUNC_END(test_kprobes_j)Signature · 1 line
2.55.0
Regards,
Sahil
Stafford Horne
maintainerRe: [PATCH v3 3/4] openrisc: Add unit tests for KProbes on branch instructions
Quoted 64 lines · Sahil
Quoted 50 lines · Stafford Horne
Quoted 49 lines · Sahil Siddiq
Tests already exist lib/tests to verify the generic functionality of KProbes. Add unit tests to verify that KProbes work on instructions that require simulation in the OpenRISC ISA, and that the corresponding delay slots are handled correctly.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/tests/test_kprobes_asm.S:
- (test_kprobes_*): Set value in r11 register to 0 prior to running tests
- (test_kprobes_adrp):
Place function at page-aligned address
UsePAGE_SIZEmacro instead of magic number
Move value in r13 to r11 before exitingChanges v1 -> v2: New commit
arch/openrisc/Kconfig.debug | 30 +++- arch/openrisc/kernel/Makefile | 1 + arch/openrisc/kernel/tests/Makefile | 3 + arch/openrisc/kernel/tests/test_kprobes.c | 59 +++++++ arch/openrisc/kernel/tests/test_kprobes.h | 24 +++ arch/openrisc/kernel/tests/test_kprobes_asm.S | 157 ++++++++++++++++++ 6 files changed, 273 insertions(+), 1 deletion(-)create mode 100644
arch/openrisc/kernel/tests/Makefilecreate mode 100644arch/openrisc/kernel/tests/test_kprobes.ccreate mode 100644arch/openrisc/kernel/tests/test_kprobes.hcreate mode 100644arch/openrisc/kernel/tests/test_kprobes_asm.S[...]
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +13
-0@@ -0,0 +1,157 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * KProbes unit tests for OpenRISC + * + * Unit tests borrowed liberally from similar work of RISC-V. All + * original copyrights apply as per the original source declaration. + */ + +#include <linux/linkage.h> +#include <asm/asm.h> +#include <asm/page.h> + +#include "test_kprobes.h"Quoted 8 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S line 19
Quoted 6 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +6
-0+ +SYM_FUNC_START(test_kprobes_j) +test_kprobes_j_addr1: + l.addi r11,r0,0 + l.j 2f + l.nopJust a tiny comment here about indenting the delay slots.
Got it, I'll indent this.
Quoted 2 lines
You could also use the delayslots here, for example:
Quoted 7 lines
Quoted 2 lines
l.j 2f l.addi r11,r0,0I initially thought of that too. But then I thought by keeping l.addi before l.j, I would also be able to test this for the case when there are no delay slots. I can reshuffle the instructions if that test isn't required. Please let me know what your thoughts are.
I don't think it matters either way since these are tests. But, it would be good to note that in a comment at the top of the files where you want to maintain that convention.
However, thinking a bit further that may be hard to enforce down the line just for a handful of files. We should assume the kernel code uses delayslots.
-Stafford
Quoted 16 lines
Quoted 5 lines
Quoted 5 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +5
-0+1: l.ori r13,r13,KPROBE_TEST_MAGIC_LOWER + l.addi r11,r13,0 + l.jr r9 + l.nop +2: l.movhi r13,KPROBE_TEST_MAGIC_UPPERQuoted 8 lines
Quoted 8 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S new file +4
-0+test_kprobes_j_addr2: + l.j 1b + l.nop +SYM_FUNC_END(test_kprobes_j)Signature · 1 line
2.55.0Regards,
Sahil
Re: [PATCH v3 3/4] openrisc: Add unit tests for KProbes on branch instructions
Quoted 31 lines · Stafford Horne
Quoted 22 lines · Sahil
Quoted 6 lines · Stafford Horne
Quoted 5 lines · Sahil Siddiq
Tests already exist lib/tests to verify the generic functionality of KProbes. Add unit tests to verify that KProbes work on instructions that require simulation in the OpenRISC ISA, and that the corresponding delay slots are handled correctly.
Quoted 10 lines
arch/openrisc/kernel/tests/test_kprobes_asm.S line 19
Quoted 8 lines
Signed-off-by Sahil Siddiq <[email protected]>[...]arch/openrisc/kernel/tests/test_kprobes_asm.S new file +6
-0+ +SYM_FUNC_START(test_kprobes_j) +test_kprobes_j_addr1: + l.addi r11,r0,0 + l.j 2f + l.nopJust a tiny comment here about indenting the delay slots.
Got it, I'll indent this.
Quoted 2 lines
You could also use the delayslots here, for example:
Quoted 7 lines
Quoted 2 lines
l.j 2f l.addi r11,r0,0I initially thought of that too. But then I thought by keeping l.addi before l.j, I would also be able to test this for the case when there are no delay slots. I can reshuffle the instructions if that test isn't required. Please let me know what your thoughts are.
Quoted 6 lines
I don't think it matters either way since these are tests. But, it would be good to note that in a comment at the top of the files where you want to maintain that convention.
However, thinking a bit further that may be hard to enforce down the line just for a handful of files. We should assume the kernel code uses delayslots.
I agree. Since "head.S" and "entry.S" already use delay slots, I don't think the kernel will work with a CPU config that has delay slots disabled. Also, there should now be no need to have a static key for "delay_slot".
Quoted 3 lines
-Stafford
Thanks,
Sahil
PATCH v3 4/4 openrisc: Add Kretprobes
In reply to a message not in the archiveAdd Kretprobes support for OpenRISC. Kretprobes allow a probe to be fired when a function returns. They are built on top of the generic rethook framework and also require the KProbe mechanism introduced in the previous commit. This work is primarily based on similar work done for RISC-V.
Kretprobes work by inserting a KProbe at a function's entry point. When the function begins to execute, the KProbe is fired and its pre-handler replaces the function's return address with that of the rethook trampoline. The trampoline in turn calls the kretprobe handler. Control is returned to the original caller following this.
---
Changes v2 -> v3:
- arch/openrisc/kernel/rethook_trampoline.S:
(save_all_base_regs): Save SR and SP registers
(restore_all_base_regs): Restore SR register
Changes v1 -> v2: New commit
arch/openrisc/Kconfig | 2 + arch/openrisc/kernel/Makefile | 1 + arch/openrisc/kernel/rethook.c | 32 +++++++ arch/openrisc/kernel/rethook.h | 8 ++ arch/openrisc/kernel/rethook_trampoline.S | 111 ++++++++++++++++++++++ 5 files changed, 154 insertions(+) create mode 100644 arch/openrisc/kernel/rethook.c create mode 100644 arch/openrisc/kernel/rethook.h create mode 100644 arch/openrisc/kernel/rethook_trampoline.S
arch/openrisc/Kconfig +2 -0
@@ -28,6 +28,8 @@ config OPENRISC select HAVE_ARCH_JUMP_LABEL_RELATIVE select HAVE_PCI select HAVE_KPROBES + select HAVE_KRETPROBES + select HAVE_RETHOOK select HAVE_UID16 select HAVE_PAGE_SIZE_8KB select HAVE_REGS_AND_STACK_ACCESS_API
arch/openrisc/kernel/Makefile +1 -0
@@ -15,6 +15,7 @@ obj-$(CONFIG_STACKTRACE) += stacktrace.o obj-$(CONFIG_MODULES) += module.o obj-$(CONFIG_OF) += prom.o obj-$(CONFIG_KPROBES) += kprobes.o +obj-$(CONFIG_RETHOOK) += rethook.o rethook_trampoline.o obj-$(CONFIG_OR_KPROBES_KUNIT) += tests/ obj-y += patching.o
arch/openrisc/kernel/rethook.c new file +32 -0
@@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Generic return hook for OpenRISC. Depends on KProbes. +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* OpenRISC implementation: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#include <linux/kprobes.h> +#include <linux/rethook.h> +#include "rethook.h" + +unsigned long arch_rethook_trampoline_callback (struct pt_regs *regs) +{ +return rethook_trampoline_handler (regs, regs->gpr2); +} +NOKPROBE_SYMBOL (arch_rethook_trampoline_callback) + +void arch_rethook_prepare(struct rethook_node *rhn, struct pt_regs *regs, bool mcount) +{ +/* Store original return address and frame pointer */ + rhn->ret_addr = regs->gpr9; + rhn->frame = regs->gpr2; + +/* Set return address to trampoline */ + regs->gpr9 = (unsigned long )arch_rethook_trampoline; +} +NOKPROBE_SYMBOL (arch_rethook_prepare)
arch/openrisc/kernel/rethook.h new file +8 -0
@@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef __OPENRISC_RETHOOK_H +#define __OPENRISC_RETHOOK_H + +unsigned long arch_rethook_trampoline_callback (struct pt_regs *regs); +void arch_rethook_prepare (struct rethook_node *rhn,struct pt_regs *regs,bool mcount); + +#endif
arch/openrisc/kernel/rethook_trampoline.S new file +111 -0
111 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v3 4/4] openrisc: Add Kretprobes
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] openrisc: missing NOKPROBE annotation on arch_rethook_trampoline() --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] openrisc: missing NOKPROBE annotation on arch_rethook_trampoline() --
commit 20e73d01661b40600429433415de2e9c63032d8f
Author: Sahil Siddiq <[email protected]>
openrisc: Add Kretprobes
This commit adds Kretprobes support for OpenRISC on top of the generic rethook framework, providing arch_rethook_prepare(), arch_rethook_trampoline_callback(), and the assembly return trampoline arch_rethook_trampoline.
Quoted 14 lines
arch/openrisc/kernel/rethook_trampoline.S new file +8
-0@@ -0,0 +1,111 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Author: Sahil Siddiq <[email protected]> + */ + +#include <linux/linkage.h> + +#include <asm/asm.h>
[ ... ]
Quoted 8 lines
arch/openrisc/kernel/rethook_trampoline.S new file +8
-0+SYM_CODE_START(arch_rethook_trampoline) + /* Allocate enough space on stack for pt_regs */ + l.addi r1,r1,-PT_SIZE + save_all_base_regs + + l.addi r3,r1,0 /* pt_regs */ + l.jal arch_rethook_trampoline_callback + l.nop
arch/openrisc/kernel/rethook_trampoline.S line 111
Quoted 10 lines
arch/openrisc/kernel/rethook_trampoline.S new file +10
-0+ + /* use the result as the return-address */ + l.addi r9,r11,0 + + restore_all_base_regs + l.addi r1,r1,PT_SIZE + + l.jr r9 + l.nop +SYM_CODE_END(arch_rethook_trampoline)
[Severity: High]
Should arch_rethook_trampoline be marked with _ASM_NOKPROBE() here (or NOKPROBE_SYMBOL() in arch/openrisc/kernel/rethook.c)?
Although arch/openrisc/kernel/rethook_trampoline.S includes <asm/asm.h> and arch/openrisc/kernel/rethook.c marks arch_rethook_trampoline_callback() and arch_rethook_prepare() with NOKPROBE_SYMBOL(), arch_rethook_trampoline is placed in .text without a kprobe blacklist annotation.
Because arch_rethook_trampoline is not blacklisted, registering a kretprobe or kprobe on arch_rethook_trampoline is permitted. When a kretprobed function returns to arch_rethook_trampoline with r9 holding the address of arch_rethook_trampoline, a kretprobe on arch_rethook_trampoline triggers:
pre_handler_kretprobe()
rethook_hook()
arch_rethook_prepare()
rhn->ret_addr = regs->gpr9;which pushes a rethook_node with ret_addr set to arch_rethook_trampoline onto current->rethooks. When arch_rethook_trampoline_callback() then calls rethook_trampoline_handler(), __rethook_find_ret_addr() skips nodes whose ret_addr equals arch_rethook_trampoline:
kernel/trace/rethook.c:__rethook_find_ret_addr() {
...
while (node) {
rh = container_of(node, struct rethook_node, llist);
if (rh->ret_addr != (unsigned long)arch_rethook_trampoline) {
*cur = node;
return rh->ret_addr;
}
node = node->next;
}
return 0;
}Can this corrupt the current->rethooks shadow stack or trigger the BUG_ON(1) in rethook_trampoline_handler() when a probe is attached to arch_rethook_trampoline?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Stafford Horne
maintainerRe: [PATCH v3 4/4] openrisc: Add Kretprobes
In reply to Sahil SiddiqQuoted 82 lines · Sahil Siddiq
Add Kretprobes support for OpenRISC. Kretprobes allow a probe to be fired when a function returns. They are built on top of the generic rethook framework and also require the KProbe mechanism introduced in the previous commit. This work is primarily based on similar work done for RISC-V.
Kretprobes work by inserting a KProbe at a function's entry point. When the function begins to execute, the KProbe is fired and its pre-handler replaces the function's return address with that of the rethook trampoline. The trampoline in turn calls the kretprobe handler. Control is returned to the original caller following this.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/rethook_trampoline.S:
(save_all_base_regs): Save SR and SP registers
(restore_all_base_regs): Restore SR registerChanges v1 -> v2: New commit
arch/openrisc/Kconfig | 2 + arch/openrisc/kernel/Makefile | 1 + arch/openrisc/kernel/rethook.c | 32 +++++++ arch/openrisc/kernel/rethook.h | 8 ++ arch/openrisc/kernel/rethook_trampoline.S | 111 ++++++++++++++++++++++ 5 files changed, 154 insertions(+) create mode 100644 arch/openrisc/kernel/rethook.c create mode 100644 arch/openrisc/kernel/rethook.h create mode 100644 arch/openrisc/kernel/rethook_trampoline.Sarch/openrisc/Kconfig +2
-0@@ -28,6 +28,8 @@ config OPENRISC select HAVE_ARCH_JUMP_LABEL_RELATIVE select HAVE_PCI select HAVE_KPROBES + select HAVE_KRETPROBES + select HAVE_RETHOOK select HAVE_UID16 select HAVE_PAGE_SIZE_8KB select HAVE_REGS_AND_STACK_ACCESS_APIarch/openrisc/kernel/Makefile +1
-0@@ -15,6 +15,7 @@ obj-$(CONFIG_STACKTRACE) += stacktrace.o obj-$(CONFIG_MODULES) += module.o obj-$(CONFIG_OF) += prom.o obj-$(CONFIG_KPROBES) += kprobes.o +obj-$(CONFIG_RETHOOK) += rethook.o rethook_trampoline.o obj-$(CONFIG_OR_KPROBES_KUNIT) += tests/ obj-y += patching.oarch/openrisc/kernel/rethook.c new file +20
-0@@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Generic return hook for OpenRISC. Depends on KProbes. +* +* Linux architectural port borrowing liberally from similar works of +* others. All original copyrights apply as per the original source +* declaration. +* +* OpenRISC implementation: +* Copyright (C) 2026 Sahil Siddiq <[email protected]> +*/ + +#include <linux/kprobes.h> +#include <linux/rethook.h> +#include "rethook.h" + +unsigned long arch_rethook_trampoline_callback (struct pt_regs *regs) +{ +return rethook_trampoline_handler (regs, regs->gpr2); +}
arch/openrisc/kernel/rethook.c line 30
Quoted 10 lines
arch/openrisc/kernel/rethook.c new file +10
-0+NOKPROBE_SYMBOL (arch_rethook_trampoline_callback) + +void arch_rethook_prepare(struct rethook_node *rhn, struct pt_regs *regs, bool mcount) +{ +/* Store original return address and frame pointer */ + rhn->ret_addr = regs->gpr9; + rhn->frame = regs->gpr2; + +/* Set return address to trampoline */ + regs->gpr9 = (unsigned long )arch_rethook_trampoline;
Though this will work, in the kernel code we prefer to regs->gpr[n] syntax for accessing gprs. So to be consistent could you use that? i.e. regs->gpr[9];
Quoted 113 lines
arch/openrisc/kernel/rethook.c new file +2
-0+} +NOKPROBE_SYMBOL (arch_rethook_prepare)arch/openrisc/kernel/rethook.h new file +8
-0@@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef __OPENRISC_RETHOOK_H +#define __OPENRISC_RETHOOK_H + +unsigned long arch_rethook_trampoline_callback (struct pt_regs *regs); +void arch_rethook_prepare (struct rethook_node *rhn,struct pt_regs *regs,bool mcount); + +#endif arch/openrisc/kernel/rethook_trampoline.S new file +91
-0@@ -0,0 +1,111 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Author: Sahil Siddiq <[email protected]> + */ + +#include <linux/linkage.h> + +#include <asm/asm.h> +#include <asm/asm-offsets.h> +#include <asm/ptrace.h> + + .text + + .macro save_all_base_regs + l.sw PT_GPR2(r1),r2 + l.sw PT_GPR3(r1),r3 + l.sw PT_GPR4(r1),r4 + l.sw PT_GPR5(r1),r5 + l.sw PT_GPR6(r1),r6 + l.sw PT_GPR7(r1),r7 + l.sw PT_GPR8(r1),r8 + l.sw PT_GPR9(r1),r9 + l.sw PT_GPR10(r1),r10 + l.sw PT_GPR11(r1),r11 + l.sw PT_GPR12(r1),r12 + l.sw PT_GPR13(r1),r13 + l.sw PT_GPR14(r1),r14 + l.sw PT_GPR15(r1),r15 + l.sw PT_GPR16(r1),r16 + l.sw PT_GPR17(r1),r17 + l.sw PT_GPR18(r1),r18 + l.sw PT_GPR19(r1),r19 + l.sw PT_GPR20(r1),r20 + l.sw PT_GPR21(r1),r21 + l.sw PT_GPR22(r1),r22 + l.sw PT_GPR23(r1),r23 + l.sw PT_GPR24(r1),r24 + l.sw PT_GPR25(r1),r25 + l.sw PT_GPR26(r1),r26 + l.sw PT_GPR27(r1),r27 + l.sw PT_GPR28(r1),r28 + l.sw PT_GPR29(r1),r29 + l.sw PT_GPR30(r1),r30 + l.sw PT_GPR31(r1),r31 + /* Save SR in pt_regs */ + l.mfspr r13,r0,SPR_SR + l.sw PT_SR(r1),r13 + /* Save SP in pt_regs as it was prior to setting up this frame */ + l.addi r13,r1,PT_SIZE + l.sw PT_SP(r1),r13 + .endm + + .macro restore_all_base_regs + /* Restore SR from pt_regs */ + l.lwz r13,PT_SR(r1) + l.mtspr r0,r13,SPR_SR + /* + * r1 doesn't need to be explicitly restored from pt_regs. When + * arch_rethook_trampoline_callback finishes, it restores SP to + * what it was before its frame was set up. + */ + l.lwz r2,PT_GPR2(r1) + l.lwz r3,PT_GPR3(r1) + l.lwz r4,PT_GPR4(r1) + l.lwz r5,PT_GPR5(r1) + l.lwz r6,PT_GPR6(r1) + l.lwz r7,PT_GPR7(r1) + l.lwz r8,PT_GPR8(r1) + /* Return address in r9 is stale, so don't restore it */ + l.lwz r10,PT_GPR10(r1) + l.lwz r11,PT_GPR11(r1) + l.lwz r12,PT_GPR12(r1) + l.lwz r13,PT_GPR13(r1) + l.lwz r14,PT_GPR14(r1) + l.lwz r15,PT_GPR15(r1) + l.lwz r16,PT_GPR16(r1) + l.lwz r17,PT_GPR17(r1) + l.lwz r18,PT_GPR18(r1) + l.lwz r19,PT_GPR19(r1) + l.lwz r20,PT_GPR20(r1) + l.lwz r21,PT_GPR21(r1) + l.lwz r22,PT_GPR22(r1) + l.lwz r23,PT_GPR23(r1) + l.lwz r24,PT_GPR24(r1) + l.lwz r25,PT_GPR25(r1) + l.lwz r26,PT_GPR26(r1) + l.lwz r27,PT_GPR27(r1) + l.lwz r28,PT_GPR28(r1) + l.lwz r29,PT_GPR29(r1) + l.lwz r30,PT_GPR30(r1) + l.lwz r31,PT_GPR31(r1)
arch/openrisc/kernel/rethook_trampoline.S line 101
Quoted 10 lines
arch/openrisc/kernel/rethook_trampoline.S new file +10
-0+ .endm + +SYM_CODE_START(arch_rethook_trampoline) + /* Allocate enough space on stack for pt_regs */ + l.addi r1,r1,-PT_SIZE + save_all_base_regs + + l.addi r3,r1,0 /* pt_regs */ + l.jal arch_rethook_trampoline_callback + l.nop
Could you indent the delay slot? For example:
l.jal ... l.nop
arch/openrisc/kernel/rethook_trampoline.S line 110
Quoted 9 lines
arch/openrisc/kernel/rethook_trampoline.S new file +9
-0+ + /* use the result as the return-address */ + l.addi r9,r11,0 + + restore_all_base_regs + l.addi r1,r1,PT_SIZE + + l.jr r9 + l.nop
Indent here too.
arch/openrisc/kernel/rethook_trampoline.S line 111
Quoted 1 line
arch/openrisc/kernel/rethook_trampoline.S new file +1
-0+SYM_CODE_END(arch_rethook_trampoline)
Thanks,
-Stafford
Re: [PATCH v3 4/4] openrisc: Add Kretprobes
Quoted 36 lines · Stafford Horne
Quoted 35 lines · Sahil Siddiq
Add Kretprobes support for OpenRISC. Kretprobes allow a probe to be fired when a function returns. They are built on top of the generic rethook framework and also require the KProbe mechanism introduced in the previous commit. This work is primarily based on similar work done for RISC-V.
Kretprobes work by inserting a KProbe at a function's entry point. When the function begins to execute, the KProbe is fired and its pre-handler replaces the function's return address with that of the rethook trampoline. The trampoline in turn calls the kretprobe handler. Control is returned to the original caller following this.
Signed-off-by Sahil Siddiq <[email protected]>---
Changes v2 -> v3:
-arch/openrisc/kernel/rethook_trampoline.S:
(save_all_base_regs): Save SR and SP registers
(restore_all_base_regs): Restore SR registerChanges v1 -> v2: New commit
[...]
arch/openrisc/kernel/rethook.c new file +13
-0+#include <linux/kprobes.h> +#include <linux/rethook.h> +#include "rethook.h" + +unsigned long arch_rethook_trampoline_callback (struct pt_regs *regs) +{ +return rethook_trampoline_handler (regs, regs->gpr2); +} +NOKPROBE_SYMBOL (arch_rethook_trampoline_callback) + +void arch_rethook_prepare(struct rethook_node *rhn, struct pt_regs *regs, bool mcount) +{ +/* Store original return address and frame pointer */
Quoted 8 lines
arch/openrisc/kernel/rethook.c line 30
Quoted 5 lines
arch/openrisc/kernel/rethook.c new file +5
-0+ rhn->ret_addr = regs->gpr9; + rhn->frame = regs->gpr2; + +/* Set return address to trampoline */ + regs->gpr9 = (unsigned long )arch_rethook_trampoline;Though this will work, in the kernel code we prefer to regs->gpr[n] syntax for accessing gprs. So to be consistent could you use that? i.e. regs->gpr[9];
Sure, I'll change this.
Quoted 36 lines
Quoted 21 lines
(quoted diff) +2
-0+} +NOKPROBE_SYMBOL(arch_rethook_prepare)arch/openrisc/kernel/rethook.h new file +8
-0@@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef __OPENRISC_RETHOOK_H +#define __OPENRISC_RETHOOK_H + +unsigned long arch_rethook_trampoline_callback (struct pt_regs *regs); +void arch_rethook_prepare (struct rethook_node *rhn,struct pt_regs *regs,bool mcount); + +#endif arch/openrisc/kernel/rethook_trampoline.S new file +0
-0arch/openrisc/kernel/rethook_trampoline.S line 101
Quoted 9 lines
arch/openrisc/kernel/rethook_trampoline.S new file +8
-0+SYM_CODE_START(arch_rethook_trampoline) + /* Allocate enough space on stack for pt_regs */ + l.addi r1,r1,-PT_SIZE + save_all_base_regs + + l.addi r3,r1,0 /* pt_regs */ + l.jal arch_rethook_trampoline_callback + l.nopCould you indent the delay slot? For example:
l.jal ... l.nop
Quoted 11 lines
arch/openrisc/kernel/rethook_trampoline.S line 110
Quoted 9 lines
arch/openrisc/kernel/rethook_trampoline.S new file +9
-0+ + /* use the result as the return-address */ + l.addi r9,r11,0 + + restore_all_base_regs + l.addi r1,r1,PT_SIZE + + l.jr r9 + l.nopIndent here too.
Sure, I'll format these as well.
Quoted 5 lines
Quoted 1 line
+SYM_CODE_END(arch_rethook_trampoline)
Thanks,
-Stafford
Thanks,
Sahil