Skip to contentSkip to conversation

riscv: add initial support for hardware breakpoints

RFC PATCH In review Jesse Taube 3 participants 18 messages Jul 22, 2025 – Aug 4, 2025

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

cover riscv: add initial support for hardware breakpoints

This patchset adds initial support for hardware breakpoints and watchpoints to the RISC-V architecture. The framework is built on top of perf subsystem and SBI debug trigger extension.

Currently following features are not supported and are in works:
- Ptrace regset support
- Virtualization of debug triggers

The SBI debug trigger extension can be found at:
https://github.com/riscv-non-isa/riscv-sbi-doc/blob/master/src/ext-debug-triggers.adoc

The Sdtrig ISA is part of RISC-V debug specification which can be found at:
https://github.com/riscv/riscv-debug-spec

based off the original RFC by Himanshu Chauhan here:
https://lore.kernel.org/lkml/[email protected]/

Himanshu Chauhan (2):
riscv: Add SBI debug trigger extension and function ids
riscv: Introduce support for hardware break/watchpoints

Jesse Taube (4):
riscv: Add insn.c, consolidate instruction decoding
riscv: insn: __read_insn use copy_from_X_nofault
riscv: hw_breakpoint: Use icount for single stepping
riscv: ptrace: Add hw breakpoint support

 arch/riscv/Kconfig                     |  12 +
 arch/riscv/include/asm/bug.h           |  12 -
 arch/riscv/include/asm/hw_breakpoint.h |  60 +++
 arch/riscv/include/asm/insn.h          | 131 ++++-
 arch/riscv/include/asm/kdebug.h        |   3 +-
 arch/riscv/include/asm/processor.h     |   4 +
 arch/riscv/include/asm/sbi.h           |  33 +-
 arch/riscv/include/uapi/asm/ptrace.h   |   3 +-
 arch/riscv/kernel/Makefile             |   2 +
 arch/riscv/kernel/hw_breakpoint.c      | 681 +++++++++++++++++++++++++
 arch/riscv/kernel/insn.c               | 153 ++++++
 arch/riscv/kernel/kgdb.c               | 102 +---
 arch/riscv/kernel/probes/kprobes.c     |   1 +
 arch/riscv/kernel/process.c            |   4 +
 arch/riscv/kernel/ptrace.c             |  93 ++++
 arch/riscv/kernel/traps.c              |  11 +-
 arch/riscv/kernel/traps_misaligned.c   |  93 +---
 17 files changed, 1208 insertions(+), 190 deletions(-)
 create mode 100644 arch/riscv/include/asm/hw_breakpoint.h
 create mode 100644 arch/riscv/kernel/hw_breakpoint.c
 create mode 100644 arch/riscv/kernel/insn.c
Signature · 1 line
2.43.0
#1 lore raw

RFC PATCH 1/6 riscv: Add insn.c, consolidate instruction decoding

Various parts of the kernel decode and read instruction from memory. Functions like get_insn, GET_INSN_LENGTH and riscv_insn_is_c are defined in multiple places. Consolidate these functions into the insn.h and the newly added insn.c.

---
 arch/riscv/include/asm/bug.h         |  12 ---
 arch/riscv/include/asm/insn.h        | 131 ++++++++++++++++++++++-
 arch/riscv/kernel/Makefile           |   1 +
 arch/riscv/kernel/insn.c             | 151 +++++++++++++++++++++++++++
 arch/riscv/kernel/kgdb.c             | 102 +-----------------
 arch/riscv/kernel/probes/kprobes.c   |   1 +
 arch/riscv/kernel/traps.c            |   5 +-
 arch/riscv/kernel/traps_misaligned.c |  93 ++++-------------
 8 files changed, 309 insertions(+), 187 deletions(-)
 create mode 100644 arch/riscv/kernel/insn.c
arch/riscv/include/asm/bug.h +0 -12
index 1aaea81fb141..a2777eb67ad1 100644
@@ -12,21 +12,9 @@
 
 #include <asm/asm.h>
 
-#define __INSN_LENGTH_MASK  _UL(0x3)
-#define __INSN_LENGTH_32    _UL(0x3)
-#define __COMPRESSED_INSN_MASK	_UL(0xffff)
-
 #define __BUG_INSN_32	_UL(0x00100073) /* ebreak */
 #define __BUG_INSN_16	_UL(0x9002) /* c.ebreak */
 
-#define GET_INSN_LENGTH(insn)						\
-({									\
-	unsigned long __len;						\
-	__len = ((insn & __INSN_LENGTH_MASK) == __INSN_LENGTH_32) ?	\
-		4UL : 2UL;						\
-	__len;								\
-})
-
 typedef u32 bug_insn_t;
 
 #ifdef CONFIG_GENERIC_BUG_RELATIVE_POINTERS
arch/riscv/include/asm/insn.h +129 -2

196 lines not on this page · raw message

arch/riscv/kernel/Makefile +1 -0
index f7480c9c6f8d..4f719b09e5ad 100644
@@ -51,6 +51,7 @@ obj-$(CONFIG_RISCV_ALTERNATIVE) += alternative.o
 obj-y	+= cpu.o
 obj-y	+= cpufeature.o
 obj-y	+= entry.o
+obj-y	+= insn.o
 obj-y	+= irq.o
 obj-y	+= process.o
 obj-y	+= ptrace.o
arch/riscv/kernel/insn.c new file +151 -0

151 lines not on this page · raw message

arch/riscv/kernel/kgdb.c +5 -97

116 lines not on this page · raw message

arch/riscv/kernel/probes/kprobes.c +1 -0
index c0738d6c6498..6a9cfb0b664a 100644
@@ -12,6 +12,7 @@
 #include <asm/sections.h>
 #include <asm/cacheflush.h>
 #include <asm/bug.h>
+#include <asm/insn.h>
 #include <asm/text-patching.h>
 
 #include "decode-insn.h"
arch/riscv/kernel/traps.c +3 -2
index 9c83848797a7..938a8b841f94 100644
@@ -26,6 +26,7 @@
 #include <asm/bug.h>
 #include <asm/cfi.h>
 #include <asm/csr.h>
+#include <asm/insn.h>
 #include <asm/processor.h>
 #include <asm/ptrace.h>
 #include <asm/syscall.h>
@@ -409,10 +410,10 @@ int is_valid_bugaddr(unsigned long pc)
 		return 0;
 	if (get_kernel_nofault(insn, (bug_insn_t *)pc))
 		return 0;
-	if ((insn & __INSN_LENGTH_MASK) == __INSN_LENGTH_32)
+	if ((insn & __INSN_LENGTH_MASK) == __INSN_LENGTH_GE_32)
 		return (insn == __BUG_INSN_32);
 	else
-		return ((insn & __COMPRESSED_INSN_MASK) == __BUG_INSN_16);
+		return ((insn & RVC_MASK_C) == __BUG_INSN_16);
 }
 #endif /* CONFIG_GENERIC_BUG */
 
arch/riscv/kernel/traps_misaligned.c +19 -74

121 lines not on this page · raw message

Signature · 1 line
2.43.0
#2 lore raw

RFC PATCH 2/6 riscv: Add SBI debug trigger extension and function ids

In reply to Jesse Taube

From: Himanshu Chauhan <[email protected]>

Debug trigger extension is a proposed SBI extension to support native debugging in S-mode and VS-mode.

The proposal for the extension can be found at:
https://lists.riscv.org/g/sig-hypervisors/message/361

This patch adds the extension and the function IDs defined by the extension.

---
 arch/riscv/include/asm/sbi.h | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
arch/riscv/include/asm/sbi.h +29 -0
index 3d250824178b..be2ca8e8a49e 100644
@@ -35,6 +35,7 @@ enum sbi_ext_id {
 	SBI_EXT_DBCN = 0x4442434E,
 	SBI_EXT_STA = 0x535441,
 	SBI_EXT_NACL = 0x4E41434C,
+	SBI_EXT_DBTR = 0x44425452,
 
 	/* Experimentals extensions must lie within this range */
 	SBI_EXT_EXPERIMENTAL_START = 0x08000000,
@@ -402,6 +403,34 @@ enum sbi_ext_nacl_feature {
 #define SBI_NACL_SHMEM_SRET_X(__i)		((__riscv_xlen / 8) * (__i))
 #define SBI_NACL_SHMEM_SRET_X_LAST		31
 
+/* SBI debug triggers function IDs */
+enum sbi_ext_dbtr_fid {
+	SBI_EXT_DBTR_NUM_TRIGGERS = 0,
+	SBI_EXT_DBTR_SETUP_SHMEM,
+	SBI_EXT_DBTR_TRIG_READ,
+	SBI_EXT_DBTR_TRIG_INSTALL,
+	SBI_EXT_DBTR_TRIG_UPDATE,
+	SBI_EXT_DBTR_TRIG_UNINSTALL,
+	SBI_EXT_DBTR_TRIG_ENABLE,
+	SBI_EXT_DBTR_TRIG_DISABLE,
+};
+
+struct sbi_dbtr_data_msg {
+	unsigned long tstate;
+	unsigned long tdata1;
+	unsigned long tdata2;
+	unsigned long tdata3;
+};
+
+struct sbi_dbtr_id_msg {
+	unsigned long idx;
+};
+
+union sbi_dbtr_shmem_entry {
+	struct sbi_dbtr_data_msg data;
+	struct sbi_dbtr_id_msg id;
+};
+
 /* SBI spec version fields */
 #define SBI_SPEC_VERSION_DEFAULT	0x1
 #define SBI_SPEC_VERSION_MAJOR_SHIFT	24
Signature · 1 line
2.43.0
#3 lore raw

RFC PATCH 3/6 riscv: insn: __read_insn use copy_from_X_nofault

In reply to Jesse Taube

__read_insn was using get_user for user space reads and direct dereferencing for kernel space reads.
Update to use copy_from_user_nofault, copy_from_kernel_nofault for this as get_user is user context only and may sleep.

---
Squash with previous commit as it's breaks bisectability. Separated as i'm unsure if copy_from_user_nofault is an acceptable replacement.

---
 arch/riscv/kernel/insn.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
arch/riscv/kernel/insn.c +5 -3
index dd2a6ef9fd25..b8e5202ddced 100644
@@ -2,6 +2,9 @@
 /*
  * Copyright 2025 Rivos, Inc
  */
+
+#include <linux/uaccess.h>
+
 #include <asm/insn.h>
 #include <asm/ptrace.h>
 #include <asm/uaccess.h>
@@ -11,10 +14,9 @@
 	int __ret;					\
 							\
 	if (user_mode(regs)) {				\
-		__ret = get_user(insn, (type __user *) insn_addr); \
+		__ret = copy_from_user_nofault(&insn, (const type __user *) insn_addr, sizeof(type)); \
 	} else {					\
-		insn = *(type *)insn_addr;		\
-		__ret = 0;				\
+		__ret = copy_from_kernel_nofault(&insn, (const type *) insn_addr, sizeof(type)); \
 	}						\
 							\
 	__ret;						\
Signature · 1 line
2.43.0
#4 lore raw

Re: [RFC PATCH 3/6] riscv: insn: __read_insn use copy_from_X_nofault

Quoted 29 lines · Jesse Taube

__read_insn was using get_user for user space reads and direct dereferencing for kernel space reads.
Update to use copy_from_user_nofault, copy_from_kernel_nofault for this as get_user is user context only and may sleep.

---
Squash with previous commit as it's breaks bisectability. Separated as i'm unsure if copy_from_user_nofault is an acceptable replacement.

---
 arch/riscv/kernel/insn.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
arch/riscv/kernel/insn.c +3 -0
index dd2a6ef9fd25..b8e5202ddced 100644
@@ -2,6 +2,9 @@
 /*
  * Copyright 2025 Rivos, Inc
  */
+
+#include <linux/uaccess.h>
+
 #include <asm/insn.h>
 #include <asm/ptrace.h>
 #include <asm/uaccess.h>

arch/riscv/kernel/insn.c line 20

Quoted 10 lines
arch/riscv/kernel/insn.c +2 -3
@@ -11,10 +14,9 @@
 	int __ret;					\
 							\
 	if (user_mode(regs)) {				\
-		__ret = get_user(insn, (type __user *) insn_addr); \
+		__ret = copy_from_user_nofault(&insn, (const type __user *) insn_addr, sizeof(type)); \
 	} else {					\
-		insn = *(type *)insn_addr;		\
-		__ret = 0;				\
+		__ret = copy_from_kernel_nofault(&insn, (const type *) insn_addr, sizeof(type)); \
 	}						\

Hi Jesse,

This can not be used for misaligned accesses handling. As pointed out by Samuel in a previous misaligned access handling patch, using the no_fault() version would lead to access failure if the user memory is swapped out. For that reason it was swapped from the no_fault() version to the standard version.

Thanks,

Clément

Quoted 2 lines
arch/riscv/kernel/insn.c +0 -0
 							\
 	__ret;						\
#5 lore raw

RFC PATCH 4/6 riscv: Introduce support for hardware break/watchpoints

In reply to Jesse Taube

From: Himanshu Chauhan <[email protected]>

RISC-V hardware breakpoint framework is built on top of perf subsystem and uses SBI debug trigger extension to install/uninstall/update/enable/disable hardware triggers as specified in Sdtrig ISA extension.

---
 arch/riscv/Kconfig                     |   1 +
 arch/riscv/include/asm/hw_breakpoint.h |  60 +++
 arch/riscv/include/asm/kdebug.h        |   3 +-
 arch/riscv/include/asm/sbi.h           |   4 +-
 arch/riscv/kernel/Makefile             |   1 +
 arch/riscv/kernel/hw_breakpoint.c      | 620 +++++++++++++++++++++++++
 arch/riscv/kernel/traps.c              |   6 +
 7 files changed, 693 insertions(+), 2 deletions(-)
 create mode 100644 arch/riscv/include/asm/hw_breakpoint.h
 create mode 100644 arch/riscv/kernel/hw_breakpoint.c
arch/riscv/Kconfig +1 -0
index bbec87b79309..95d3047cab10 100644
@@ -163,6 +163,7 @@ config RISCV
 	select HAVE_FUNCTION_ERROR_INJECTION
 	select HAVE_GCC_PLUGINS
 	select HAVE_GENERIC_VDSO if MMU && 64BIT
+	select HAVE_HW_BREAKPOINT if PERF_EVENTS && RISCV_SBI
 	select HAVE_IRQ_TIME_ACCOUNTING
 	select HAVE_KERNEL_BZIP2 if !XIP_KERNEL && !EFI_ZBOOT
 	select HAVE_KERNEL_GZIP if !XIP_KERNEL && !EFI_ZBOOT
arch/riscv/include/asm/hw_breakpoint.h new file +60 -0

60 lines not on this page · raw message

arch/riscv/include/asm/kdebug.h +2 -1
index 85ac00411f6e..53e989781aa1 100644
@@ -6,7 +6,8 @@
 enum die_val {
 	DIE_UNUSED,
 	DIE_TRAP,
-	DIE_OOPS
+	DIE_OOPS,
+	DIE_DEBUG
 };
 
 #endif
arch/riscv/include/asm/sbi.h +3 -1
index be2ca8e8a49e..64fa7a82aa45 100644
@@ -282,7 +282,9 @@ struct sbi_sta_struct {
 	u8 pad[47];
 } __packed;
 
-#define SBI_SHMEM_DISABLE		-1
+#define SBI_SHMEM_DISABLE	(-1UL)
+#define SBI_SHMEM_LO(pa)	((unsigned long)lower_32_bits(pa))
+#define SBI_SHMEM_HI(pa)	((unsigned long)upper_32_bits(pa))
 
 enum sbi_ext_nacl_fid {
 	SBI_EXT_NACL_PROBE_FEATURE = 0x0,
arch/riscv/kernel/Makefile +1 -0
index 4f719b09e5ad..3e72505734bd 100644
@@ -99,6 +99,7 @@ obj-$(CONFIG_DYNAMIC_FTRACE)	+= mcount-dyn.o
 
 obj-$(CONFIG_PERF_EVENTS)	+= perf_callchain.o
 obj-$(CONFIG_HAVE_PERF_REGS)	+= perf_regs.o
+obj-$(CONFIG_HAVE_HW_BREAKPOINT)	+= hw_breakpoint.o
 obj-$(CONFIG_RISCV_SBI)		+= sbi.o sbi_ecall.o
 ifeq ($(CONFIG_RISCV_SBI), y)
 obj-$(CONFIG_SMP)		+= sbi-ipi.o
arch/riscv/kernel/hw_breakpoint.c new file +620 -0

620 lines not on this page · raw message

arch/riscv/kernel/traps.c +6 -0
index 938a8b841f94..2ac471ec79a8 100644
@@ -289,6 +289,12 @@ void handle_break(struct pt_regs *regs)
 	if (probe_breakpoint_handler(regs))
 		return;
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+	if (notify_die(DIE_DEBUG, "EBREAK", regs, 0, regs->cause, SIGTRAP)
+	    == NOTIFY_STOP)
+		return;
+#endif
+
 	current->thread.bad_cause = regs->cause;
 
 	if (user_mode(regs))
Signature · 1 line
2.43.0
#6 lore raw

Re: [RFC PATCH 4/6] riscv: Introduce support for hardware break/watchpoints

Quoted 346 lines · Jesse Taube

From: Himanshu Chauhan <[email protected]>

RISC-V hardware breakpoint framework is built on top of perf subsystem and uses SBI debug trigger extension to install/uninstall/update/enable/disable hardware triggers as specified in Sdtrig ISA extension.

---

arch/riscv/Kconfig                     |   1 +
arch/riscv/include/asm/hw_breakpoint.h |  60 +++
arch/riscv/include/asm/kdebug.h        |   3 +-
arch/riscv/include/asm/sbi.h           |   4 +-
arch/riscv/kernel/Makefile             |   1 +
arch/riscv/kernel/hw_breakpoint.c      | 620 +++++++++++++++++++++++++
arch/riscv/kernel/traps.c              |   6 +
7 files changed, 693 insertions(+), 2 deletions(-)

create mode 100644 arch/riscv/include/asm/hw_breakpoint.h create mode 100644 arch/riscv/kernel/hw_breakpoint.c

arch/riscv/Kconfig +1 -0
index bbec87b79309..95d3047cab10 100644
@@ -163,6 +163,7 @@ config RISCV
 	select HAVE_FUNCTION_ERROR_INJECTION
 	select HAVE_GCC_PLUGINS
 	select HAVE_GENERIC_VDSO if MMU && 64BIT
+	select HAVE_HW_BREAKPOINT if PERF_EVENTS && RISCV_SBI
 	select HAVE_IRQ_TIME_ACCOUNTING
 	select HAVE_KERNEL_BZIP2 if !XIP_KERNEL && !EFI_ZBOOT
 	select HAVE_KERNEL_GZIP if !XIP_KERNEL && !EFI_ZBOOT
arch/riscv/include/asm/hw_breakpoint.h new file +60 -0
new file mode 100644
index 000000000000..8efa3921c535
@@ -0,0 +1,60 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#ifndef __RISCV_HW_BREAKPOINT_H
+#define __RISCV_HW_BREAKPOINT_H
+
+struct task_struct;
+
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+
+#include <uapi/linux/hw_breakpoint.h>
+
+#if __riscv_xlen == 64
+#define cpu_to_le cpu_to_le64
+#define le_to_cpu le64_to_cpu
+#elif __riscv_xlen == 32
+#define cpu_to_le cpu_to_le32
+#define le_to_cpu le32_to_cpu
+#else
+#error "Unexpected __riscv_xlen"
+#endif
+
+struct arch_hw_breakpoint {
+	unsigned long address;
+	unsigned long len;
+
+	/* Callback info */
+	unsigned long next_addr;
+	bool in_callback;
+
+
+	/* Trigger configuration data */
+	unsigned long tdata1;
+	unsigned long tdata2;
+	unsigned long tdata3;
+};
+
+/* Maximum number of hardware breakpoints supported */
+#define RV_MAX_TRIGGERS 32
+
+struct perf_event_attr;
+struct notifier_block;
+struct perf_event;
+struct pt_regs;
+
+int hw_breakpoint_slots(int type);
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw);
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+			     const struct perf_event_attr *attr,
+			     struct arch_hw_breakpoint *hw);
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+				    unsigned long val, void *data);
+int arch_install_hw_breakpoint(struct perf_event *bp);
+void arch_uninstall_hw_breakpoint(struct perf_event *bp);
+void hw_breakpoint_pmu_read(struct perf_event *bp);
+
+#endif /* CONFIG_HAVE_HW_BREAKPOINT */
+#endif /* __RISCV_HW_BREAKPOINT_H */
arch/riscv/include/asm/kdebug.h +2 -1
index 85ac00411f6e..53e989781aa1 100644
@@ -6,7 +6,8 @@
 enum die_val {
 	DIE_UNUSED,
 	DIE_TRAP,
-	DIE_OOPS
+	DIE_OOPS,
+	DIE_DEBUG
 };
 
 #endif
arch/riscv/include/asm/sbi.h +3 -1
index be2ca8e8a49e..64fa7a82aa45 100644
@@ -282,7 +282,9 @@ struct sbi_sta_struct {
 	u8 pad[47];
 } __packed;
 
-#define SBI_SHMEM_DISABLE		-1
+#define SBI_SHMEM_DISABLE	(-1UL)
+#define SBI_SHMEM_LO(pa)	((unsigned long)lower_32_bits(pa))
+#define SBI_SHMEM_HI(pa)	((unsigned long)upper_32_bits(pa))
 
 enum sbi_ext_nacl_fid {
 	SBI_EXT_NACL_PROBE_FEATURE = 0x0,
arch/riscv/kernel/Makefile +0 -0
index 4f719b09e5ad..3e72505734bd 100644
@@ -99,6 +99,7 @@ obj-$(CONFIG_DYNAMIC_FTRACE)	+= mcount-dyn.o
 

obj-$(CONFIG_PERF_EVENTS) += perf_callchain.o
obj-$(CONFIG_HAVE_PERF_REGS) += perf_regs.o
+obj-$(CONFIG_HAVE_HW_BREAKPOINT) += hw_breakpoint.o
obj-$(CONFIG_RISCV_SBI) += sbi.o sbi_ecall.o
ifeq ($(CONFIG_RISCV_SBI), y)
obj-$(CONFIG_SMP) += sbi-ipi.o

arch/riscv/kernel/hw_breakpoint.c new file +201 -0
new file mode 100644
index 000000000000..9e3a3b82d300
@@ -0,0 +1,620 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#include <linux/hw_breakpoint.h>
+#include <linux/perf_event.h>
+#include <linux/spinlock.h>
+#include <linux/percpu.h>
+#include <linux/kdebug.h>
+#include <linux/bitops.h>
+#include <linux/bitfield.h>
+#include <linux/cpu.h>
+#include <linux/cpuhotplug.h>
+
+#include <asm/insn.h>
+#include <asm/sbi.h>
+
+#define DBTR_TDATA1_TYPE_SHIFT		(__riscv_xlen - 4)
+#define DBTR_TDATA1_DMODE		BIT_UL(__riscv_xlen - 5)
+
+#define DBTR_TDATA1_TYPE_MCONTROL	(2UL << DBTR_TDATA1_TYPE_SHIFT)
+#define DBTR_TDATA1_TYPE_MCONTROL6	(6UL << DBTR_TDATA1_TYPE_SHIFT)
+
+#define DBTR_TDATA1_MCONTROL6_LOAD		BIT(0)
+#define DBTR_TDATA1_MCONTROL6_STORE		BIT(1)
+#define DBTR_TDATA1_MCONTROL6_EXECUTE		BIT(2)
+#define DBTR_TDATA1_MCONTROL6_U			BIT(3)
+#define DBTR_TDATA1_MCONTROL6_S			BIT(4)
+#define DBTR_TDATA1_MCONTROL6_M			BIT(6)
+#define DBTR_TDATA1_MCONTROL6_SIZE_FIELD	GENMASK(18, 16)
+#define DBTR_TDATA1_MCONTROL6_SELECT		BIT(21)
+#define DBTR_TDATA1_MCONTROL6_VU		BIT(23)
+#define DBTR_TDATA1_MCONTROL6_VS		BIT(24)
+
+#define DBTR_TDATA1_MCONTROL6_SIZE_8BIT		1
+#define DBTR_TDATA1_MCONTROL6_SIZE_16BIT	2
+#define DBTR_TDATA1_MCONTROL6_SIZE_32BIT	3
+#define DBTR_TDATA1_MCONTROL6_SIZE_64BIT	5
+
+#define DBTR_TDATA1_MCONTROL_LOAD		BIT(0)
+#define DBTR_TDATA1_MCONTROL_STORE		BIT(1)
+#define DBTR_TDATA1_MCONTROL_EXECUTE		BIT(2)
+#define DBTR_TDATA1_MCONTROL_U			BIT(3)
+#define DBTR_TDATA1_MCONTROL_S			BIT(4)
+#define DBTR_TDATA1_MCONTROL_M			BIT(6)
+#define DBTR_TDATA1_MCONTROL_SIZELO_FIELD	GENMASK(17, 16)
+#define DBTR_TDATA1_MCONTROL_SELECT		BIT(19)
+#define DBTR_TDATA1_MCONTROL_SIZEHI_FIELD	GENMASK(22, 21)
+
+#define DBTR_TDATA1_MCONTROL_SIZELO_8BIT	1
+#define DBTR_TDATA1_MCONTROL_SIZELO_16BIT	2
+#define DBTR_TDATA1_MCONTROL_SIZELO_32BIT	3
+/* value of 5 split across HI and LO */
+#define DBTR_TDATA1_MCONTROL_SIZELO_64BIT	1
+#define DBTR_TDATA1_MCONTROL_SIZEHI_64BIT	1
+
+/* Registered per-cpu bp/wp */
+static DEFINE_PER_CPU(struct perf_event *, pcpu_hw_bp_events[RV_MAX_TRIGGERS]);
+static DEFINE_PER_CPU(unsigned long, ecall_lock_flags);
+static DEFINE_PER_CPU(raw_spinlock_t, ecall_lock);
+
+/* Per-cpu shared memory between S and M mode */
+static DEFINE_PER_CPU(union sbi_dbtr_shmem_entry, sbi_dbtr_shmem);
+
+/* number of debug triggers on this cpu . */
+static int dbtr_total_num __ro_after_init;
+static unsigned long dbtr_type __ro_after_init;
+static unsigned long dbtr_init __ro_after_init;
+
+static int arch_smp_setup_sbi_shmem(unsigned int cpu)
+{
+	union sbi_dbtr_shmem_entry *dbtr_shmem;
+	unsigned long shmem_pa;
+	struct sbiret ret;
+	int rc;
+
+	dbtr_shmem = per_cpu_ptr(&sbi_dbtr_shmem, cpu);
+	if (!dbtr_shmem) {
+		pr_err("Invalid per-cpu shared memory for debug triggers\n");
+		return -ENODEV;
+	}
+
+	shmem_pa = virt_to_phys(dbtr_shmem);
+
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+			SBI_SHMEM_LO(shmem_pa), SBI_SHMEM_HI(shmem_pa), 0, 0, 0, 0);
+
+	if (ret.error) {
+		switch (ret.error) {
+		case SBI_ERR_DENIED:
+			pr_warn("%s: Access denied for shared memory at %lx\n",
+				__func__, shmem_pa);
+			rc = -EPERM;
+			break;
+
+		case SBI_ERR_INVALID_PARAM:
+		case SBI_ERR_INVALID_ADDRESS:
+			pr_warn("%s: Invalid address parameter (%ld)\n",
+				__func__, ret.error);
+			rc = -EINVAL;
+			break;
+
+		case SBI_ERR_ALREADY_AVAILABLE:
+			pr_warn("%s: Shared memory is already set\n",
+				__func__);
+			rc = -EADDRINUSE;
+			break;
+
+		case SBI_ERR_FAILURE:
+			pr_err("%s: Internal sdtrig state error\n",
+			       __func__);
+			rc = -ENXIO;
+			break;
+
+		default:
+			pr_warn("%s: Unknown error %lu\n", __func__, ret.error);
+			rc = -ENXIO;
+			break;
+		}
+	}
+
+	pr_debug("CPU %d: HW Breakpoint shared memory registered.\n", cpu);
+
+	return rc;
+}
+
+static int arch_smp_teardown_sbi_shmem(unsigned int cpu)
+{
+	struct sbiret ret;
+
+	/* Disable shared memory */
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+			SBI_SHMEM_DISABLE, SBI_SHMEM_DISABLE, 0, 0, 0, 0);
+
+	if (ret.error) {
+		switch (ret.error) {
+		case SBI_ERR_DENIED:
+			pr_err("%s: Access denied for shared memory.\n",
+			       __func__);
+			break;
+
+		case SBI_ERR_INVALID_PARAM:
+		case SBI_ERR_INVALID_ADDRESS:
+			pr_err("%s: Invalid address parameter (%lu)\n",
+			       __func__, ret.error);
+			break;
+
+		case SBI_ERR_ALREADY_AVAILABLE:
+			pr_err("%s: Shared memory is already set\n",
+			       __func__);
+			break;
+		case SBI_ERR_FAILURE:
+			pr_err("%s: Internal sdtrig state error\n",
+			       __func__);
+			break;
+		default:
+			pr_err("%s: Unknown error %lu\n", __func__, ret.error);
+			break;
+		}
+	}
+
+	pr_debug("CPU %d: HW Breakpoint shared memory disabled.\n", cpu);
+
+	return 0;
+}
+
+static void init_sbi_dbtr(void)
+{
+	struct sbiret ret;
+
+	/*
+	 * Called by hw_breakpoint_slots and arch_hw_breakpoint_init.
+	 * Only proceed if this is the first CPU to reach this code.
+	 */
+	if (test_and_set_bit(0, &dbtr_init))
+		return;
+
+	if (sbi_probe_extension(SBI_EXT_DBTR) <= 0) {
+		pr_debug("%s: SBI_EXT_DBTR is not supported\n", __func__);
+		dbtr_total_num = 0;
+		return;
+	}
+
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+			DBTR_TDATA1_TYPE_MCONTROL6, 0, 0, 0, 0, 0);
+	if (ret.error) {
+		pr_warn("%s: failed to detect mcontrol6 triggers. error: %ld.\n",
+			__func__, ret.error);
+	} else if (!ret.value) {
+		pr_warn("%s: No mcontrol6 triggers available.\n", __func__);
+	} else {
+		dbtr_total_num = ret.value;
+		dbtr_type = DBTR_TDATA1_TYPE_MCONTROL6;
+		return;
+	}
+
+	/* fallback to legacy mcontrol triggers if mcontrol6 is not available */
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+			DBTR_TDATA1_TYPE_MCONTROL, 0, 0, 0, 0, 0);
+	if (ret.error) {

arch/riscv/kernel/hw_breakpoint.c line 211

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+		pr_warn("%s: failed to detect mcontrol triggers. error: %ld.\n",
+			__func__, ret.error);
+	} else if (!ret.value) {
+		pr_err("%s: No mcontrol triggers available.\n", __func__);
+		dbtr_total_num = 0;
+	} else {
+		dbtr_total_num = ret.value;
+		dbtr_type = DBTR_TDATA1_TYPE_MCONTROL;
+	}
+}

dbtr_total_num is static and thus would be initialized to zero. Although above code is setting it to zero in some error conditions. And not setting to zero in other error conditions.

It'll be better if function starts out setting dbtr_total_num as setting to 0. Then set correct value in success conditions.

Quoted 65 lines
arch/riscv/kernel/hw_breakpoint.c new file +65 -0
+
+int hw_breakpoint_slots(int type)
+{
+	/*
+	 * We can be called early, so don't rely on
+	 * static variables being initialised.
+	 */
+	init_sbi_dbtr();
+
+	return dbtr_total_num;
+}
+
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw)
+{
+	unsigned int len;
+	unsigned long va;
+
+	va = hw->address;
+	len = hw->len;
+
+	return (va >= TASK_SIZE) && ((va + len - 1) >= TASK_SIZE);
+}
+
+static int rv_init_mcontrol_trigger(const struct perf_event_attr *attr,
+				    struct arch_hw_breakpoint *hw)
+{
+	unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+	switch (attr->bp_type) {
+	case HW_BREAKPOINT_X:
+		tdata1 |= DBTR_TDATA1_MCONTROL_EXECUTE;
+		break;
+	case HW_BREAKPOINT_R:
+		tdata1 |= DBTR_TDATA1_MCONTROL_LOAD;
+		break;
+	case HW_BREAKPOINT_W:
+		tdata1 |= DBTR_TDATA1_MCONTROL_STORE;
+		break;
+	case HW_BREAKPOINT_RW:
+		tdata1 |= DBTR_TDATA1_MCONTROL_STORE | DBTR_TDATA1_MCONTROL_LOAD;
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	switch (attr->bp_len) {
+	case HW_BREAKPOINT_LEN_1:
+		hw->len = 1;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+				     DBTR_TDATA1_MCONTROL_SIZELO_8BIT);
+		break;
+	case HW_BREAKPOINT_LEN_2:
+		hw->len = 2;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+				     DBTR_TDATA1_MCONTROL_SIZELO_16BIT);
+		break;
+	case HW_BREAKPOINT_LEN_4:
+		hw->len = 4;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+				     DBTR_TDATA1_MCONTROL_SIZELO_32BIT);
+		break;
+#if __riscv_xlen >= 64
+	case HW_BREAKPOINT_LEN_8:
+		hw->len = 8;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,

arch/riscv/kernel/hw_breakpoint.c line 286

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+				     DBTR_TDATA1_MCONTROL_SIZELO_64BIT) |
+			  FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZEHI_FIELD,
+				     DBTR_TDATA1_MCONTROL_SIZEHI_64BIT);
+		break;
+#endif
+	default:
+		return -EINVAL;
+	}
+
+	tdata1 |= DBTR_TDATA1_MCONTROL_U;

Assuming this function could be re-used for kernel data breakpoints too Shouldn't this be based on some flag to select U v/s S.
Same comment for setting up tdata1 with mcontrol6.

Quoted 354 lines
arch/riscv/kernel/hw_breakpoint.c new file +334 -0
+
+	hw->tdata1 = tdata1;
+
+	return 0;
+}
+
+static int rv_init_mcontrol6_trigger(const struct perf_event_attr *attr,
+				     struct arch_hw_breakpoint *hw)
+{
+	unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+	switch (attr->bp_type) {
+	case HW_BREAKPOINT_X:
+		tdata1 |= DBTR_TDATA1_MCONTROL6_EXECUTE;
+		break;
+	case HW_BREAKPOINT_R:
+		tdata1 |= DBTR_TDATA1_MCONTROL6_LOAD;
+		break;
+	case HW_BREAKPOINT_W:
+		tdata1 |= DBTR_TDATA1_MCONTROL6_STORE;
+		break;
+	case HW_BREAKPOINT_RW:
+		tdata1 |= DBTR_TDATA1_MCONTROL6_STORE | DBTR_TDATA1_MCONTROL6_LOAD;
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	switch (attr->bp_len) {
+	case HW_BREAKPOINT_LEN_1:
+		hw->len = 1;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+				     DBTR_TDATA1_MCONTROL6_SIZE_8BIT);
+		break;
+	case HW_BREAKPOINT_LEN_2:
+		hw->len = 2;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+				     DBTR_TDATA1_MCONTROL6_SIZE_16BIT);
+		break;
+	case HW_BREAKPOINT_LEN_4:
+		hw->len = 4;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+				     DBTR_TDATA1_MCONTROL6_SIZE_32BIT);
+		break;
+	case HW_BREAKPOINT_LEN_8:
+		hw->len = 8;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+				     DBTR_TDATA1_MCONTROL6_SIZE_64BIT);
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	tdata1 |= DBTR_TDATA1_MCONTROL6_U;
+
+	hw->tdata1 = tdata1;
+
+	return 0;
+}
+
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+			     const struct perf_event_attr *attr,
+			     struct arch_hw_breakpoint *hw)
+{
+	int ret;
+
+	/* Breakpoint address */
+	hw->address = attr->bp_addr;
+	hw->tdata2 = attr->bp_addr;
+	hw->tdata3 = 0x0;
+	hw->next_addr = 0x0;
+	hw->in_callback = false;
+
+	switch (dbtr_type) {
+	case DBTR_TDATA1_TYPE_MCONTROL:
+		ret = rv_init_mcontrol_trigger(attr, hw);
+		break;
+	case DBTR_TDATA1_TYPE_MCONTROL6:
+		ret = rv_init_mcontrol6_trigger(attr, hw);
+		break;
+	default:
+		pr_warn("Unsupported trigger type %lu.\n", dbtr_type >> DBTR_TDATA1_TYPE_SHIFT);
+		ret = -EOPNOTSUPP;
+		break;
+	}
+
+	return ret;
+}
+
+/*
+ * Set breakpoint to next insruction after breakpoint.
+ * Returns 0 if success
+ * Returns < 0 on error
+ */
+static int setup_singlestep(struct perf_event *event, struct pt_regs *regs)
+{
+	struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+	struct arch_hw_breakpoint old_hw_bp;
+	struct perf_event_attr bp_insn;
+	unsigned long next_addr, insn;
+	int ret;
+
+	/* Remove breakpoint even if return error as not to loop */
+	arch_uninstall_hw_breakpoint(event);
+
+	ret = get_insn(regs, regs->epc, &insn);
+	if (ret < 0)
+		return ret;
+
+	next_addr = get_step_address(regs, insn);
+
+	ret = get_insn(regs, next_addr, &insn);
+	if (ret < 0)
+		return ret;
+
+	bp_insn.bp_type = HW_BREAKPOINT_X;
+	bp_insn.bp_addr = next_addr;
+	/* Get the size of the intruction */
+	bp_insn.bp_len = GET_INSN_LENGTH(insn);
+
+	ret = hw_breakpoint_arch_parse(NULL, &bp_insn, bp);
+	if (ret)
+		return ret;
+
+	ret = arch_install_hw_breakpoint(event);
+	if (ret)
+		return ret;
+
+	bp->in_callback = true;
+	bp->next_addr = next_addr;
+	return 0;
+}
+
+/*
+ * HW Breakpoint/watchpoint handler
+ */
+static int hw_breakpoint_handler(struct pt_regs *regs)
+{
+	struct perf_event *event;
+	struct arch_hw_breakpoint *bp;
+	int ret, i;
+
+	for (i = 0; i < dbtr_total_num; i++) {
+		event = this_cpu_read(pcpu_hw_bp_events[i]);
+		if (!event)
+			continue;
+
+		bp = counter_arch_bp(event);
+		if (bp->in_callback) {
+			/* Reset changed breakpoint data */
+			bp->in_callback = false;
+			if (regs->epc == bp->next_addr) {
+				arch_uninstall_hw_breakpoint(event);
+				/* Restore original breakpoint */
+				if (hw_breakpoint_arch_parse(NULL, &event->attr, bp))
+					return NOTIFY_DONE;
+				if (arch_install_hw_breakpoint(event))
+					return NOTIFY_DONE;
+				return NOTIFY_STOP;
+			}
+
+			pr_err("%s: in_callback was set, but epc(%lx) was not next "
+				 "address(%lx).\n", __func__, regs->epc, bp->next_addr);
+			bp->next_addr = 0x0;
+			return NOTIFY_DONE;
+		}
+
+		switch (event->attr.bp_type) {
+		/* Breakpoint */
+		case HW_BREAKPOINT_X:
+			if (event->attr.bp_addr == regs->epc) {
+				ret = setup_singlestep(event, regs);
+				if (ret < 0) {
+					pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+					return NOTIFY_DONE;
+				}
+
+				perf_bp_event(event, regs);
+				return NOTIFY_STOP;
+			}
+			break;
+
+		/* Watchpoint */
+		case HW_BREAKPOINT_W:
+		case HW_BREAKPOINT_R:
+		case HW_BREAKPOINT_RW:
+			if (event->attr.bp_addr == regs->badaddr) {
+				ret = setup_singlestep(event, regs);
+				if (ret < 0) {
+					pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+					return NOTIFY_DONE;
+				}
+
+				perf_bp_event(event, regs);
+				return NOTIFY_STOP;
+			}
+			break;
+
+		default:
+			pr_warn("%s: Unknown type: %u\n", __func__, event->attr.bp_type);
+			break;
+		}
+	}
+
+	return NOTIFY_DONE;
+}
+
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+				    unsigned long val, void *data)
+{
+	struct die_args *args = data;
+
+	if (val != DIE_DEBUG)
+		return NOTIFY_DONE;
+
+	return hw_breakpoint_handler(args->regs);
+}
+
+/* atomic: counter->ctx->lock is held */
+int arch_install_hw_breakpoint(struct perf_event *event)
+{
+	struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+	union sbi_dbtr_shmem_entry *shmem = this_cpu_ptr(&sbi_dbtr_shmem);
+	struct sbi_dbtr_data_msg *xmit;
+	struct sbi_dbtr_id_msg *recv;
+	struct perf_event **slot;
+	unsigned long idx;
+	struct sbiret ret;
+	int err = 0;
+
+	raw_spin_lock_irqsave(this_cpu_ptr(&ecall_lock),
+			      *this_cpu_ptr(&ecall_lock_flags));
+
+	xmit = &shmem->data;
+	recv = &shmem->id;
+	xmit->tdata1 = cpu_to_le(bp->tdata1);
+	xmit->tdata2 = cpu_to_le(bp->tdata2);
+	xmit->tdata3 = cpu_to_le(bp->tdata3);
+
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_INSTALL,
+			1, 0, 0, 0, 0, 0);
+
+	if (ret.error) {
+		pr_warn("%s: failed to install trigger. error: %ld\n", __func__, ret.error);
+		err = sbi_err_map_linux_errno(ret.error);
+		goto done;
+	}
+
+	idx = le_to_cpu(recv->idx);
+	if (idx >= dbtr_total_num) {
+		pr_warn("%s: invalid trigger index %lu\n", __func__, idx);
+		err = -EINVAL;
+		goto done;
+	}
+
+	slot = this_cpu_ptr(&pcpu_hw_bp_events[idx]);
+	if (*slot) {
+		pr_warn("%s: slot %lu is in use\n", __func__, idx);
+		err = -EBUSY;
+		goto done;
+	}
+
+	pr_debug("Trigger 0x%lx installed at index 0x%lx\n", bp->tdata2, idx);
+
+	/* Save the event - to be looked up in handler */
+	*slot = event;
+
+done:
+	raw_spin_unlock_irqrestore(this_cpu_ptr(&ecall_lock),
+				   *this_cpu_ptr(&ecall_lock_flags));
+	return err;
+}
+
+/* atomic: counter->ctx->lock is held */
+void arch_uninstall_hw_breakpoint(struct perf_event *event)
+{
+	struct sbiret ret;
+	int i;
+
+	for (i = 0; i < dbtr_total_num; i++) {
+		struct perf_event **slot = this_cpu_ptr(&pcpu_hw_bp_events[i]);
+
+		if (*slot == event) {
+			*slot = NULL;
+			break;
+		}
+	}
+
+
+	if (i == dbtr_total_num) {
+		pr_warn("%s: Breakpoint not installed.\n", __func__);
+		return;
+	}
+
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_UNINSTALL,
+			i, 1, 0, 0, 0, 0);
+	if (ret.error)
+		pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
+}
+
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }
+
+void hw_breakpoint_pmu_read(struct perf_event *bp) { }
+
+static int __init arch_hw_breakpoint_init(void)
+{
+	unsigned int cpu;
+	int rc = 0;
+
+	for_each_possible_cpu(cpu)
+		raw_spin_lock_init(&per_cpu(ecall_lock, cpu));
+
+	init_sbi_dbtr();
+
+	if (dbtr_total_num) {
+		pr_debug("%s: total number of type %lu triggers: %u\n",
+			__func__, dbtr_type >> DBTR_TDATA1_TYPE_SHIFT, dbtr_total_num);
+	} else {
+		pr_debug("%s: No hardware triggers available\n", __func__);
+		return rc;
+	}
+
+	/* Hotplug handler to register/unregister shared memory with SBI */
+	rc = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN,
+			       "riscv/hw_breakpoint:prepare",
+			       arch_smp_setup_sbi_shmem,
+			       arch_smp_teardown_sbi_shmem);
+
+	if (rc < 0)
+		pr_warn("%s: Failed to setup CPU hotplug state\n", __func__);
+
+	return rc;
+}
+arch_initcall(arch_hw_breakpoint_init);
arch/riscv/kernel/traps.c +6 -0
index 938a8b841f94..2ac471ec79a8 100644
@@ -289,6 +289,12 @@ void handle_break(struct pt_regs *regs)
 	if (probe_breakpoint_handler(regs))
 		return;
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+	if (notify_die(DIE_DEBUG, "EBREAK", regs, 0, regs->cause, SIGTRAP)
+	    == NOTIFY_STOP)
+		return;
+#endif
+
 	current->thread.bad_cause = regs->cause;
 
 	if (user_mode(regs))
Signature · 1 line
2.43.0
#7 lore raw

Re: [RFC PATCH 4/6] riscv: Introduce support for hardware break/watchpoints

Quoted 363 lines · Deepak Gupta
Quoted 346 lines · Jesse Taube

From: Himanshu Chauhan <[email protected]>

RISC-V hardware breakpoint framework is built on top of perf subsystem and uses SBI debug trigger extension to install/uninstall/update/enable/disable hardware triggers as specified in Sdtrig ISA extension.

---

arch/riscv/Kconfig                     |   1 +
arch/riscv/include/asm/hw_breakpoint.h |  60 +++
arch/riscv/include/asm/kdebug.h        |   3 +-
arch/riscv/include/asm/sbi.h           |   4 +-
arch/riscv/kernel/Makefile             |   1 +
arch/riscv/kernel/hw_breakpoint.c      | 620 +++++++++++++++++++++++++
arch/riscv/kernel/traps.c              |   6 +
7 files changed, 693 insertions(+), 2 deletions(-)

create mode 100644 arch/riscv/include/asm/hw_breakpoint.h create mode 100644 arch/riscv/kernel/hw_breakpoint.c

arch/riscv/Kconfig +1 -0
index bbec87b79309..95d3047cab10 100644
@@ -163,6 +163,7 @@ config RISCV
      select HAVE_FUNCTION_ERROR_INJECTION
      select HAVE_GCC_PLUGINS
      select HAVE_GENERIC_VDSO if MMU && 64BIT
+      select HAVE_HW_BREAKPOINT if PERF_EVENTS && RISCV_SBI
      select HAVE_IRQ_TIME_ACCOUNTING
      select HAVE_KERNEL_BZIP2 if !XIP_KERNEL && !EFI_ZBOOT
      select HAVE_KERNEL_GZIP if !XIP_KERNEL && !EFI_ZBOOT
arch/riscv/include/asm/hw_breakpoint.h new file +60 -0
new file mode 100644
index 000000000000..8efa3921c535
@@ -0,0 +1,60 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#ifndef __RISCV_HW_BREAKPOINT_H
+#define __RISCV_HW_BREAKPOINT_H
+
+struct task_struct;
+
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+
+#include <uapi/linux/hw_breakpoint.h>
+
+#if __riscv_xlen == 64
+#define cpu_to_le cpu_to_le64
+#define le_to_cpu le64_to_cpu
+#elif __riscv_xlen == 32
+#define cpu_to_le cpu_to_le32
+#define le_to_cpu le32_to_cpu
+#else
+#error "Unexpected __riscv_xlen"
+#endif
+
+struct arch_hw_breakpoint {
+      unsigned long address;
+      unsigned long len;
+
+      /* Callback info */
+      unsigned long next_addr;
+      bool in_callback;
+
+
+      /* Trigger configuration data */
+      unsigned long tdata1;
+      unsigned long tdata2;
+      unsigned long tdata3;
+};
+
+/* Maximum number of hardware breakpoints supported */
+#define RV_MAX_TRIGGERS 32
+
+struct perf_event_attr;
+struct notifier_block;
+struct perf_event;
+struct pt_regs;
+
+int hw_breakpoint_slots(int type);
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw);
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+                           const struct perf_event_attr *attr,
+                           struct arch_hw_breakpoint *hw);
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+                                  unsigned long val, void *data);
+int arch_install_hw_breakpoint(struct perf_event *bp);
+void arch_uninstall_hw_breakpoint(struct perf_event *bp);
+void hw_breakpoint_pmu_read(struct perf_event *bp);
+
+#endif /* CONFIG_HAVE_HW_BREAKPOINT */
+#endif /* __RISCV_HW_BREAKPOINT_H */
arch/riscv/include/asm/kdebug.h +2 -1
index 85ac00411f6e..53e989781aa1 100644
@@ -6,7 +6,8 @@
 enum die_val {
      DIE_UNUSED,
      DIE_TRAP,
-      DIE_OOPS
+      DIE_OOPS,
+      DIE_DEBUG
 };
 
 #endif
arch/riscv/include/asm/sbi.h +3 -1
index be2ca8e8a49e..64fa7a82aa45 100644
@@ -282,7 +282,9 @@ struct sbi_sta_struct {
      u8 pad[47];
 } __packed;
 
-#define SBI_SHMEM_DISABLE             -1
+#define SBI_SHMEM_DISABLE     (-1UL)
+#define SBI_SHMEM_LO(pa)      ((unsigned long)lower_32_bits(pa))
+#define SBI_SHMEM_HI(pa)      ((unsigned long)upper_32_bits(pa))
 
 enum sbi_ext_nacl_fid {
      SBI_EXT_NACL_PROBE_FEATURE = 0x0,
arch/riscv/kernel/Makefile +0 -0
index 4f719b09e5ad..3e72505734bd 100644
@@ -99,6 +99,7 @@ obj-$(CONFIG_DYNAMIC_FTRACE) += mcount-dyn.o
 

obj-$(CONFIG_PERF_EVENTS) += perf_callchain.o
obj-$(CONFIG_HAVE_PERF_REGS) += perf_regs.o
+obj-$(CONFIG_HAVE_HW_BREAKPOINT) += hw_breakpoint.o
obj-$(CONFIG_RISCV_SBI) += sbi.o sbi_ecall.o
ifeq ($(CONFIG_RISCV_SBI), y)
obj-$(CONFIG_SMP) += sbi-ipi.o

arch/riscv/kernel/hw_breakpoint.c new file +201 -0
new file mode 100644
index 000000000000..9e3a3b82d300
@@ -0,0 +1,620 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#include <linux/hw_breakpoint.h>
+#include <linux/perf_event.h>
+#include <linux/spinlock.h>
+#include <linux/percpu.h>
+#include <linux/kdebug.h>
+#include <linux/bitops.h>
+#include <linux/bitfield.h>
+#include <linux/cpu.h>
+#include <linux/cpuhotplug.h>
+
+#include <asm/insn.h>
+#include <asm/sbi.h>
+
+#define DBTR_TDATA1_TYPE_SHIFT                (__riscv_xlen - 4)
+#define DBTR_TDATA1_DMODE             BIT_UL(__riscv_xlen - 5)
+
+#define DBTR_TDATA1_TYPE_MCONTROL     (2UL << DBTR_TDATA1_TYPE_SHIFT)
+#define DBTR_TDATA1_TYPE_MCONTROL6    (6UL << DBTR_TDATA1_TYPE_SHIFT)
+
+#define DBTR_TDATA1_MCONTROL6_LOAD            BIT(0)
+#define DBTR_TDATA1_MCONTROL6_STORE           BIT(1)
+#define DBTR_TDATA1_MCONTROL6_EXECUTE         BIT(2)
+#define DBTR_TDATA1_MCONTROL6_U                       BIT(3)
+#define DBTR_TDATA1_MCONTROL6_S                       BIT(4)
+#define DBTR_TDATA1_MCONTROL6_M                       BIT(6)
+#define DBTR_TDATA1_MCONTROL6_SIZE_FIELD      GENMASK(18, 16)
+#define DBTR_TDATA1_MCONTROL6_SELECT          BIT(21)
+#define DBTR_TDATA1_MCONTROL6_VU              BIT(23)
+#define DBTR_TDATA1_MCONTROL6_VS              BIT(24)
+
+#define DBTR_TDATA1_MCONTROL6_SIZE_8BIT               1
+#define DBTR_TDATA1_MCONTROL6_SIZE_16BIT      2
+#define DBTR_TDATA1_MCONTROL6_SIZE_32BIT      3
+#define DBTR_TDATA1_MCONTROL6_SIZE_64BIT      5
+
+#define DBTR_TDATA1_MCONTROL_LOAD             BIT(0)
+#define DBTR_TDATA1_MCONTROL_STORE            BIT(1)
+#define DBTR_TDATA1_MCONTROL_EXECUTE          BIT(2)
+#define DBTR_TDATA1_MCONTROL_U                        BIT(3)
+#define DBTR_TDATA1_MCONTROL_S                        BIT(4)
+#define DBTR_TDATA1_MCONTROL_M                        BIT(6)
+#define DBTR_TDATA1_MCONTROL_SIZELO_FIELD     GENMASK(17, 16)
+#define DBTR_TDATA1_MCONTROL_SELECT           BIT(19)
+#define DBTR_TDATA1_MCONTROL_SIZEHI_FIELD     GENMASK(22, 21)
+
+#define DBTR_TDATA1_MCONTROL_SIZELO_8BIT      1
+#define DBTR_TDATA1_MCONTROL_SIZELO_16BIT     2
+#define DBTR_TDATA1_MCONTROL_SIZELO_32BIT     3
+/* value of 5 split across HI and LO */
+#define DBTR_TDATA1_MCONTROL_SIZELO_64BIT     1
+#define DBTR_TDATA1_MCONTROL_SIZEHI_64BIT     1
+
+/* Registered per-cpu bp/wp */
+static DEFINE_PER_CPU(struct perf_event *, pcpu_hw_bp_events[RV_MAX_TRIGGERS]);
+static DEFINE_PER_CPU(unsigned long, ecall_lock_flags);
+static DEFINE_PER_CPU(raw_spinlock_t, ecall_lock);
+
+/* Per-cpu shared memory between S and M mode */
+static DEFINE_PER_CPU(union sbi_dbtr_shmem_entry, sbi_dbtr_shmem);
+
+/* number of debug triggers on this cpu . */
+static int dbtr_total_num __ro_after_init;
+static unsigned long dbtr_type __ro_after_init;
+static unsigned long dbtr_init __ro_after_init;
+
+static int arch_smp_setup_sbi_shmem(unsigned int cpu)
+{
+      union sbi_dbtr_shmem_entry *dbtr_shmem;
+      unsigned long shmem_pa;
+      struct sbiret ret;
+      int rc;
+
+      dbtr_shmem = per_cpu_ptr(&sbi_dbtr_shmem, cpu);
+      if (!dbtr_shmem) {
+              pr_err("Invalid per-cpu shared memory for debug triggers\n");
+              return -ENODEV;
+      }
+
+      shmem_pa = virt_to_phys(dbtr_shmem);
+
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+                      SBI_SHMEM_LO(shmem_pa), SBI_SHMEM_HI(shmem_pa), 0, 0, 0, 0);
+
+      if (ret.error) {
+              switch (ret.error) {
+              case SBI_ERR_DENIED:
+                      pr_warn("%s: Access denied for shared memory at %lx\n",
+                              __func__, shmem_pa);
+                      rc = -EPERM;
+                      break;
+
+              case SBI_ERR_INVALID_PARAM:
+              case SBI_ERR_INVALID_ADDRESS:
+                      pr_warn("%s: Invalid address parameter (%ld)\n",
+                              __func__, ret.error);
+                      rc = -EINVAL;
+                      break;
+
+              case SBI_ERR_ALREADY_AVAILABLE:
+                      pr_warn("%s: Shared memory is already set\n",
+                              __func__);
+                      rc = -EADDRINUSE;
+                      break;
+
+              case SBI_ERR_FAILURE:
+                      pr_err("%s: Internal sdtrig state error\n",
+                             __func__);
+                      rc = -ENXIO;
+                      break;
+
+              default:
+                      pr_warn("%s: Unknown error %lu\n", __func__, ret.error);
+                      rc = -ENXIO;
+                      break;
+              }
+      }
+
+      pr_debug("CPU %d: HW Breakpoint shared memory registered.\n", cpu);
+
+      return rc;
+}
+
+static int arch_smp_teardown_sbi_shmem(unsigned int cpu)
+{
+      struct sbiret ret;
+
+      /* Disable shared memory */
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+                      SBI_SHMEM_DISABLE, SBI_SHMEM_DISABLE, 0, 0, 0, 0);
+
+      if (ret.error) {
+              switch (ret.error) {
+              case SBI_ERR_DENIED:
+                      pr_err("%s: Access denied for shared memory.\n",
+                             __func__);
+                      break;
+
+              case SBI_ERR_INVALID_PARAM:
+              case SBI_ERR_INVALID_ADDRESS:
+                      pr_err("%s: Invalid address parameter (%lu)\n",
+                             __func__, ret.error);
+                      break;
+
+              case SBI_ERR_ALREADY_AVAILABLE:
+                      pr_err("%s: Shared memory is already set\n",
+                             __func__);
+                      break;
+              case SBI_ERR_FAILURE:
+                      pr_err("%s: Internal sdtrig state error\n",
+                             __func__);
+                      break;
+              default:
+                      pr_err("%s: Unknown error %lu\n", __func__, ret.error);
+                      break;
+              }
+      }
+
+      pr_debug("CPU %d: HW Breakpoint shared memory disabled.\n", cpu);
+
+      return 0;
+}
+
+static void init_sbi_dbtr(void)
+{
+      struct sbiret ret;
+
+      /*
+       * Called by hw_breakpoint_slots and arch_hw_breakpoint_init.
+       * Only proceed if this is the first CPU to reach this code.
+       */
+      if (test_and_set_bit(0, &dbtr_init))
+              return;
+
+      if (sbi_probe_extension(SBI_EXT_DBTR) <= 0) {
+              pr_debug("%s: SBI_EXT_DBTR is not supported\n", __func__);
+              dbtr_total_num = 0;
+              return;
+      }
+
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+                      DBTR_TDATA1_TYPE_MCONTROL6, 0, 0, 0, 0, 0);
+      if (ret.error) {
+              pr_warn("%s: failed to detect mcontrol6 triggers. error: %ld.\n",
+                      __func__, ret.error);
+      } else if (!ret.value) {
+              pr_warn("%s: No mcontrol6 triggers available.\n", __func__);
+      } else {
+              dbtr_total_num = ret.value;
+              dbtr_type = DBTR_TDATA1_TYPE_MCONTROL6;
+              return;
+      }
+
+      /* fallback to legacy mcontrol triggers if mcontrol6 is not available */
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+                      DBTR_TDATA1_TYPE_MCONTROL, 0, 0, 0, 0, 0);
+      if (ret.error) {

arch/riscv/kernel/hw_breakpoint.c line 211

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+              pr_warn("%s: failed to detect mcontrol triggers. error: %ld.\n",
+                      __func__, ret.error);
+      } else if (!ret.value) {
+              pr_err("%s: No mcontrol triggers available.\n", __func__);
+              dbtr_total_num = 0;
+      } else {
+              dbtr_total_num = ret.value;
+              dbtr_type = DBTR_TDATA1_TYPE_MCONTROL;
+      }
+}

dbtr_total_num is static and thus would be initialized to zero. Although above code is setting it to zero in some error conditions. And not setting to zero in other error conditions.

Quoted 2 lines

It'll be better if function starts out setting dbtr_total_num as setting to 0. Then set correct value in success conditions.

I would do that, but dbtr_total_num is marked as __ro_after_init and I don't want to
write to it twice, and i wanted to explicitly set it to zero as that means breakpoints are disabled.
I can just remove the assignments to zero though.

Quoted 72 lines
Quoted 72 lines
arch/riscv/kernel/hw_breakpoint.c new file +71 -0
+
+int hw_breakpoint_slots(int type)
+{
+      /*
+       * We can be called early, so don't rely on
+       * static variables being initialised.
+       */
+      init_sbi_dbtr();
+
+      return dbtr_total_num;
+}
+
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw)
+{
+      unsigned int len;
+      unsigned long va;
+
+      va = hw->address;
+      len = hw->len;
+
+      return (va >= TASK_SIZE) && ((va + len - 1) >= TASK_SIZE);
+}
+
+static int rv_init_mcontrol_trigger(const struct perf_event_attr *attr,
+                                  struct arch_hw_breakpoint *hw)
+{
+      unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+      switch (attr->bp_type) {
+      case HW_BREAKPOINT_X:
+              tdata1 |= DBTR_TDATA1_MCONTROL_EXECUTE;
+              break;
+      case HW_BREAKPOINT_R:
+              tdata1 |= DBTR_TDATA1_MCONTROL_LOAD;
+              break;
+      case HW_BREAKPOINT_W:
+              tdata1 |= DBTR_TDATA1_MCONTROL_STORE;
+              break;
+      case HW_BREAKPOINT_RW:
+              tdata1 |= DBTR_TDATA1_MCONTROL_STORE | DBTR_TDATA1_MCONTROL_LOAD;
+              break;
+      default:
+              return -EINVAL;
+      }
+
+      switch (attr->bp_len) {
+      case HW_BREAKPOINT_LEN_1:
+              hw->len = 1;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZELO_8BIT);
+              break;
+      case HW_BREAKPOINT_LEN_2:
+              hw->len = 2;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZELO_16BIT);
+              break;
+      case HW_BREAKPOINT_LEN_4:
+              hw->len = 4;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZELO_32BIT);
+              break;
+#if __riscv_xlen >= 64
+      case HW_BREAKPOINT_LEN_8:
+              hw->len = 8;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZELO_64BIT) |
+                        FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZEHI_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZEHI_64BIT);
+              break;
+#endif
+      default:
Quoted 8 lines

arch/riscv/kernel/hw_breakpoint.c line 286

Quoted 4 lines
arch/riscv/kernel/hw_breakpoint.c new file +4 -0
+              return -EINVAL;
+      }
+
+      tdata1 |= DBTR_TDATA1_MCONTROL_U;

Assuming this function could be re-used for kernel data breakpoints too Shouldn't this be based on some flag to select U v/s S.
Same comment for setting up tdata1 with mcontrol6.

Yes I can add a mode flag, so when kernel breakpoints or virtualized breakpoints are added it will be easier.

Thanks,
Jesse Taube

Quoted 355 lines
Quoted 355 lines
arch/riscv/kernel/hw_breakpoint.c new file +334 -0
+
+      hw->tdata1 = tdata1;
+
+      return 0;
+}
+
+static int rv_init_mcontrol6_trigger(const struct perf_event_attr *attr,
+                                   struct arch_hw_breakpoint *hw)
+{
+      unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+      switch (attr->bp_type) {
+      case HW_BREAKPOINT_X:
+              tdata1 |= DBTR_TDATA1_MCONTROL6_EXECUTE;
+              break;
+      case HW_BREAKPOINT_R:
+              tdata1 |= DBTR_TDATA1_MCONTROL6_LOAD;
+              break;
+      case HW_BREAKPOINT_W:
+              tdata1 |= DBTR_TDATA1_MCONTROL6_STORE;
+              break;
+      case HW_BREAKPOINT_RW:
+              tdata1 |= DBTR_TDATA1_MCONTROL6_STORE | DBTR_TDATA1_MCONTROL6_LOAD;
+              break;
+      default:
+              return -EINVAL;
+      }
+
+      switch (attr->bp_len) {
+      case HW_BREAKPOINT_LEN_1:
+              hw->len = 1;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                   DBTR_TDATA1_MCONTROL6_SIZE_8BIT);
+              break;
+      case HW_BREAKPOINT_LEN_2:
+              hw->len = 2;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                   DBTR_TDATA1_MCONTROL6_SIZE_16BIT);
+              break;
+      case HW_BREAKPOINT_LEN_4:
+              hw->len = 4;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                   DBTR_TDATA1_MCONTROL6_SIZE_32BIT);
+              break;
+      case HW_BREAKPOINT_LEN_8:
+              hw->len = 8;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                   DBTR_TDATA1_MCONTROL6_SIZE_64BIT);
+              break;
+      default:
+              return -EINVAL;
+      }
+
+      tdata1 |= DBTR_TDATA1_MCONTROL6_U;
+
+      hw->tdata1 = tdata1;
+
+      return 0;
+}
+
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+                           const struct perf_event_attr *attr,
+                           struct arch_hw_breakpoint *hw)
+{
+      int ret;
+
+      /* Breakpoint address */
+      hw->address = attr->bp_addr;
+      hw->tdata2 = attr->bp_addr;
+      hw->tdata3 = 0x0;
+      hw->next_addr = 0x0;
+      hw->in_callback = false;
+
+      switch (dbtr_type) {
+      case DBTR_TDATA1_TYPE_MCONTROL:
+              ret = rv_init_mcontrol_trigger(attr, hw);
+              break;
+      case DBTR_TDATA1_TYPE_MCONTROL6:
+              ret = rv_init_mcontrol6_trigger(attr, hw);
+              break;
+      default:
+              pr_warn("Unsupported trigger type %lu.\n", dbtr_type >> DBTR_TDATA1_TYPE_SHIFT);
+              ret = -EOPNOTSUPP;
+              break;
+      }
+
+      return ret;
+}
+
+/*
+ * Set breakpoint to next insruction after breakpoint.
+ * Returns 0 if success
+ * Returns < 0 on error
+ */
+static int setup_singlestep(struct perf_event *event, struct pt_regs *regs)
+{
+      struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+      struct arch_hw_breakpoint old_hw_bp;
+      struct perf_event_attr bp_insn;
+      unsigned long next_addr, insn;
+      int ret;
+
+      /* Remove breakpoint even if return error as not to loop */
+      arch_uninstall_hw_breakpoint(event);
+
+      ret = get_insn(regs, regs->epc, &insn);
+      if (ret < 0)
+              return ret;
+
+      next_addr = get_step_address(regs, insn);
+
+      ret = get_insn(regs, next_addr, &insn);
+      if (ret < 0)
+              return ret;
+
+      bp_insn.bp_type = HW_BREAKPOINT_X;
+      bp_insn.bp_addr = next_addr;
+      /* Get the size of the intruction */
+      bp_insn.bp_len = GET_INSN_LENGTH(insn);
+
+      ret = hw_breakpoint_arch_parse(NULL, &bp_insn, bp);
+      if (ret)
+              return ret;
+
+      ret = arch_install_hw_breakpoint(event);
+      if (ret)
+              return ret;
+
+      bp->in_callback = true;
+      bp->next_addr = next_addr;
+      return 0;
+}
+
+/*
+ * HW Breakpoint/watchpoint handler
+ */
+static int hw_breakpoint_handler(struct pt_regs *regs)
+{
+      struct perf_event *event;
+      struct arch_hw_breakpoint *bp;
+      int ret, i;
+
+      for (i = 0; i < dbtr_total_num; i++) {
+              event = this_cpu_read(pcpu_hw_bp_events[i]);
+              if (!event)
+                      continue;
+
+              bp = counter_arch_bp(event);
+              if (bp->in_callback) {
+                      /* Reset changed breakpoint data */
+                      bp->in_callback = false;
+                      if (regs->epc == bp->next_addr) {
+                              arch_uninstall_hw_breakpoint(event);
+                              /* Restore original breakpoint */
+                              if (hw_breakpoint_arch_parse(NULL, &event->attr, bp))
+                                      return NOTIFY_DONE;
+                              if (arch_install_hw_breakpoint(event))
+                                      return NOTIFY_DONE;
+                              return NOTIFY_STOP;
+                      }
+
+                      pr_err("%s: in_callback was set, but epc(%lx) was not next "
+                               "address(%lx).\n", __func__, regs->epc, bp->next_addr);
+                      bp->next_addr = 0x0;
+                      return NOTIFY_DONE;
+              }
+
+              switch (event->attr.bp_type) {
+              /* Breakpoint */
+              case HW_BREAKPOINT_X:
+                      if (event->attr.bp_addr == regs->epc) {
+                              ret = setup_singlestep(event, regs);
+                              if (ret < 0) {
+                                      pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+                                      return NOTIFY_DONE;
+                              }
+
+                              perf_bp_event(event, regs);
+                              return NOTIFY_STOP;
+                      }
+                      break;
+
+              /* Watchpoint */
+              case HW_BREAKPOINT_W:
+              case HW_BREAKPOINT_R:
+              case HW_BREAKPOINT_RW:
+                      if (event->attr.bp_addr == regs->badaddr) {
+                              ret = setup_singlestep(event, regs);
+                              if (ret < 0) {
+                                      pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+                                      return NOTIFY_DONE;
+                              }
+
+                              perf_bp_event(event, regs);
+                              return NOTIFY_STOP;
+                      }
+                      break;
+
+              default:
+                      pr_warn("%s: Unknown type: %u\n", __func__, event->attr.bp_type);
+                      break;
+              }
+      }
+
+      return NOTIFY_DONE;
+}
+
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+                                  unsigned long val, void *data)
+{
+      struct die_args *args = data;
+
+      if (val != DIE_DEBUG)
+              return NOTIFY_DONE;
+
+      return hw_breakpoint_handler(args->regs);
+}
+
+/* atomic: counter->ctx->lock is held */
+int arch_install_hw_breakpoint(struct perf_event *event)
+{
+      struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+      union sbi_dbtr_shmem_entry *shmem = this_cpu_ptr(&sbi_dbtr_shmem);
+      struct sbi_dbtr_data_msg *xmit;
+      struct sbi_dbtr_id_msg *recv;
+      struct perf_event **slot;
+      unsigned long idx;
+      struct sbiret ret;
+      int err = 0;
+
+      raw_spin_lock_irqsave(this_cpu_ptr(&ecall_lock),
+                            *this_cpu_ptr(&ecall_lock_flags));
+
+      xmit = &shmem->data;
+      recv = &shmem->id;
+      xmit->tdata1 = cpu_to_le(bp->tdata1);
+      xmit->tdata2 = cpu_to_le(bp->tdata2);
+      xmit->tdata3 = cpu_to_le(bp->tdata3);
+
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_INSTALL,
+                      1, 0, 0, 0, 0, 0);
+
+      if (ret.error) {
+              pr_warn("%s: failed to install trigger. error: %ld\n", __func__, ret.error);
+              err = sbi_err_map_linux_errno(ret.error);
+              goto done;
+      }
+
+      idx = le_to_cpu(recv->idx);
+      if (idx >= dbtr_total_num) {
+              pr_warn("%s: invalid trigger index %lu\n", __func__, idx);
+              err = -EINVAL;
+              goto done;
+      }
+
+      slot = this_cpu_ptr(&pcpu_hw_bp_events[idx]);
+      if (*slot) {
+              pr_warn("%s: slot %lu is in use\n", __func__, idx);
+              err = -EBUSY;
+              goto done;
+      }
+
+      pr_debug("Trigger 0x%lx installed at index 0x%lx\n", bp->tdata2, idx);
+
+      /* Save the event - to be looked up in handler */
+      *slot = event;
+
+done:
+      raw_spin_unlock_irqrestore(this_cpu_ptr(&ecall_lock),
+                                 *this_cpu_ptr(&ecall_lock_flags));
+      return err;
+}
+
+/* atomic: counter->ctx->lock is held */
+void arch_uninstall_hw_breakpoint(struct perf_event *event)
+{
+      struct sbiret ret;
+      int i;
+
+      for (i = 0; i < dbtr_total_num; i++) {
+              struct perf_event **slot = this_cpu_ptr(&pcpu_hw_bp_events[i]);
+
+              if (*slot == event) {
+                      *slot = NULL;
+                      break;
+              }
+      }
+
+
+      if (i == dbtr_total_num) {
+              pr_warn("%s: Breakpoint not installed.\n", __func__);
+              return;
+      }
+
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_UNINSTALL,
+                      i, 1, 0, 0, 0, 0);
+      if (ret.error)
+              pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
+}
+
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }
+
+void hw_breakpoint_pmu_read(struct perf_event *bp) { }
+
+static int __init arch_hw_breakpoint_init(void)
+{
+      unsigned int cpu;
+      int rc = 0;
+
+      for_each_possible_cpu(cpu)
+              raw_spin_lock_init(&per_cpu(ecall_lock, cpu));
+
+      init_sbi_dbtr();
+
+      if (dbtr_total_num) {
+              pr_debug("%s: total number of type %lu triggers: %u\n",
+                      __func__, dbtr_type >> DBTR_TDATA1_TYPE_SHIFT, dbtr_total_num);
+      } else {
+              pr_debug("%s: No hardware triggers available\n", __func__);
+              return rc;
+      }
+
+      /* Hotplug handler to register/unregister shared memory with SBI */
+      rc = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN,
+                             "riscv/hw_breakpoint:prepare",
+                             arch_smp_setup_sbi_shmem,
+                             arch_smp_teardown_sbi_shmem);
+
+      if (rc < 0)
+              pr_warn("%s: Failed to setup CPU hotplug state\n", __func__);
+
+      return rc;
+}
+arch_initcall(arch_hw_breakpoint_init);
arch/riscv/kernel/traps.c +6 -1
index 938a8b841f94..2ac471ec79a8 100644
@@ -289,6 +289,12 @@ void handle_break(struct pt_regs *regs)
      if (probe_breakpoint_handler(regs))
              return;
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+      if (notify_die(DIE_DEBUG, "EBREAK", regs, 0, regs->cause, SIGTRAP)
+          == NOTIFY_STOP)
+              return;
+#endif
+
      current->thread.bad_cause = regs->cause;
 
      if (user_mode(regs))
--

2.43.0

#8 lore raw

Re: [RFC PATCH 4/6] riscv: Introduce support for hardware break/watchpoints

Quoted 364 lines · Jesse Taube
Quoted 363 lines · Deepak Gupta
Quoted 346 lines · Jesse Taube

From: Himanshu Chauhan <[email protected]>

RISC-V hardware breakpoint framework is built on top of perf subsystem and uses SBI debug trigger extension to install/uninstall/update/enable/disable hardware triggers as specified in Sdtrig ISA extension.

---

arch/riscv/Kconfig                     |   1 +
arch/riscv/include/asm/hw_breakpoint.h |  60 +++
arch/riscv/include/asm/kdebug.h        |   3 +-
arch/riscv/include/asm/sbi.h           |   4 +-
arch/riscv/kernel/Makefile             |   1 +
arch/riscv/kernel/hw_breakpoint.c      | 620 +++++++++++++++++++++++++
arch/riscv/kernel/traps.c              |   6 +
7 files changed, 693 insertions(+), 2 deletions(-)

create mode 100644 arch/riscv/include/asm/hw_breakpoint.h create mode 100644 arch/riscv/kernel/hw_breakpoint.c

arch/riscv/Kconfig +1 -0
index bbec87b79309..95d3047cab10 100644
@@ -163,6 +163,7 @@ config RISCV
      select HAVE_FUNCTION_ERROR_INJECTION
      select HAVE_GCC_PLUGINS
      select HAVE_GENERIC_VDSO if MMU && 64BIT
+      select HAVE_HW_BREAKPOINT if PERF_EVENTS && RISCV_SBI
      select HAVE_IRQ_TIME_ACCOUNTING
      select HAVE_KERNEL_BZIP2 if !XIP_KERNEL && !EFI_ZBOOT
      select HAVE_KERNEL_GZIP if !XIP_KERNEL && !EFI_ZBOOT
arch/riscv/include/asm/hw_breakpoint.h new file +60 -0
new file mode 100644
index 000000000000..8efa3921c535
@@ -0,0 +1,60 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#ifndef __RISCV_HW_BREAKPOINT_H
+#define __RISCV_HW_BREAKPOINT_H
+
+struct task_struct;
+
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+
+#include <uapi/linux/hw_breakpoint.h>
+
+#if __riscv_xlen == 64
+#define cpu_to_le cpu_to_le64
+#define le_to_cpu le64_to_cpu
+#elif __riscv_xlen == 32
+#define cpu_to_le cpu_to_le32
+#define le_to_cpu le32_to_cpu
+#else
+#error "Unexpected __riscv_xlen"
+#endif
+
+struct arch_hw_breakpoint {
+      unsigned long address;
+      unsigned long len;
+
+      /* Callback info */
+      unsigned long next_addr;
+      bool in_callback;
+
+
+      /* Trigger configuration data */
+      unsigned long tdata1;
+      unsigned long tdata2;
+      unsigned long tdata3;
+};
+
+/* Maximum number of hardware breakpoints supported */
+#define RV_MAX_TRIGGERS 32
+
+struct perf_event_attr;
+struct notifier_block;
+struct perf_event;
+struct pt_regs;
+
+int hw_breakpoint_slots(int type);
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw);
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+                           const struct perf_event_attr *attr,
+                           struct arch_hw_breakpoint *hw);
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+                                  unsigned long val, void *data);
+int arch_install_hw_breakpoint(struct perf_event *bp);
+void arch_uninstall_hw_breakpoint(struct perf_event *bp);
+void hw_breakpoint_pmu_read(struct perf_event *bp);
+
+#endif /* CONFIG_HAVE_HW_BREAKPOINT */
+#endif /* __RISCV_HW_BREAKPOINT_H */
arch/riscv/include/asm/kdebug.h +2 -1
index 85ac00411f6e..53e989781aa1 100644
@@ -6,7 +6,8 @@
 enum die_val {
      DIE_UNUSED,
      DIE_TRAP,
-      DIE_OOPS
+      DIE_OOPS,
+      DIE_DEBUG
 };
 
 #endif
arch/riscv/include/asm/sbi.h +3 -1
index be2ca8e8a49e..64fa7a82aa45 100644
@@ -282,7 +282,9 @@ struct sbi_sta_struct {
      u8 pad[47];
 } __packed;
 
-#define SBI_SHMEM_DISABLE             -1
+#define SBI_SHMEM_DISABLE     (-1UL)
+#define SBI_SHMEM_LO(pa)      ((unsigned long)lower_32_bits(pa))
+#define SBI_SHMEM_HI(pa)      ((unsigned long)upper_32_bits(pa))
 
 enum sbi_ext_nacl_fid {
      SBI_EXT_NACL_PROBE_FEATURE = 0x0,
arch/riscv/kernel/Makefile +0 -0
index 4f719b09e5ad..3e72505734bd 100644
@@ -99,6 +99,7 @@ obj-$(CONFIG_DYNAMIC_FTRACE) += mcount-dyn.o
 

obj-$(CONFIG_PERF_EVENTS) += perf_callchain.o
obj-$(CONFIG_HAVE_PERF_REGS) += perf_regs.o
+obj-$(CONFIG_HAVE_HW_BREAKPOINT) += hw_breakpoint.o
obj-$(CONFIG_RISCV_SBI) += sbi.o sbi_ecall.o
ifeq ($(CONFIG_RISCV_SBI), y)
obj-$(CONFIG_SMP) += sbi-ipi.o

arch/riscv/kernel/hw_breakpoint.c new file +201 -0
new file mode 100644
index 000000000000..9e3a3b82d300
@@ -0,0 +1,620 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#include <linux/hw_breakpoint.h>
+#include <linux/perf_event.h>
+#include <linux/spinlock.h>
+#include <linux/percpu.h>
+#include <linux/kdebug.h>
+#include <linux/bitops.h>
+#include <linux/bitfield.h>
+#include <linux/cpu.h>
+#include <linux/cpuhotplug.h>
+
+#include <asm/insn.h>
+#include <asm/sbi.h>
+
+#define DBTR_TDATA1_TYPE_SHIFT                (__riscv_xlen - 4)
+#define DBTR_TDATA1_DMODE             BIT_UL(__riscv_xlen - 5)
+
+#define DBTR_TDATA1_TYPE_MCONTROL     (2UL << DBTR_TDATA1_TYPE_SHIFT)
+#define DBTR_TDATA1_TYPE_MCONTROL6    (6UL << DBTR_TDATA1_TYPE_SHIFT)
+
+#define DBTR_TDATA1_MCONTROL6_LOAD            BIT(0)
+#define DBTR_TDATA1_MCONTROL6_STORE           BIT(1)
+#define DBTR_TDATA1_MCONTROL6_EXECUTE         BIT(2)
+#define DBTR_TDATA1_MCONTROL6_U                       BIT(3)
+#define DBTR_TDATA1_MCONTROL6_S                       BIT(4)
+#define DBTR_TDATA1_MCONTROL6_M                       BIT(6)
+#define DBTR_TDATA1_MCONTROL6_SIZE_FIELD      GENMASK(18, 16)
+#define DBTR_TDATA1_MCONTROL6_SELECT          BIT(21)
+#define DBTR_TDATA1_MCONTROL6_VU              BIT(23)
+#define DBTR_TDATA1_MCONTROL6_VS              BIT(24)
+
+#define DBTR_TDATA1_MCONTROL6_SIZE_8BIT               1
+#define DBTR_TDATA1_MCONTROL6_SIZE_16BIT      2
+#define DBTR_TDATA1_MCONTROL6_SIZE_32BIT      3
+#define DBTR_TDATA1_MCONTROL6_SIZE_64BIT      5
+
+#define DBTR_TDATA1_MCONTROL_LOAD             BIT(0)
+#define DBTR_TDATA1_MCONTROL_STORE            BIT(1)
+#define DBTR_TDATA1_MCONTROL_EXECUTE          BIT(2)
+#define DBTR_TDATA1_MCONTROL_U                        BIT(3)
+#define DBTR_TDATA1_MCONTROL_S                        BIT(4)
+#define DBTR_TDATA1_MCONTROL_M                        BIT(6)
+#define DBTR_TDATA1_MCONTROL_SIZELO_FIELD     GENMASK(17, 16)
+#define DBTR_TDATA1_MCONTROL_SELECT           BIT(19)
+#define DBTR_TDATA1_MCONTROL_SIZEHI_FIELD     GENMASK(22, 21)
+
+#define DBTR_TDATA1_MCONTROL_SIZELO_8BIT      1
+#define DBTR_TDATA1_MCONTROL_SIZELO_16BIT     2
+#define DBTR_TDATA1_MCONTROL_SIZELO_32BIT     3
+/* value of 5 split across HI and LO */
+#define DBTR_TDATA1_MCONTROL_SIZELO_64BIT     1
+#define DBTR_TDATA1_MCONTROL_SIZEHI_64BIT     1
+
+/* Registered per-cpu bp/wp */
+static DEFINE_PER_CPU(struct perf_event *, pcpu_hw_bp_events[RV_MAX_TRIGGERS]);
+static DEFINE_PER_CPU(unsigned long, ecall_lock_flags);
+static DEFINE_PER_CPU(raw_spinlock_t, ecall_lock);
+
+/* Per-cpu shared memory between S and M mode */
+static DEFINE_PER_CPU(union sbi_dbtr_shmem_entry, sbi_dbtr_shmem);
+
+/* number of debug triggers on this cpu . */
+static int dbtr_total_num __ro_after_init;
+static unsigned long dbtr_type __ro_after_init;
+static unsigned long dbtr_init __ro_after_init;
+
+static int arch_smp_setup_sbi_shmem(unsigned int cpu)
+{
+      union sbi_dbtr_shmem_entry *dbtr_shmem;
+      unsigned long shmem_pa;
+      struct sbiret ret;
+      int rc;
+
+      dbtr_shmem = per_cpu_ptr(&sbi_dbtr_shmem, cpu);
+      if (!dbtr_shmem) {
+              pr_err("Invalid per-cpu shared memory for debug triggers\n");
+              return -ENODEV;
+      }
+
+      shmem_pa = virt_to_phys(dbtr_shmem);
+
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+                      SBI_SHMEM_LO(shmem_pa), SBI_SHMEM_HI(shmem_pa), 0, 0, 0, 0);
+
+      if (ret.error) {
+              switch (ret.error) {
+              case SBI_ERR_DENIED:
+                      pr_warn("%s: Access denied for shared memory at %lx\n",
+                              __func__, shmem_pa);
+                      rc = -EPERM;
+                      break;
+
+              case SBI_ERR_INVALID_PARAM:
+              case SBI_ERR_INVALID_ADDRESS:
+                      pr_warn("%s: Invalid address parameter (%ld)\n",
+                              __func__, ret.error);
+                      rc = -EINVAL;
+                      break;
+
+              case SBI_ERR_ALREADY_AVAILABLE:
+                      pr_warn("%s: Shared memory is already set\n",
+                              __func__);
+                      rc = -EADDRINUSE;
+                      break;
+
+              case SBI_ERR_FAILURE:
+                      pr_err("%s: Internal sdtrig state error\n",
+                             __func__);
+                      rc = -ENXIO;
+                      break;
+
+              default:
+                      pr_warn("%s: Unknown error %lu\n", __func__, ret.error);
+                      rc = -ENXIO;
+                      break;
+              }
+      }
+
+      pr_debug("CPU %d: HW Breakpoint shared memory registered.\n", cpu);
+
+      return rc;
+}
+
+static int arch_smp_teardown_sbi_shmem(unsigned int cpu)
+{
+      struct sbiret ret;
+
+      /* Disable shared memory */
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+                      SBI_SHMEM_DISABLE, SBI_SHMEM_DISABLE, 0, 0, 0, 0);
+
+      if (ret.error) {
+              switch (ret.error) {
+              case SBI_ERR_DENIED:
+                      pr_err("%s: Access denied for shared memory.\n",
+                             __func__);
+                      break;
+
+              case SBI_ERR_INVALID_PARAM:
+              case SBI_ERR_INVALID_ADDRESS:
+                      pr_err("%s: Invalid address parameter (%lu)\n",
+                             __func__, ret.error);
+                      break;
+
+              case SBI_ERR_ALREADY_AVAILABLE:
+                      pr_err("%s: Shared memory is already set\n",
+                             __func__);
+                      break;
+              case SBI_ERR_FAILURE:
+                      pr_err("%s: Internal sdtrig state error\n",
+                             __func__);
+                      break;
+              default:
+                      pr_err("%s: Unknown error %lu\n", __func__, ret.error);
+                      break;
+              }
+      }
+
+      pr_debug("CPU %d: HW Breakpoint shared memory disabled.\n", cpu);
+
+      return 0;
+}
+
+static void init_sbi_dbtr(void)
+{
+      struct sbiret ret;
+
+      /*
+       * Called by hw_breakpoint_slots and arch_hw_breakpoint_init.
+       * Only proceed if this is the first CPU to reach this code.
+       */
+      if (test_and_set_bit(0, &dbtr_init))
+              return;
+
+      if (sbi_probe_extension(SBI_EXT_DBTR) <= 0) {
+              pr_debug("%s: SBI_EXT_DBTR is not supported\n", __func__);
+              dbtr_total_num = 0;
+              return;
+      }
+
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+                      DBTR_TDATA1_TYPE_MCONTROL6, 0, 0, 0, 0, 0);
+      if (ret.error) {
+              pr_warn("%s: failed to detect mcontrol6 triggers. error: %ld.\n",
+                      __func__, ret.error);
+      } else if (!ret.value) {
+              pr_warn("%s: No mcontrol6 triggers available.\n", __func__);
+      } else {
+              dbtr_total_num = ret.value;
+              dbtr_type = DBTR_TDATA1_TYPE_MCONTROL6;
+              return;
+      }
+
+      /* fallback to legacy mcontrol triggers if mcontrol6 is not available */
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+                      DBTR_TDATA1_TYPE_MCONTROL, 0, 0, 0, 0, 0);
+      if (ret.error) {

arch/riscv/kernel/hw_breakpoint.c line 211

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+              pr_warn("%s: failed to detect mcontrol triggers. error: %ld.\n",
+                      __func__, ret.error);
+      } else if (!ret.value) {
+              pr_err("%s: No mcontrol triggers available.\n", __func__);
+              dbtr_total_num = 0;
+      } else {
+              dbtr_total_num = ret.value;
+              dbtr_type = DBTR_TDATA1_TYPE_MCONTROL;
+      }
+}

dbtr_total_num is static and thus would be initialized to zero. Although above code is setting it to zero in some error conditions. And not setting to zero in other error conditions.

Quoted 8 lines
Quoted 2 lines

It'll be better if function starts out setting dbtr_total_num as setting to 0. Then set correct value in success conditions.

I would do that, but dbtr_total_num is marked as __ro_after_init and I don't want to
write to it twice, and i wanted to explicitly set it to zero as that means breakpoints are disabled.
I can just remove the assignments to zero though.

Make sense.

Quoted 443 lines
Quoted 73 lines
Quoted 73 lines
arch/riscv/kernel/hw_breakpoint.c new file +71 -0
+
+int hw_breakpoint_slots(int type)
+{
+      /*
+       * We can be called early, so don't rely on
+       * static variables being initialised.
+       */
+      init_sbi_dbtr();
+
+      return dbtr_total_num;
+}
+
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw)
+{
+      unsigned int len;
+      unsigned long va;
+
+      va = hw->address;
+      len = hw->len;
+
+      return (va >= TASK_SIZE) && ((va + len - 1) >= TASK_SIZE);
+}
+
+static int rv_init_mcontrol_trigger(const struct perf_event_attr *attr,
+                                  struct arch_hw_breakpoint *hw)
+{
+      unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+      switch (attr->bp_type) {
+      case HW_BREAKPOINT_X:
+              tdata1 |= DBTR_TDATA1_MCONTROL_EXECUTE;
+              break;
+      case HW_BREAKPOINT_R:
+              tdata1 |= DBTR_TDATA1_MCONTROL_LOAD;
+              break;
+      case HW_BREAKPOINT_W:
+              tdata1 |= DBTR_TDATA1_MCONTROL_STORE;
+              break;
+      case HW_BREAKPOINT_RW:
+              tdata1 |= DBTR_TDATA1_MCONTROL_STORE | DBTR_TDATA1_MCONTROL_LOAD;
+              break;
+      default:
+              return -EINVAL;
+      }
+
+      switch (attr->bp_len) {
+      case HW_BREAKPOINT_LEN_1:
+              hw->len = 1;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZELO_8BIT);
+              break;
+      case HW_BREAKPOINT_LEN_2:
+              hw->len = 2;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZELO_16BIT);
+              break;
+      case HW_BREAKPOINT_LEN_4:
+              hw->len = 4;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZELO_32BIT);
+              break;
+#if __riscv_xlen >= 64
+      case HW_BREAKPOINT_LEN_8:
+              hw->len = 8;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZELO_64BIT) |
+                        FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZEHI_FIELD,
+                                   DBTR_TDATA1_MCONTROL_SIZEHI_64BIT);
+              break;
+#endif
+      default:
Quoted 8 lines

arch/riscv/kernel/hw_breakpoint.c line 286

Quoted 4 lines
arch/riscv/kernel/hw_breakpoint.c new file +4 -0
+              return -EINVAL;
+      }
+
+      tdata1 |= DBTR_TDATA1_MCONTROL_U;

Assuming this function could be re-used for kernel data breakpoints too Shouldn't this be based on some flag to select U v/s S.
Same comment for setting up tdata1 with mcontrol6.

Yes I can add a mode flag, so when kernel breakpoints or virtualized breakpoints are added it will be easier.

Thanks,
Jesse Taube

Quoted 355 lines
Quoted 355 lines
arch/riscv/kernel/hw_breakpoint.c new file +334 -0
+
+      hw->tdata1 = tdata1;
+
+      return 0;
+}
+
+static int rv_init_mcontrol6_trigger(const struct perf_event_attr *attr,
+                                   struct arch_hw_breakpoint *hw)
+{
+      unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+      switch (attr->bp_type) {
+      case HW_BREAKPOINT_X:
+              tdata1 |= DBTR_TDATA1_MCONTROL6_EXECUTE;
+              break;
+      case HW_BREAKPOINT_R:
+              tdata1 |= DBTR_TDATA1_MCONTROL6_LOAD;
+              break;
+      case HW_BREAKPOINT_W:
+              tdata1 |= DBTR_TDATA1_MCONTROL6_STORE;
+              break;
+      case HW_BREAKPOINT_RW:
+              tdata1 |= DBTR_TDATA1_MCONTROL6_STORE | DBTR_TDATA1_MCONTROL6_LOAD;
+              break;
+      default:
+              return -EINVAL;
+      }
+
+      switch (attr->bp_len) {
+      case HW_BREAKPOINT_LEN_1:
+              hw->len = 1;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                   DBTR_TDATA1_MCONTROL6_SIZE_8BIT);
+              break;
+      case HW_BREAKPOINT_LEN_2:
+              hw->len = 2;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                   DBTR_TDATA1_MCONTROL6_SIZE_16BIT);
+              break;
+      case HW_BREAKPOINT_LEN_4:
+              hw->len = 4;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                   DBTR_TDATA1_MCONTROL6_SIZE_32BIT);
+              break;
+      case HW_BREAKPOINT_LEN_8:
+              hw->len = 8;
+              tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                   DBTR_TDATA1_MCONTROL6_SIZE_64BIT);
+              break;
+      default:
+              return -EINVAL;
+      }
+
+      tdata1 |= DBTR_TDATA1_MCONTROL6_U;
+
+      hw->tdata1 = tdata1;
+
+      return 0;
+}
+
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+                           const struct perf_event_attr *attr,
+                           struct arch_hw_breakpoint *hw)
+{
+      int ret;
+
+      /* Breakpoint address */
+      hw->address = attr->bp_addr;
+      hw->tdata2 = attr->bp_addr;
+      hw->tdata3 = 0x0;
+      hw->next_addr = 0x0;
+      hw->in_callback = false;
+
+      switch (dbtr_type) {
+      case DBTR_TDATA1_TYPE_MCONTROL:
+              ret = rv_init_mcontrol_trigger(attr, hw);
+              break;
+      case DBTR_TDATA1_TYPE_MCONTROL6:
+              ret = rv_init_mcontrol6_trigger(attr, hw);
+              break;
+      default:
+              pr_warn("Unsupported trigger type %lu.\n", dbtr_type >> DBTR_TDATA1_TYPE_SHIFT);
+              ret = -EOPNOTSUPP;
+              break;
+      }
+
+      return ret;
+}
+
+/*
+ * Set breakpoint to next insruction after breakpoint.
+ * Returns 0 if success
+ * Returns < 0 on error
+ */
+static int setup_singlestep(struct perf_event *event, struct pt_regs *regs)
+{
+      struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+      struct arch_hw_breakpoint old_hw_bp;
+      struct perf_event_attr bp_insn;
+      unsigned long next_addr, insn;
+      int ret;
+
+      /* Remove breakpoint even if return error as not to loop */
+      arch_uninstall_hw_breakpoint(event);
+
+      ret = get_insn(regs, regs->epc, &insn);
+      if (ret < 0)
+              return ret;
+
+      next_addr = get_step_address(regs, insn);
+
+      ret = get_insn(regs, next_addr, &insn);
+      if (ret < 0)
+              return ret;
+
+      bp_insn.bp_type = HW_BREAKPOINT_X;
+      bp_insn.bp_addr = next_addr;
+      /* Get the size of the intruction */
+      bp_insn.bp_len = GET_INSN_LENGTH(insn);
+
+      ret = hw_breakpoint_arch_parse(NULL, &bp_insn, bp);
+      if (ret)
+              return ret;
+
+      ret = arch_install_hw_breakpoint(event);
+      if (ret)
+              return ret;
+
+      bp->in_callback = true;
+      bp->next_addr = next_addr;
+      return 0;
+}
+
+/*
+ * HW Breakpoint/watchpoint handler
+ */
+static int hw_breakpoint_handler(struct pt_regs *regs)
+{
+      struct perf_event *event;
+      struct arch_hw_breakpoint *bp;
+      int ret, i;
+
+      for (i = 0; i < dbtr_total_num; i++) {
+              event = this_cpu_read(pcpu_hw_bp_events[i]);
+              if (!event)
+                      continue;
+
+              bp = counter_arch_bp(event);
+              if (bp->in_callback) {
+                      /* Reset changed breakpoint data */
+                      bp->in_callback = false;
+                      if (regs->epc == bp->next_addr) {
+                              arch_uninstall_hw_breakpoint(event);
+                              /* Restore original breakpoint */
+                              if (hw_breakpoint_arch_parse(NULL, &event->attr, bp))
+                                      return NOTIFY_DONE;
+                              if (arch_install_hw_breakpoint(event))
+                                      return NOTIFY_DONE;
+                              return NOTIFY_STOP;
+                      }
+
+                      pr_err("%s: in_callback was set, but epc(%lx) was not next "
+                               "address(%lx).\n", __func__, regs->epc, bp->next_addr);
+                      bp->next_addr = 0x0;
+                      return NOTIFY_DONE;
+              }
+
+              switch (event->attr.bp_type) {
+              /* Breakpoint */
+              case HW_BREAKPOINT_X:
+                      if (event->attr.bp_addr == regs->epc) {
+                              ret = setup_singlestep(event, regs);
+                              if (ret < 0) {
+                                      pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+                                      return NOTIFY_DONE;
+                              }
+
+                              perf_bp_event(event, regs);
+                              return NOTIFY_STOP;
+                      }
+                      break;
+
+              /* Watchpoint */
+              case HW_BREAKPOINT_W:
+              case HW_BREAKPOINT_R:
+              case HW_BREAKPOINT_RW:
+                      if (event->attr.bp_addr == regs->badaddr) {
+                              ret = setup_singlestep(event, regs);
+                              if (ret < 0) {
+                                      pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+                                      return NOTIFY_DONE;
+                              }
+
+                              perf_bp_event(event, regs);
+                              return NOTIFY_STOP;
+                      }
+                      break;
+
+              default:
+                      pr_warn("%s: Unknown type: %u\n", __func__, event->attr.bp_type);
+                      break;
+              }
+      }
+
+      return NOTIFY_DONE;
+}
+
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+                                  unsigned long val, void *data)
+{
+      struct die_args *args = data;
+
+      if (val != DIE_DEBUG)
+              return NOTIFY_DONE;
+
+      return hw_breakpoint_handler(args->regs);
+}
+
+/* atomic: counter->ctx->lock is held */
+int arch_install_hw_breakpoint(struct perf_event *event)
+{
+      struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+      union sbi_dbtr_shmem_entry *shmem = this_cpu_ptr(&sbi_dbtr_shmem);
+      struct sbi_dbtr_data_msg *xmit;
+      struct sbi_dbtr_id_msg *recv;
+      struct perf_event **slot;
+      unsigned long idx;
+      struct sbiret ret;
+      int err = 0;
+
+      raw_spin_lock_irqsave(this_cpu_ptr(&ecall_lock),
+                            *this_cpu_ptr(&ecall_lock_flags));
+
+      xmit = &shmem->data;
+      recv = &shmem->id;
+      xmit->tdata1 = cpu_to_le(bp->tdata1);
+      xmit->tdata2 = cpu_to_le(bp->tdata2);
+      xmit->tdata3 = cpu_to_le(bp->tdata3);
+
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_INSTALL,
+                      1, 0, 0, 0, 0, 0);
+
+      if (ret.error) {
+              pr_warn("%s: failed to install trigger. error: %ld\n", __func__, ret.error);
+              err = sbi_err_map_linux_errno(ret.error);
+              goto done;
+      }
+
+      idx = le_to_cpu(recv->idx);
+      if (idx >= dbtr_total_num) {
+              pr_warn("%s: invalid trigger index %lu\n", __func__, idx);
+              err = -EINVAL;
+              goto done;
+      }
+
+      slot = this_cpu_ptr(&pcpu_hw_bp_events[idx]);
+      if (*slot) {
+              pr_warn("%s: slot %lu is in use\n", __func__, idx);
+              err = -EBUSY;
+              goto done;
+      }
+
+      pr_debug("Trigger 0x%lx installed at index 0x%lx\n", bp->tdata2, idx);
+
+      /* Save the event - to be looked up in handler */
+      *slot = event;
+
+done:
+      raw_spin_unlock_irqrestore(this_cpu_ptr(&ecall_lock),
+                                 *this_cpu_ptr(&ecall_lock_flags));
+      return err;
+}
+
+/* atomic: counter->ctx->lock is held */
+void arch_uninstall_hw_breakpoint(struct perf_event *event)
+{
+      struct sbiret ret;
+      int i;
+
+      for (i = 0; i < dbtr_total_num; i++) {
+              struct perf_event **slot = this_cpu_ptr(&pcpu_hw_bp_events[i]);
+
+              if (*slot == event) {
+                      *slot = NULL;
+                      break;
+              }
+      }
+
+
+      if (i == dbtr_total_num) {
+              pr_warn("%s: Breakpoint not installed.\n", __func__);
+              return;
+      }
+
+      ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_UNINSTALL,
+                      i, 1, 0, 0, 0, 0);
+      if (ret.error)
+              pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
+}
+
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }
+
+void hw_breakpoint_pmu_read(struct perf_event *bp) { }
+
+static int __init arch_hw_breakpoint_init(void)
+{
+      unsigned int cpu;
+      int rc = 0;
+
+      for_each_possible_cpu(cpu)
+              raw_spin_lock_init(&per_cpu(ecall_lock, cpu));
+
+      init_sbi_dbtr();
+
+      if (dbtr_total_num) {
+              pr_debug("%s: total number of type %lu triggers: %u\n",
+                      __func__, dbtr_type >> DBTR_TDATA1_TYPE_SHIFT, dbtr_total_num);
+      } else {
+              pr_debug("%s: No hardware triggers available\n", __func__);
+              return rc;
+      }
+
+      /* Hotplug handler to register/unregister shared memory with SBI */
+      rc = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN,
+                             "riscv/hw_breakpoint:prepare",
+                             arch_smp_setup_sbi_shmem,
+                             arch_smp_teardown_sbi_shmem);
+
+      if (rc < 0)
+              pr_warn("%s: Failed to setup CPU hotplug state\n", __func__);
+
+      return rc;
+}
+arch_initcall(arch_hw_breakpoint_init);
arch/riscv/kernel/traps.c +6 -1
index 938a8b841f94..2ac471ec79a8 100644
@@ -289,6 +289,12 @@ void handle_break(struct pt_regs *regs)
      if (probe_breakpoint_handler(regs))
              return;
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+      if (notify_die(DIE_DEBUG, "EBREAK", regs, 0, regs->cause, SIGTRAP)
+          == NOTIFY_STOP)
+              return;
+#endif
+
      current->thread.bad_cause = regs->cause;
 
      if (user_mode(regs))
--

2.43.0

#9 lore raw

Re: [RFC PATCH 4/6] riscv: Introduce support for hardware break/watchpoints

In reply to Jesse Taube
Quoted 256 lines · Jesse Taube

From: Himanshu Chauhan <[email protected]>

RISC-V hardware breakpoint framework is built on top of perf subsystem and uses SBI debug trigger extension to install/uninstall/update/enable/disable hardware triggers as specified in Sdtrig ISA extension.

---
 arch/riscv/Kconfig                     |   1 +
 arch/riscv/include/asm/hw_breakpoint.h |  60 +++
 arch/riscv/include/asm/kdebug.h        |   3 +-
 arch/riscv/include/asm/sbi.h           |   4 +-
 arch/riscv/kernel/Makefile             |   1 +
 arch/riscv/kernel/hw_breakpoint.c      | 620 +++++++++++++++++++++++++
 arch/riscv/kernel/traps.c              |   6 +
 7 files changed, 693 insertions(+), 2 deletions(-)
 create mode 100644 arch/riscv/include/asm/hw_breakpoint.h
 create mode 100644 arch/riscv/kernel/hw_breakpoint.c
arch/riscv/Kconfig +1 -0
index bbec87b79309..95d3047cab10 100644
@@ -163,6 +163,7 @@ config RISCV
 	select HAVE_FUNCTION_ERROR_INJECTION
 	select HAVE_GCC_PLUGINS
 	select HAVE_GENERIC_VDSO if MMU && 64BIT
+	select HAVE_HW_BREAKPOINT if PERF_EVENTS && RISCV_SBI
 	select HAVE_IRQ_TIME_ACCOUNTING
 	select HAVE_KERNEL_BZIP2 if !XIP_KERNEL && !EFI_ZBOOT
 	select HAVE_KERNEL_GZIP if !XIP_KERNEL && !EFI_ZBOOT
arch/riscv/include/asm/hw_breakpoint.h new file +60 -0
new file mode 100644
index 000000000000..8efa3921c535
@@ -0,0 +1,60 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#ifndef __RISCV_HW_BREAKPOINT_H
+#define __RISCV_HW_BREAKPOINT_H
+
+struct task_struct;
+
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+
+#include <uapi/linux/hw_breakpoint.h>
+
+#if __riscv_xlen == 64
+#define cpu_to_le cpu_to_le64
+#define le_to_cpu le64_to_cpu
+#elif __riscv_xlen == 32
+#define cpu_to_le cpu_to_le32
+#define le_to_cpu le32_to_cpu
+#else
+#error "Unexpected __riscv_xlen"
+#endif
+
+struct arch_hw_breakpoint {
+	unsigned long address;
+	unsigned long len;
+
+	/* Callback info */
+	unsigned long next_addr;
+	bool in_callback;
+
+
+	/* Trigger configuration data */
+	unsigned long tdata1;
+	unsigned long tdata2;
+	unsigned long tdata3;
+};
+
+/* Maximum number of hardware breakpoints supported */
+#define RV_MAX_TRIGGERS 32
+
+struct perf_event_attr;
+struct notifier_block;
+struct perf_event;
+struct pt_regs;
+
+int hw_breakpoint_slots(int type);
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw);
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+			     const struct perf_event_attr *attr,
+			     struct arch_hw_breakpoint *hw);
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+				    unsigned long val, void *data);
+int arch_install_hw_breakpoint(struct perf_event *bp);
+void arch_uninstall_hw_breakpoint(struct perf_event *bp);
+void hw_breakpoint_pmu_read(struct perf_event *bp);
+
+#endif /* CONFIG_HAVE_HW_BREAKPOINT */
+#endif /* __RISCV_HW_BREAKPOINT_H */
arch/riscv/include/asm/kdebug.h +2 -1
index 85ac00411f6e..53e989781aa1 100644
@@ -6,7 +6,8 @@
 enum die_val {
 	DIE_UNUSED,
 	DIE_TRAP,
-	DIE_OOPS
+	DIE_OOPS,
+	DIE_DEBUG
 };
 
 #endif
arch/riscv/include/asm/sbi.h +3 -1
index be2ca8e8a49e..64fa7a82aa45 100644
@@ -282,7 +282,9 @@ struct sbi_sta_struct {
 	u8 pad[47];
 } __packed;
 
-#define SBI_SHMEM_DISABLE		-1
+#define SBI_SHMEM_DISABLE	(-1UL)
+#define SBI_SHMEM_LO(pa)	((unsigned long)lower_32_bits(pa))
+#define SBI_SHMEM_HI(pa)	((unsigned long)upper_32_bits(pa))
 
 enum sbi_ext_nacl_fid {
 	SBI_EXT_NACL_PROBE_FEATURE = 0x0,
arch/riscv/kernel/Makefile +1 -0
index 4f719b09e5ad..3e72505734bd 100644
@@ -99,6 +99,7 @@ obj-$(CONFIG_DYNAMIC_FTRACE)	+= mcount-dyn.o
 
 obj-$(CONFIG_PERF_EVENTS)	+= perf_callchain.o
 obj-$(CONFIG_HAVE_PERF_REGS)	+= perf_regs.o
+obj-$(CONFIG_HAVE_HW_BREAKPOINT)	+= hw_breakpoint.o
 obj-$(CONFIG_RISCV_SBI)		+= sbi.o sbi_ecall.o
 ifeq ($(CONFIG_RISCV_SBI), y)
 obj-$(CONFIG_SMP)		+= sbi-ipi.o
arch/riscv/kernel/hw_breakpoint.c new file +111 -0
new file mode 100644
index 000000000000..9e3a3b82d300
@@ -0,0 +1,620 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#include <linux/hw_breakpoint.h>
+#include <linux/perf_event.h>
+#include <linux/spinlock.h>
+#include <linux/percpu.h>
+#include <linux/kdebug.h>
+#include <linux/bitops.h>
+#include <linux/bitfield.h>
+#include <linux/cpu.h>
+#include <linux/cpuhotplug.h>
+
+#include <asm/insn.h>
+#include <asm/sbi.h>
+
+#define DBTR_TDATA1_TYPE_SHIFT		(__riscv_xlen - 4)
+#define DBTR_TDATA1_DMODE		BIT_UL(__riscv_xlen - 5)
+
+#define DBTR_TDATA1_TYPE_MCONTROL	(2UL << DBTR_TDATA1_TYPE_SHIFT)
+#define DBTR_TDATA1_TYPE_MCONTROL6	(6UL << DBTR_TDATA1_TYPE_SHIFT)
+
+#define DBTR_TDATA1_MCONTROL6_LOAD		BIT(0)
+#define DBTR_TDATA1_MCONTROL6_STORE		BIT(1)
+#define DBTR_TDATA1_MCONTROL6_EXECUTE		BIT(2)
+#define DBTR_TDATA1_MCONTROL6_U			BIT(3)
+#define DBTR_TDATA1_MCONTROL6_S			BIT(4)
+#define DBTR_TDATA1_MCONTROL6_M			BIT(6)
+#define DBTR_TDATA1_MCONTROL6_SIZE_FIELD	GENMASK(18, 16)
+#define DBTR_TDATA1_MCONTROL6_SELECT		BIT(21)
+#define DBTR_TDATA1_MCONTROL6_VU		BIT(23)
+#define DBTR_TDATA1_MCONTROL6_VS		BIT(24)
+
+#define DBTR_TDATA1_MCONTROL6_SIZE_8BIT		1
+#define DBTR_TDATA1_MCONTROL6_SIZE_16BIT	2
+#define DBTR_TDATA1_MCONTROL6_SIZE_32BIT	3
+#define DBTR_TDATA1_MCONTROL6_SIZE_64BIT	5
+
+#define DBTR_TDATA1_MCONTROL_LOAD		BIT(0)
+#define DBTR_TDATA1_MCONTROL_STORE		BIT(1)
+#define DBTR_TDATA1_MCONTROL_EXECUTE		BIT(2)
+#define DBTR_TDATA1_MCONTROL_U			BIT(3)
+#define DBTR_TDATA1_MCONTROL_S			BIT(4)
+#define DBTR_TDATA1_MCONTROL_M			BIT(6)
+#define DBTR_TDATA1_MCONTROL_SIZELO_FIELD	GENMASK(17, 16)
+#define DBTR_TDATA1_MCONTROL_SELECT		BIT(19)
+#define DBTR_TDATA1_MCONTROL_SIZEHI_FIELD	GENMASK(22, 21)
+
+#define DBTR_TDATA1_MCONTROL_SIZELO_8BIT	1
+#define DBTR_TDATA1_MCONTROL_SIZELO_16BIT	2
+#define DBTR_TDATA1_MCONTROL_SIZELO_32BIT	3
+/* value of 5 split across HI and LO */
+#define DBTR_TDATA1_MCONTROL_SIZELO_64BIT	1
+#define DBTR_TDATA1_MCONTROL_SIZEHI_64BIT	1
+
+/* Registered per-cpu bp/wp */
+static DEFINE_PER_CPU(struct perf_event *, pcpu_hw_bp_events[RV_MAX_TRIGGERS]);
+static DEFINE_PER_CPU(unsigned long, ecall_lock_flags);
+static DEFINE_PER_CPU(raw_spinlock_t, ecall_lock);
+
+/* Per-cpu shared memory between S and M mode */
+static DEFINE_PER_CPU(union sbi_dbtr_shmem_entry, sbi_dbtr_shmem);
+
+/* number of debug triggers on this cpu . */
+static int dbtr_total_num __ro_after_init;
+static unsigned long dbtr_type __ro_after_init;
+static unsigned long dbtr_init __ro_after_init;
+
+static int arch_smp_setup_sbi_shmem(unsigned int cpu)
+{
+	union sbi_dbtr_shmem_entry *dbtr_shmem;
+	unsigned long shmem_pa;
+	struct sbiret ret;
+	int rc;
+
+	dbtr_shmem = per_cpu_ptr(&sbi_dbtr_shmem, cpu);
+	if (!dbtr_shmem) {
+		pr_err("Invalid per-cpu shared memory for debug triggers\n");
+		return -ENODEV;
+	}
+
+	shmem_pa = virt_to_phys(dbtr_shmem);
+
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+			SBI_SHMEM_LO(shmem_pa), SBI_SHMEM_HI(shmem_pa), 0, 0, 0, 0);
+
+	if (ret.error) {
+		switch (ret.error) {
+		case SBI_ERR_DENIED:
+			pr_warn("%s: Access denied for shared memory at %lx\n",
+				__func__, shmem_pa);
+			rc = -EPERM;
+			break;
+
+		case SBI_ERR_INVALID_PARAM:
+		case SBI_ERR_INVALID_ADDRESS:
+			pr_warn("%s: Invalid address parameter (%ld)\n",
+				__func__, ret.error);
+			rc = -EINVAL;
+			break;
+
+		case SBI_ERR_ALREADY_AVAILABLE:
+			pr_warn("%s: Shared memory is already set\n",
+				__func__);
+			rc = -EADDRINUSE;
+			break;
+
+		case SBI_ERR_FAILURE:
+			pr_err("%s: Internal sdtrig state error\n",

arch/riscv/kernel/hw_breakpoint.c line 121

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+			       __func__);
+			rc = -ENXIO;
+			break;
+
+		default:
+			pr_warn("%s: Unknown error %lu\n", __func__, ret.error);
+			rc = -ENXIO;
+			break;
+		}
+	}

Hi Jesse,

Is there a reason not to use sbi_err_map_linux_errno() ?

Quoted 30 lines
arch/riscv/kernel/hw_breakpoint.c new file +30 -0
+
+	pr_debug("CPU %d: HW Breakpoint shared memory registered.\n", cpu);
+
+	return rc;
+}
+
+static int arch_smp_teardown_sbi_shmem(unsigned int cpu)
+{
+	struct sbiret ret;
+
+	/* Disable shared memory */
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+			SBI_SHMEM_DISABLE, SBI_SHMEM_DISABLE, 0, 0, 0, 0);
+
+	if (ret.error) {
+		switch (ret.error) {
+		case SBI_ERR_DENIED:
+			pr_err("%s: Access denied for shared memory.\n",
+			       __func__);
+			break;
+
+		case SBI_ERR_INVALID_PARAM:
+		case SBI_ERR_INVALID_ADDRESS:
+			pr_err("%s: Invalid address parameter (%lu)\n",
+			       __func__, ret.error);
+			break;
+
+		case SBI_ERR_ALREADY_AVAILABLE:
+			pr_err("%s: Shared memory is already set\n",
+			       __func__);

arch/riscv/kernel/hw_breakpoint.c line 161

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+			break;
+		case SBI_ERR_FAILURE:
+			pr_err("%s: Internal sdtrig state error\n",
+			       __func__);
+			break;
+		default:
+			pr_err("%s: Unknown error %lu\n", __func__, ret.error);
+			break;
+		}
+	}

Ditto

Quoted 27 lines
arch/riscv/kernel/hw_breakpoint.c new file +27 -0
+
+	pr_debug("CPU %d: HW Breakpoint shared memory disabled.\n", cpu);
+
+	return 0;
+}
+
+static void init_sbi_dbtr(void)
+{
+	struct sbiret ret;
+
+	/*
+	 * Called by hw_breakpoint_slots and arch_hw_breakpoint_init.
+	 * Only proceed if this is the first CPU to reach this code.
+	 */
+	if (test_and_set_bit(0, &dbtr_init))
+		return;
+
+	if (sbi_probe_extension(SBI_EXT_DBTR) <= 0) {
+		pr_debug("%s: SBI_EXT_DBTR is not supported\n", __func__);
+		dbtr_total_num = 0;
+		return;
+	}
+
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+			DBTR_TDATA1_TYPE_MCONTROL6, 0, 0, 0, 0, 0);
+	if (ret.error) {
+		pr_warn("%s: failed to detect mcontrol6 triggers. error: %ld.\n",

arch/riscv/kernel/hw_breakpoint.c line 198

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+			__func__, ret.error);
+	} else if (!ret.value) {
+		pr_warn("%s: No mcontrol6 triggers available.\n", __func__);
+	} else {
+		dbtr_total_num = ret.value;
+		dbtr_type = DBTR_TDATA1_TYPE_MCONTROL6;
+		return;
+	}
+
+	/* fallback to legacy mcontrol triggers if mcontrol6 is not available */

Nit: Since all other comments starts with a capital letter, I'd suggest using a capital F (Fallback).

Quoted 51 lines
arch/riscv/kernel/hw_breakpoint.c new file +51 -0
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+			DBTR_TDATA1_TYPE_MCONTROL, 0, 0, 0, 0, 0);
+	if (ret.error) {
+		pr_warn("%s: failed to detect mcontrol triggers. error: %ld.\n",
+			__func__, ret.error);
+	} else if (!ret.value) {
+		pr_err("%s: No mcontrol triggers available.\n", __func__);
+		dbtr_total_num = 0;
+	} else {
+		dbtr_total_num = ret.value;
+		dbtr_type = DBTR_TDATA1_TYPE_MCONTROL;
+	}
+}
+
+int hw_breakpoint_slots(int type)
+{
+	/*
+	 * We can be called early, so don't rely on
+	 * static variables being initialised.
+	 */
+	init_sbi_dbtr();
+
+	return dbtr_total_num;
+}
+
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw)
+{
+	unsigned int len;
+	unsigned long va;
+
+	va = hw->address;
+	len = hw->len;
+
+	return (va >= TASK_SIZE) && ((va + len - 1) >= TASK_SIZE);
+}
+
+static int rv_init_mcontrol_trigger(const struct perf_event_attr *attr,
+				    struct arch_hw_breakpoint *hw)
+{
+	unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+	switch (attr->bp_type) {
+	case HW_BREAKPOINT_X:
+		tdata1 |= DBTR_TDATA1_MCONTROL_EXECUTE;
+		break;
+	case HW_BREAKPOINT_R:
+		tdata1 |= DBTR_TDATA1_MCONTROL_LOAD;
+		break;
+	case HW_BREAKPOINT_W:
+		tdata1 |= DBTR_TDATA1_MCONTROL_STORE;
+		break;

arch/riscv/kernel/hw_breakpoint.c line 259

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+	case HW_BREAKPOINT_RW:
+		tdata1 |= DBTR_TDATA1_MCONTROL_STORE | DBTR_TDATA1_MCONTROL_LOAD;
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	switch (attr->bp_len) {
+	case HW_BREAKPOINT_LEN_1:
+		hw->len = 1;

You can probably add a define for that to avoid

#define TDATA1(lo, hi) \
	FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD, \
		   DBTR_TDATA1_MCONTROL_SIZELO_64BIT) | \
	FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZEHI_FIELD, \
		   DBTR_TDATA1_MCONTROL_SIZEHI_64BIT);

arch/riscv/kernel/hw_breakpoint.c line 261

Quoted 2 lines
arch/riscv/kernel/hw_breakpoint.c new file +2 -0
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+				     DBTR_TDATA1_MCONTROL_SIZELO_8BIT);
		tdata1 |= TDATA1(DBTR_TDATA1_MCONTROL_SIZELO_8BIT, 0);

arch/riscv/kernel/hw_breakpoint.c line 266

Quoted 5 lines
arch/riscv/kernel/hw_breakpoint.c new file +5 -0
+		break;
+	case HW_BREAKPOINT_LEN_2:
+		hw->len = 2;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+				     DBTR_TDATA1_MCONTROL_SIZELO_16BIT);
		tdata1 |= TDATA1(DBTR_TDATA1_MCONTROL_SIZELO_16BIT, 0);

arch/riscv/kernel/hw_breakpoint.c line 271

Quoted 5 lines
arch/riscv/kernel/hw_breakpoint.c new file +5 -0
+		break;
+	case HW_BREAKPOINT_LEN_4:
+		hw->len = 4;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+				     DBTR_TDATA1_MCONTROL_SIZELO_32BIT);
		tdata1 |= TDATA1(DBTR_TDATA1_MCONTROL_SIZELO_32BIT, 0);

arch/riscv/kernel/hw_breakpoint.c line 279

Quoted 8 lines
arch/riscv/kernel/hw_breakpoint.c new file +8 -0
+		break;
+#if __riscv_xlen >= 64
+	case HW_BREAKPOINT_LEN_8:
+		hw->len = 8;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+				     DBTR_TDATA1_MCONTROL_SIZELO_64BIT) |
+			  FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZEHI_FIELD,
+				     DBTR_TDATA1_MCONTROL_SIZEHI_64BIT);
		tdata1 |= TDATA1(DBTR_TDATA1_MCONTROL_SIZELO_64BIT,

DBTR_TDATA1_MCONTROL_SIZEHI_64BIT);

Quoted 88 lines
arch/riscv/kernel/hw_breakpoint.c new file +88 -0
+		break;
+#endif
+	default:
+		return -EINVAL;
+	}
+
+	tdata1 |= DBTR_TDATA1_MCONTROL_U;
+
+	hw->tdata1 = tdata1;
+
+	return 0;
+}
+
+static int rv_init_mcontrol6_trigger(const struct perf_event_attr *attr,
+				     struct arch_hw_breakpoint *hw)
+{
+	unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+	switch (attr->bp_type) {
+	case HW_BREAKPOINT_X:
+		tdata1 |= DBTR_TDATA1_MCONTROL6_EXECUTE;
+		break;
+	case HW_BREAKPOINT_R:
+		tdata1 |= DBTR_TDATA1_MCONTROL6_LOAD;
+		break;
+	case HW_BREAKPOINT_W:
+		tdata1 |= DBTR_TDATA1_MCONTROL6_STORE;
+		break;
+	case HW_BREAKPOINT_RW:
+		tdata1 |= DBTR_TDATA1_MCONTROL6_STORE | DBTR_TDATA1_MCONTROL6_LOAD;
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	switch (attr->bp_len) {
+	case HW_BREAKPOINT_LEN_1:
+		hw->len = 1;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+				     DBTR_TDATA1_MCONTROL6_SIZE_8BIT);
+		break;
+	case HW_BREAKPOINT_LEN_2:
+		hw->len = 2;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+				     DBTR_TDATA1_MCONTROL6_SIZE_16BIT);
+		break;
+	case HW_BREAKPOINT_LEN_4:
+		hw->len = 4;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+				     DBTR_TDATA1_MCONTROL6_SIZE_32BIT);
+		break;
+	case HW_BREAKPOINT_LEN_8:
+		hw->len = 8;
+		tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+				     DBTR_TDATA1_MCONTROL6_SIZE_64BIT);
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	tdata1 |= DBTR_TDATA1_MCONTROL6_U;
+
+	hw->tdata1 = tdata1;
+
+	return 0;
+}
+
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+			     const struct perf_event_attr *attr,
+			     struct arch_hw_breakpoint *hw)
+{
+	int ret;
+
+	/* Breakpoint address */
+	hw->address = attr->bp_addr;
+	hw->tdata2 = attr->bp_addr;
+	hw->tdata3 = 0x0;
+	hw->next_addr = 0x0;
+	hw->in_callback = false;
+
+	switch (dbtr_type) {
+	case DBTR_TDATA1_TYPE_MCONTROL:
+		ret = rv_init_mcontrol_trigger(attr, hw);
+		break;
+	case DBTR_TDATA1_TYPE_MCONTROL6:
+		ret = rv_init_mcontrol6_trigger(attr, hw);
+		break;
+	default:

arch/riscv/kernel/hw_breakpoint.c line 377

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+		pr_warn("Unsupported trigger type %lu.\n", dbtr_type >> DBTR_TDATA1_TYPE_SHIFT);
+		ret = -EOPNOTSUPP;
+		break;
+	}
+
+	return ret;
+}
+
+/*
+ * Set breakpoint to next insruction after breakpoint.

Typo: instruction

Quoted 200 lines
arch/riscv/kernel/hw_breakpoint.c new file +200 -0
+ * Returns 0 if success
+ * Returns < 0 on error
+ */
+static int setup_singlestep(struct perf_event *event, struct pt_regs *regs)
+{
+	struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+	struct arch_hw_breakpoint old_hw_bp;
+	struct perf_event_attr bp_insn;
+	unsigned long next_addr, insn;
+	int ret;
+
+	/* Remove breakpoint even if return error as not to loop */
+	arch_uninstall_hw_breakpoint(event);
+
+	ret = get_insn(regs, regs->epc, &insn);
+	if (ret < 0)
+		return ret;
+
+	next_addr = get_step_address(regs, insn);
+
+	ret = get_insn(regs, next_addr, &insn);
+	if (ret < 0)
+		return ret;
+
+	bp_insn.bp_type = HW_BREAKPOINT_X;
+	bp_insn.bp_addr = next_addr;
+	/* Get the size of the intruction */
+	bp_insn.bp_len = GET_INSN_LENGTH(insn);
+
+	ret = hw_breakpoint_arch_parse(NULL, &bp_insn, bp);
+	if (ret)
+		return ret;
+
+	ret = arch_install_hw_breakpoint(event);
+	if (ret)
+		return ret;
+
+	bp->in_callback = true;
+	bp->next_addr = next_addr;
+	return 0;
+}
+
+/*
+ * HW Breakpoint/watchpoint handler
+ */
+static int hw_breakpoint_handler(struct pt_regs *regs)
+{
+	struct perf_event *event;
+	struct arch_hw_breakpoint *bp;
+	int ret, i;
+
+	for (i = 0; i < dbtr_total_num; i++) {
+		event = this_cpu_read(pcpu_hw_bp_events[i]);
+		if (!event)
+			continue;
+
+		bp = counter_arch_bp(event);
+		if (bp->in_callback) {
+			/* Reset changed breakpoint data */
+			bp->in_callback = false;
+			if (regs->epc == bp->next_addr) {
+				arch_uninstall_hw_breakpoint(event);
+				/* Restore original breakpoint */
+				if (hw_breakpoint_arch_parse(NULL, &event->attr, bp))
+					return NOTIFY_DONE;
+				if (arch_install_hw_breakpoint(event))
+					return NOTIFY_DONE;
+				return NOTIFY_STOP;
+			}
+
+			pr_err("%s: in_callback was set, but epc(%lx) was not next "
+				 "address(%lx).\n", __func__, regs->epc, bp->next_addr);
+			bp->next_addr = 0x0;
+			return NOTIFY_DONE;
+		}
+
+		switch (event->attr.bp_type) {
+		/* Breakpoint */
+		case HW_BREAKPOINT_X:
+			if (event->attr.bp_addr == regs->epc) {
+				ret = setup_singlestep(event, regs);
+				if (ret < 0) {
+					pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+					return NOTIFY_DONE;
+				}
+
+				perf_bp_event(event, regs);
+				return NOTIFY_STOP;
+			}
+			break;
+
+		/* Watchpoint */
+		case HW_BREAKPOINT_W:
+		case HW_BREAKPOINT_R:
+		case HW_BREAKPOINT_RW:
+			if (event->attr.bp_addr == regs->badaddr) {
+				ret = setup_singlestep(event, regs);
+				if (ret < 0) {
+					pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+					return NOTIFY_DONE;
+				}
+
+				perf_bp_event(event, regs);
+				return NOTIFY_STOP;
+			}
+			break;
+
+		default:
+			pr_warn("%s: Unknown type: %u\n", __func__, event->attr.bp_type);
+			break;
+		}
+	}
+
+	return NOTIFY_DONE;
+}
+
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+				    unsigned long val, void *data)
+{
+	struct die_args *args = data;
+
+	if (val != DIE_DEBUG)
+		return NOTIFY_DONE;
+
+	return hw_breakpoint_handler(args->regs);
+}
+
+/* atomic: counter->ctx->lock is held */
+int arch_install_hw_breakpoint(struct perf_event *event)
+{
+	struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+	union sbi_dbtr_shmem_entry *shmem = this_cpu_ptr(&sbi_dbtr_shmem);
+	struct sbi_dbtr_data_msg *xmit;
+	struct sbi_dbtr_id_msg *recv;
+	struct perf_event **slot;
+	unsigned long idx;
+	struct sbiret ret;
+	int err = 0;
+
+	raw_spin_lock_irqsave(this_cpu_ptr(&ecall_lock),
+			      *this_cpu_ptr(&ecall_lock_flags));
+
+	xmit = &shmem->data;
+	recv = &shmem->id;
+	xmit->tdata1 = cpu_to_le(bp->tdata1);
+	xmit->tdata2 = cpu_to_le(bp->tdata2);
+	xmit->tdata3 = cpu_to_le(bp->tdata3);
+
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_INSTALL,
+			1, 0, 0, 0, 0, 0);
+
+	if (ret.error) {
+		pr_warn("%s: failed to install trigger. error: %ld\n", __func__, ret.error);
+		err = sbi_err_map_linux_errno(ret.error);
+		goto done;
+	}
+
+	idx = le_to_cpu(recv->idx);
+	if (idx >= dbtr_total_num) {
+		pr_warn("%s: invalid trigger index %lu\n", __func__, idx);
+		err = -EINVAL;
+		goto done;
+	}
+
+	slot = this_cpu_ptr(&pcpu_hw_bp_events[idx]);
+	if (*slot) {
+		pr_warn("%s: slot %lu is in use\n", __func__, idx);
+		err = -EBUSY;
+		goto done;
+	}
+
+	pr_debug("Trigger 0x%lx installed at index 0x%lx\n", bp->tdata2, idx);
+
+	/* Save the event - to be looked up in handler */
+	*slot = event;
+
+done:
+	raw_spin_unlock_irqrestore(this_cpu_ptr(&ecall_lock),
+				   *this_cpu_ptr(&ecall_lock_flags));
+	return err;
+}
+
+/* atomic: counter->ctx->lock is held */
+void arch_uninstall_hw_breakpoint(struct perf_event *event)
+{
+	struct sbiret ret;
+	int i;
+
+	for (i = 0; i < dbtr_total_num; i++) {
+		struct perf_event **slot = this_cpu_ptr(&pcpu_hw_bp_events[i]);
+
+		if (*slot == event) {
+			*slot = NULL;
+			break;
+		}
+	}
+
+
+	if (i == dbtr_total_num) {
+		pr_warn("%s: Breakpoint not installed.\n", __func__);

arch/riscv/kernel/hw_breakpoint.c line 587

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+		return;
+	}
+
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_UNINSTALL,
+			i, 1, 0, 0, 0, 0);
+	if (ret.error)
+		pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
+}
+
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }

Is there nothing to do to remove the registered breakpoints ? All other architecture seems to implement it.

Quoted 50 lines
arch/riscv/kernel/hw_breakpoint.c new file +33 -0
+
+void hw_breakpoint_pmu_read(struct perf_event *bp) { }
+
+static int __init arch_hw_breakpoint_init(void)
+{
+	unsigned int cpu;
+	int rc = 0;
+
+	for_each_possible_cpu(cpu)
+		raw_spin_lock_init(&per_cpu(ecall_lock, cpu));
+
+	init_sbi_dbtr();
+
+	if (dbtr_total_num) {
+		pr_debug("%s: total number of type %lu triggers: %u\n",
+			__func__, dbtr_type >> DBTR_TDATA1_TYPE_SHIFT, dbtr_total_num);
+	} else {
+		pr_debug("%s: No hardware triggers available\n", __func__);
+		return rc;
+	}
+
+	/* Hotplug handler to register/unregister shared memory with SBI */
+	rc = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN,
+			       "riscv/hw_breakpoint:prepare",
+			       arch_smp_setup_sbi_shmem,
+			       arch_smp_teardown_sbi_shmem);
+
+	if (rc < 0)
+		pr_warn("%s: Failed to setup CPU hotplug state\n", __func__);
+
+	return rc;
+}
+arch_initcall(arch_hw_breakpoint_init);
arch/riscv/kernel/traps.c +6 -0
index 938a8b841f94..2ac471ec79a8 100644
@@ -289,6 +289,12 @@ void handle_break(struct pt_regs *regs)
 	if (probe_breakpoint_handler(regs))
 		return;
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+	if (notify_die(DIE_DEBUG, "EBREAK", regs, 0, regs->cause, SIGTRAP)
+	    == NOTIFY_STOP)
+		return;
+#endif
+
 	current->thread.bad_cause = regs->cause;
 
 	if (user_mode(regs))
#10 lore raw

Re: [RFC PATCH 4/6] riscv: Introduce support for hardware break/watchpoints

Quoted 273 lines · Clément Léger
Quoted 256 lines · Jesse Taube

From: Himanshu Chauhan <[email protected]>

RISC-V hardware breakpoint framework is built on top of perf subsystem and uses SBI debug trigger extension to install/uninstall/update/enable/disable hardware triggers as specified in Sdtrig ISA extension.

---
 arch/riscv/Kconfig                     |   1 +
 arch/riscv/include/asm/hw_breakpoint.h |  60 +++
 arch/riscv/include/asm/kdebug.h        |   3 +-
 arch/riscv/include/asm/sbi.h           |   4 +-
 arch/riscv/kernel/Makefile             |   1 +
 arch/riscv/kernel/hw_breakpoint.c      | 620 +++++++++++++++++++++++++
 arch/riscv/kernel/traps.c              |   6 +
 7 files changed, 693 insertions(+), 2 deletions(-)
 create mode 100644 arch/riscv/include/asm/hw_breakpoint.h
 create mode 100644 arch/riscv/kernel/hw_breakpoint.c
arch/riscv/Kconfig +1 -0
index bbec87b79309..95d3047cab10 100644
@@ -163,6 +163,7 @@ config RISCV
      select HAVE_FUNCTION_ERROR_INJECTION
      select HAVE_GCC_PLUGINS
      select HAVE_GENERIC_VDSO if MMU && 64BIT
+     select HAVE_HW_BREAKPOINT if PERF_EVENTS && RISCV_SBI
      select HAVE_IRQ_TIME_ACCOUNTING
      select HAVE_KERNEL_BZIP2 if !XIP_KERNEL && !EFI_ZBOOT
      select HAVE_KERNEL_GZIP if !XIP_KERNEL && !EFI_ZBOOT
arch/riscv/include/asm/hw_breakpoint.h new file +60 -0
new file mode 100644
index 000000000000..8efa3921c535
@@ -0,0 +1,60 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#ifndef __RISCV_HW_BREAKPOINT_H
+#define __RISCV_HW_BREAKPOINT_H
+
+struct task_struct;
+
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+
+#include <uapi/linux/hw_breakpoint.h>
+
+#if __riscv_xlen == 64
+#define cpu_to_le cpu_to_le64
+#define le_to_cpu le64_to_cpu
+#elif __riscv_xlen == 32
+#define cpu_to_le cpu_to_le32
+#define le_to_cpu le32_to_cpu
+#else
+#error "Unexpected __riscv_xlen"
+#endif
+
+struct arch_hw_breakpoint {
+     unsigned long address;
+     unsigned long len;
+
+     /* Callback info */
+     unsigned long next_addr;
+     bool in_callback;
+
+
+     /* Trigger configuration data */
+     unsigned long tdata1;
+     unsigned long tdata2;
+     unsigned long tdata3;
+};
+
+/* Maximum number of hardware breakpoints supported */
+#define RV_MAX_TRIGGERS 32
+
+struct perf_event_attr;
+struct notifier_block;
+struct perf_event;
+struct pt_regs;
+
+int hw_breakpoint_slots(int type);
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw);
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+                          const struct perf_event_attr *attr,
+                          struct arch_hw_breakpoint *hw);
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+                                 unsigned long val, void *data);
+int arch_install_hw_breakpoint(struct perf_event *bp);
+void arch_uninstall_hw_breakpoint(struct perf_event *bp);
+void hw_breakpoint_pmu_read(struct perf_event *bp);
+
+#endif /* CONFIG_HAVE_HW_BREAKPOINT */
+#endif /* __RISCV_HW_BREAKPOINT_H */
arch/riscv/include/asm/kdebug.h +2 -1
index 85ac00411f6e..53e989781aa1 100644
@@ -6,7 +6,8 @@
 enum die_val {
      DIE_UNUSED,
      DIE_TRAP,
-     DIE_OOPS
+     DIE_OOPS,
+     DIE_DEBUG
 };
 
 #endif
arch/riscv/include/asm/sbi.h +3 -1
index be2ca8e8a49e..64fa7a82aa45 100644
@@ -282,7 +282,9 @@ struct sbi_sta_struct {
      u8 pad[47];
 } __packed;
 
-#define SBI_SHMEM_DISABLE            -1
+#define SBI_SHMEM_DISABLE    (-1UL)
+#define SBI_SHMEM_LO(pa)     ((unsigned long)lower_32_bits(pa))
+#define SBI_SHMEM_HI(pa)     ((unsigned long)upper_32_bits(pa))
 
 enum sbi_ext_nacl_fid {
      SBI_EXT_NACL_PROBE_FEATURE = 0x0,
arch/riscv/kernel/Makefile +1 -0
index 4f719b09e5ad..3e72505734bd 100644
@@ -99,6 +99,7 @@ obj-$(CONFIG_DYNAMIC_FTRACE)        += mcount-dyn.o
 
 obj-$(CONFIG_PERF_EVENTS)    += perf_callchain.o
 obj-$(CONFIG_HAVE_PERF_REGS) += perf_regs.o
+obj-$(CONFIG_HAVE_HW_BREAKPOINT)     += hw_breakpoint.o
 obj-$(CONFIG_RISCV_SBI)              += sbi.o sbi_ecall.o
 ifeq ($(CONFIG_RISCV_SBI), y)
 obj-$(CONFIG_SMP)            += sbi-ipi.o
arch/riscv/kernel/hw_breakpoint.c new file +111 -0
new file mode 100644
index 000000000000..9e3a3b82d300
@@ -0,0 +1,620 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Copyright (C) 2024 Ventana Micro Systems Inc.
+ */
+
+#include <linux/hw_breakpoint.h>
+#include <linux/perf_event.h>
+#include <linux/spinlock.h>
+#include <linux/percpu.h>
+#include <linux/kdebug.h>
+#include <linux/bitops.h>
+#include <linux/bitfield.h>
+#include <linux/cpu.h>
+#include <linux/cpuhotplug.h>
+
+#include <asm/insn.h>
+#include <asm/sbi.h>
+
+#define DBTR_TDATA1_TYPE_SHIFT               (__riscv_xlen - 4)
+#define DBTR_TDATA1_DMODE            BIT_UL(__riscv_xlen - 5)
+
+#define DBTR_TDATA1_TYPE_MCONTROL    (2UL << DBTR_TDATA1_TYPE_SHIFT)
+#define DBTR_TDATA1_TYPE_MCONTROL6   (6UL << DBTR_TDATA1_TYPE_SHIFT)
+
+#define DBTR_TDATA1_MCONTROL6_LOAD           BIT(0)
+#define DBTR_TDATA1_MCONTROL6_STORE          BIT(1)
+#define DBTR_TDATA1_MCONTROL6_EXECUTE                BIT(2)
+#define DBTR_TDATA1_MCONTROL6_U                      BIT(3)
+#define DBTR_TDATA1_MCONTROL6_S                      BIT(4)
+#define DBTR_TDATA1_MCONTROL6_M                      BIT(6)
+#define DBTR_TDATA1_MCONTROL6_SIZE_FIELD     GENMASK(18, 16)
+#define DBTR_TDATA1_MCONTROL6_SELECT         BIT(21)
+#define DBTR_TDATA1_MCONTROL6_VU             BIT(23)
+#define DBTR_TDATA1_MCONTROL6_VS             BIT(24)
+
+#define DBTR_TDATA1_MCONTROL6_SIZE_8BIT              1
+#define DBTR_TDATA1_MCONTROL6_SIZE_16BIT     2
+#define DBTR_TDATA1_MCONTROL6_SIZE_32BIT     3
+#define DBTR_TDATA1_MCONTROL6_SIZE_64BIT     5
+
+#define DBTR_TDATA1_MCONTROL_LOAD            BIT(0)
+#define DBTR_TDATA1_MCONTROL_STORE           BIT(1)
+#define DBTR_TDATA1_MCONTROL_EXECUTE         BIT(2)
+#define DBTR_TDATA1_MCONTROL_U                       BIT(3)
+#define DBTR_TDATA1_MCONTROL_S                       BIT(4)
+#define DBTR_TDATA1_MCONTROL_M                       BIT(6)
+#define DBTR_TDATA1_MCONTROL_SIZELO_FIELD    GENMASK(17, 16)
+#define DBTR_TDATA1_MCONTROL_SELECT          BIT(19)
+#define DBTR_TDATA1_MCONTROL_SIZEHI_FIELD    GENMASK(22, 21)
+
+#define DBTR_TDATA1_MCONTROL_SIZELO_8BIT     1
+#define DBTR_TDATA1_MCONTROL_SIZELO_16BIT    2
+#define DBTR_TDATA1_MCONTROL_SIZELO_32BIT    3
+/* value of 5 split across HI and LO */
+#define DBTR_TDATA1_MCONTROL_SIZELO_64BIT    1
+#define DBTR_TDATA1_MCONTROL_SIZEHI_64BIT    1
+
+/* Registered per-cpu bp/wp */
+static DEFINE_PER_CPU(struct perf_event *, pcpu_hw_bp_events[RV_MAX_TRIGGERS]);
+static DEFINE_PER_CPU(unsigned long, ecall_lock_flags);
+static DEFINE_PER_CPU(raw_spinlock_t, ecall_lock);
+
+/* Per-cpu shared memory between S and M mode */
+static DEFINE_PER_CPU(union sbi_dbtr_shmem_entry, sbi_dbtr_shmem);
+
+/* number of debug triggers on this cpu . */
+static int dbtr_total_num __ro_after_init;
+static unsigned long dbtr_type __ro_after_init;
+static unsigned long dbtr_init __ro_after_init;
+
+static int arch_smp_setup_sbi_shmem(unsigned int cpu)
+{
+     union sbi_dbtr_shmem_entry *dbtr_shmem;
+     unsigned long shmem_pa;
+     struct sbiret ret;
+     int rc;
+
+     dbtr_shmem = per_cpu_ptr(&sbi_dbtr_shmem, cpu);
+     if (!dbtr_shmem) {
+             pr_err("Invalid per-cpu shared memory for debug triggers\n");
+             return -ENODEV;
+     }
+
+     shmem_pa = virt_to_phys(dbtr_shmem);
+
+     ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+                     SBI_SHMEM_LO(shmem_pa), SBI_SHMEM_HI(shmem_pa), 0, 0, 0, 0);
+
+     if (ret.error) {
+             switch (ret.error) {
+             case SBI_ERR_DENIED:
+                     pr_warn("%s: Access denied for shared memory at %lx\n",
+                             __func__, shmem_pa);
+                     rc = -EPERM;
+                     break;
+
+             case SBI_ERR_INVALID_PARAM:
+             case SBI_ERR_INVALID_ADDRESS:
+                     pr_warn("%s: Invalid address parameter (%ld)\n",
+                             __func__, ret.error);
+                     rc = -EINVAL;
+                     break;
+
+             case SBI_ERR_ALREADY_AVAILABLE:
+                     pr_warn("%s: Shared memory is already set\n",
+                             __func__);
+                     rc = -EADDRINUSE;
+                     break;
+
+             case SBI_ERR_FAILURE:
+                     pr_err("%s: Internal sdtrig state error\n",

arch/riscv/kernel/hw_breakpoint.c line 121

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+                            __func__);
+                     rc = -ENXIO;
+                     break;
+
+             default:
+                     pr_warn("%s: Unknown error %lu\n", __func__, ret.error);
+                     rc = -ENXIO;
+                     break;
+             }
+     }

Hi Jesse,

Quoted 1 line

Is there a reason not to use sbi_err_map_linux_errno() ?

No, I kept this from Himanshu Chauhan's original RFC.
I changed it to:
if (ret.error) {
pr_warn("%s: failed to setup shared memory. error: %ld\n",

__func__, ret.error);
        return sbi_err_map_linux_errno(ret.error);
}
Quoted 148 lines
Quoted 31 lines
arch/riscv/kernel/hw_breakpoint.c new file +30 -0
+
+     pr_debug("CPU %d: HW Breakpoint shared memory registered.\n", cpu);
+
+     return rc;
+}
+
+static int arch_smp_teardown_sbi_shmem(unsigned int cpu)
+{
+     struct sbiret ret;
+
+     /* Disable shared memory */
+     ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_SETUP_SHMEM,
+                     SBI_SHMEM_DISABLE, SBI_SHMEM_DISABLE, 0, 0, 0, 0);
+
+     if (ret.error) {
+             switch (ret.error) {
+             case SBI_ERR_DENIED:
+                     pr_err("%s: Access denied for shared memory.\n",
+                            __func__);
+                     break;
+
+             case SBI_ERR_INVALID_PARAM:
+             case SBI_ERR_INVALID_ADDRESS:
+                     pr_err("%s: Invalid address parameter (%lu)\n",
+                            __func__, ret.error);
+                     break;
+
+             case SBI_ERR_ALREADY_AVAILABLE:
+                     pr_err("%s: Shared memory is already set\n",
+                            __func__);

arch/riscv/kernel/hw_breakpoint.c line 161

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+                     break;
+             case SBI_ERR_FAILURE:
+                     pr_err("%s: Internal sdtrig state error\n",
+                            __func__);
+                     break;
+             default:
+                     pr_err("%s: Unknown error %lu\n", __func__, ret.error);
+                     break;
+             }
+     }

Ditto

Quoted 27 lines
arch/riscv/kernel/hw_breakpoint.c new file +27 -0
+
+     pr_debug("CPU %d: HW Breakpoint shared memory disabled.\n", cpu);
+
+     return 0;
+}
+
+static void init_sbi_dbtr(void)
+{
+     struct sbiret ret;
+
+     /*
+      * Called by hw_breakpoint_slots and arch_hw_breakpoint_init.
+      * Only proceed if this is the first CPU to reach this code.
+      */
+     if (test_and_set_bit(0, &dbtr_init))
+             return;
+
+     if (sbi_probe_extension(SBI_EXT_DBTR) <= 0) {
+             pr_debug("%s: SBI_EXT_DBTR is not supported\n", __func__);
+             dbtr_total_num = 0;
+             return;
+     }
+
+     ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+                     DBTR_TDATA1_TYPE_MCONTROL6, 0, 0, 0, 0, 0);
+     if (ret.error) {
+             pr_warn("%s: failed to detect mcontrol6 triggers. error: %ld.\n",

arch/riscv/kernel/hw_breakpoint.c line 198

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+                     __func__, ret.error);
+     } else if (!ret.value) {
+             pr_warn("%s: No mcontrol6 triggers available.\n", __func__);
+     } else {
+             dbtr_total_num = ret.value;
+             dbtr_type = DBTR_TDATA1_TYPE_MCONTROL6;
+             return;
+     }
+
+     /* fallback to legacy mcontrol triggers if mcontrol6 is not available */

Nit: Since all other comments starts with a capital letter, I'd suggest using a capital F (Fallback).

Quoted 51 lines
arch/riscv/kernel/hw_breakpoint.c new file +51 -0
+     ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+                     DBTR_TDATA1_TYPE_MCONTROL, 0, 0, 0, 0, 0);
+     if (ret.error) {
+             pr_warn("%s: failed to detect mcontrol triggers. error: %ld.\n",
+                     __func__, ret.error);
+     } else if (!ret.value) {
+             pr_err("%s: No mcontrol triggers available.\n", __func__);
+             dbtr_total_num = 0;
+     } else {
+             dbtr_total_num = ret.value;
+             dbtr_type = DBTR_TDATA1_TYPE_MCONTROL;
+     }
+}
+
+int hw_breakpoint_slots(int type)
+{
+     /*
+      * We can be called early, so don't rely on
+      * static variables being initialised.
+      */
+     init_sbi_dbtr();
+
+     return dbtr_total_num;
+}
+
+int arch_check_bp_in_kernelspace(struct arch_hw_breakpoint *hw)
+{
+     unsigned int len;
+     unsigned long va;
+
+     va = hw->address;
+     len = hw->len;
+
+     return (va >= TASK_SIZE) && ((va + len - 1) >= TASK_SIZE);
+}
+
+static int rv_init_mcontrol_trigger(const struct perf_event_attr *attr,
+                                 struct arch_hw_breakpoint *hw)
+{
+     unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+     switch (attr->bp_type) {
+     case HW_BREAKPOINT_X:
+             tdata1 |= DBTR_TDATA1_MCONTROL_EXECUTE;
+             break;
+     case HW_BREAKPOINT_R:
+             tdata1 |= DBTR_TDATA1_MCONTROL_LOAD;
+             break;
+     case HW_BREAKPOINT_W:
+             tdata1 |= DBTR_TDATA1_MCONTROL_STORE;
+             break;

arch/riscv/kernel/hw_breakpoint.c line 259

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+     case HW_BREAKPOINT_RW:
+             tdata1 |= DBTR_TDATA1_MCONTROL_STORE | DBTR_TDATA1_MCONTROL_LOAD;
+             break;
+     default:
+             return -EINVAL;
+     }
+
+     switch (attr->bp_len) {
+     case HW_BREAKPOINT_LEN_1:
+             hw->len = 1;

You can probably add a define for that to avoid

Quoted 5 lines
#define TDATA1(lo, hi) \
        FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD, \
                   DBTR_TDATA1_MCONTROL_SIZELO_64BIT) | \
        FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZEHI_FIELD, \
                   DBTR_TDATA1_MCONTROL_SIZEHI_64BIT);

Good idea! I changed the name to TDATA1_MCTRL_SZ and also added TDATA1_MCTRL6_SZ

Quoted 341 lines

arch/riscv/kernel/hw_breakpoint.c line 261

Quoted 3 lines
arch/riscv/kernel/hw_breakpoint.c new file +2 -0
+             tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                  DBTR_TDATA1_MCONTROL_SIZELO_8BIT);
                tdata1 |= TDATA1(DBTR_TDATA1_MCONTROL_SIZELO_8BIT, 0);

arch/riscv/kernel/hw_breakpoint.c line 266

Quoted 5 lines
arch/riscv/kernel/hw_breakpoint.c new file +5 -0
+             break;
+     case HW_BREAKPOINT_LEN_2:
+             hw->len = 2;
+             tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                  DBTR_TDATA1_MCONTROL_SIZELO_16BIT);
                tdata1 |= TDATA1(DBTR_TDATA1_MCONTROL_SIZELO_16BIT, 0);

arch/riscv/kernel/hw_breakpoint.c line 271

Quoted 5 lines
arch/riscv/kernel/hw_breakpoint.c new file +5 -0
+             break;
+     case HW_BREAKPOINT_LEN_4:
+             hw->len = 4;
+             tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                  DBTR_TDATA1_MCONTROL_SIZELO_32BIT);
                tdata1 |= TDATA1(DBTR_TDATA1_MCONTROL_SIZELO_32BIT, 0);

arch/riscv/kernel/hw_breakpoint.c line 279

Quoted 8 lines
arch/riscv/kernel/hw_breakpoint.c new file +8 -0
+             break;
+#if __riscv_xlen >= 64
+     case HW_BREAKPOINT_LEN_8:
+             hw->len = 8;
+             tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZELO_FIELD,
+                                  DBTR_TDATA1_MCONTROL_SIZELO_64BIT) |
+                       FIELD_PREP(DBTR_TDATA1_MCONTROL_SIZEHI_FIELD,
+                                  DBTR_TDATA1_MCONTROL_SIZEHI_64BIT);
                tdata1 |= TDATA1(DBTR_TDATA1_MCONTROL_SIZELO_64BIT,

DBTR_TDATA1_MCONTROL_SIZEHI_64BIT);

Quoted 88 lines
arch/riscv/kernel/hw_breakpoint.c new file +88 -0
+             break;
+#endif
+     default:
+             return -EINVAL;
+     }
+
+     tdata1 |= DBTR_TDATA1_MCONTROL_U;
+
+     hw->tdata1 = tdata1;
+
+     return 0;
+}
+
+static int rv_init_mcontrol6_trigger(const struct perf_event_attr *attr,
+                                  struct arch_hw_breakpoint *hw)
+{
+     unsigned long tdata1 = DBTR_TDATA1_TYPE_MCONTROL;
+
+     switch (attr->bp_type) {
+     case HW_BREAKPOINT_X:
+             tdata1 |= DBTR_TDATA1_MCONTROL6_EXECUTE;
+             break;
+     case HW_BREAKPOINT_R:
+             tdata1 |= DBTR_TDATA1_MCONTROL6_LOAD;
+             break;
+     case HW_BREAKPOINT_W:
+             tdata1 |= DBTR_TDATA1_MCONTROL6_STORE;
+             break;
+     case HW_BREAKPOINT_RW:
+             tdata1 |= DBTR_TDATA1_MCONTROL6_STORE | DBTR_TDATA1_MCONTROL6_LOAD;
+             break;
+     default:
+             return -EINVAL;
+     }
+
+     switch (attr->bp_len) {
+     case HW_BREAKPOINT_LEN_1:
+             hw->len = 1;
+             tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                  DBTR_TDATA1_MCONTROL6_SIZE_8BIT);
+             break;
+     case HW_BREAKPOINT_LEN_2:
+             hw->len = 2;
+             tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                  DBTR_TDATA1_MCONTROL6_SIZE_16BIT);
+             break;
+     case HW_BREAKPOINT_LEN_4:
+             hw->len = 4;
+             tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                  DBTR_TDATA1_MCONTROL6_SIZE_32BIT);
+             break;
+     case HW_BREAKPOINT_LEN_8:
+             hw->len = 8;
+             tdata1 |= FIELD_PREP(DBTR_TDATA1_MCONTROL6_SIZE_FIELD,
+                                  DBTR_TDATA1_MCONTROL6_SIZE_64BIT);
+             break;
+     default:
+             return -EINVAL;
+     }
+
+     tdata1 |= DBTR_TDATA1_MCONTROL6_U;
+
+     hw->tdata1 = tdata1;
+
+     return 0;
+}
+
+int hw_breakpoint_arch_parse(struct perf_event *bp,
+                          const struct perf_event_attr *attr,
+                          struct arch_hw_breakpoint *hw)
+{
+     int ret;
+
+     /* Breakpoint address */
+     hw->address = attr->bp_addr;
+     hw->tdata2 = attr->bp_addr;
+     hw->tdata3 = 0x0;
+     hw->next_addr = 0x0;
+     hw->in_callback = false;
+
+     switch (dbtr_type) {
+     case DBTR_TDATA1_TYPE_MCONTROL:
+             ret = rv_init_mcontrol_trigger(attr, hw);
+             break;
+     case DBTR_TDATA1_TYPE_MCONTROL6:
+             ret = rv_init_mcontrol6_trigger(attr, hw);
+             break;
+     default:

arch/riscv/kernel/hw_breakpoint.c line 377

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c new file +10 -0
+             pr_warn("Unsupported trigger type %lu.\n", dbtr_type >> DBTR_TDATA1_TYPE_SHIFT);
+             ret = -EOPNOTSUPP;
+             break;
+     }
+
+     return ret;
+}
+
+/*
+ * Set breakpoint to next insruction after breakpoint.

Typo: instruction

Quoted 205 lines
arch/riscv/kernel/hw_breakpoint.c new file +205 -0
+ * Returns 0 if success
+ * Returns < 0 on error
+ */
+static int setup_singlestep(struct perf_event *event, struct pt_regs *regs)
+{
+     struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+     struct arch_hw_breakpoint old_hw_bp;
+     struct perf_event_attr bp_insn;
+     unsigned long next_addr, insn;
+     int ret;
+
+     /* Remove breakpoint even if return error as not to loop */
+     arch_uninstall_hw_breakpoint(event);
+
+     ret = get_insn(regs, regs->epc, &insn);
+     if (ret < 0)
+             return ret;
+
+     next_addr = get_step_address(regs, insn);
+
+     ret = get_insn(regs, next_addr, &insn);
+     if (ret < 0)
+             return ret;
+
+     bp_insn.bp_type = HW_BREAKPOINT_X;
+     bp_insn.bp_addr = next_addr;
+     /* Get the size of the intruction */
+     bp_insn.bp_len = GET_INSN_LENGTH(insn);
+
+     ret = hw_breakpoint_arch_parse(NULL, &bp_insn, bp);
+     if (ret)
+             return ret;
+
+     ret = arch_install_hw_breakpoint(event);
+     if (ret)
+             return ret;
+
+     bp->in_callback = true;
+     bp->next_addr = next_addr;
+     return 0;
+}
+
+/*
+ * HW Breakpoint/watchpoint handler
+ */
+static int hw_breakpoint_handler(struct pt_regs *regs)
+{
+     struct perf_event *event;
+     struct arch_hw_breakpoint *bp;
+     int ret, i;
+
+     for (i = 0; i < dbtr_total_num; i++) {
+             event = this_cpu_read(pcpu_hw_bp_events[i]);
+             if (!event)
+                     continue;
+
+             bp = counter_arch_bp(event);
+             if (bp->in_callback) {
+                     /* Reset changed breakpoint data */
+                     bp->in_callback = false;
+                     if (regs->epc == bp->next_addr) {
+                             arch_uninstall_hw_breakpoint(event);
+                             /* Restore original breakpoint */
+                             if (hw_breakpoint_arch_parse(NULL, &event->attr, bp))
+                                     return NOTIFY_DONE;
+                             if (arch_install_hw_breakpoint(event))
+                                     return NOTIFY_DONE;
+                             return NOTIFY_STOP;
+                     }
+
+                     pr_err("%s: in_callback was set, but epc(%lx) was not next "
+                              "address(%lx).\n", __func__, regs->epc, bp->next_addr);
+                     bp->next_addr = 0x0;
+                     return NOTIFY_DONE;
+             }
+
+             switch (event->attr.bp_type) {
+             /* Breakpoint */
+             case HW_BREAKPOINT_X:
+                     if (event->attr.bp_addr == regs->epc) {
+                             ret = setup_singlestep(event, regs);
+                             if (ret < 0) {
+                                     pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+                                     return NOTIFY_DONE;
+                             }
+
+                             perf_bp_event(event, regs);
+                             return NOTIFY_STOP;
+                     }
+                     break;
+
+             /* Watchpoint */
+             case HW_BREAKPOINT_W:
+             case HW_BREAKPOINT_R:
+             case HW_BREAKPOINT_RW:
+                     if (event->attr.bp_addr == regs->badaddr) {
+                             ret = setup_singlestep(event, regs);
+                             if (ret < 0) {
+                                     pr_err("%s: setup_singlestep failed %d.\n", __func__, ret);
+                                     return NOTIFY_DONE;
+                             }
+
+                             perf_bp_event(event, regs);
+                             return NOTIFY_STOP;
+                     }
+                     break;
+
+             default:
+                     pr_warn("%s: Unknown type: %u\n", __func__, event->attr.bp_type);
+                     break;
+             }
+     }
+
+     return NOTIFY_DONE;
+}
+
+int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
+                                 unsigned long val, void *data)
+{
+     struct die_args *args = data;
+
+     if (val != DIE_DEBUG)
+             return NOTIFY_DONE;
+
+     return hw_breakpoint_handler(args->regs);
+}
+
+/* atomic: counter->ctx->lock is held */
+int arch_install_hw_breakpoint(struct perf_event *event)
+{
+     struct arch_hw_breakpoint *bp = counter_arch_bp(event);
+     union sbi_dbtr_shmem_entry *shmem = this_cpu_ptr(&sbi_dbtr_shmem);
+     struct sbi_dbtr_data_msg *xmit;
+     struct sbi_dbtr_id_msg *recv;
+     struct perf_event **slot;
+     unsigned long idx;
+     struct sbiret ret;
+     int err = 0;
+
+     raw_spin_lock_irqsave(this_cpu_ptr(&ecall_lock),
+                           *this_cpu_ptr(&ecall_lock_flags));
+
+     xmit = &shmem->data;
+     recv = &shmem->id;
+     xmit->tdata1 = cpu_to_le(bp->tdata1);
+     xmit->tdata2 = cpu_to_le(bp->tdata2);
+     xmit->tdata3 = cpu_to_le(bp->tdata3);
+
+     ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_INSTALL,
+                     1, 0, 0, 0, 0, 0);
+
+     if (ret.error) {
+             pr_warn("%s: failed to install trigger. error: %ld\n", __func__, ret.error);
+             err = sbi_err_map_linux_errno(ret.error);
+             goto done;
+     }
+
+     idx = le_to_cpu(recv->idx);
+     if (idx >= dbtr_total_num) {
+             pr_warn("%s: invalid trigger index %lu\n", __func__, idx);
+             err = -EINVAL;
+             goto done;
+     }
+
+     slot = this_cpu_ptr(&pcpu_hw_bp_events[idx]);
+     if (*slot) {
+             pr_warn("%s: slot %lu is in use\n", __func__, idx);
+             err = -EBUSY;
+             goto done;
+     }
+
+     pr_debug("Trigger 0x%lx installed at index 0x%lx\n", bp->tdata2, idx);
+
+     /* Save the event - to be looked up in handler */
+     *slot = event;
+
+done:
+     raw_spin_unlock_irqrestore(this_cpu_ptr(&ecall_lock),
+                                *this_cpu_ptr(&ecall_lock_flags));
+     return err;
+}
+
+/* atomic: counter->ctx->lock is held */
+void arch_uninstall_hw_breakpoint(struct perf_event *event)
+{
+     struct sbiret ret;
+     int i;
+
+     for (i = 0; i < dbtr_total_num; i++) {
+             struct perf_event **slot = this_cpu_ptr(&pcpu_hw_bp_events[i]);
+
+             if (*slot == event) {
+                     *slot = NULL;
+                     break;
+             }
+     }
+
+
+     if (i == dbtr_total_num) {
+             pr_warn("%s: Breakpoint not installed.\n", __func__);
+             return;
+     }
+
+     ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_TRIG_UNINSTALL,
+                     i, 1, 0, 0, 0, 0);
Quoted 8 lines

arch/riscv/kernel/hw_breakpoint.c line 587

Quoted 5 lines
arch/riscv/kernel/hw_breakpoint.c new file +5 -0
+     if (ret.error)
+             pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
+}
+
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }

Is there nothing to do to remove the registered breakpoints ? All other architecture seems to implement it.

As you noticed in the next patch I did add it. This function is only necessary if adding ptrace support.

Thanks,
Jesse Taube

Quoted 52 lines
Quoted 51 lines
arch/riscv/kernel/hw_breakpoint.c new file +33 -0
+
+void hw_breakpoint_pmu_read(struct perf_event *bp) { }
+
+static int __init arch_hw_breakpoint_init(void)
+{
+     unsigned int cpu;
+     int rc = 0;
+
+     for_each_possible_cpu(cpu)
+             raw_spin_lock_init(&per_cpu(ecall_lock, cpu));
+
+     init_sbi_dbtr();
+
+     if (dbtr_total_num) {
+             pr_debug("%s: total number of type %lu triggers: %u\n",
+                     __func__, dbtr_type >> DBTR_TDATA1_TYPE_SHIFT, dbtr_total_num);
+     } else {
+             pr_debug("%s: No hardware triggers available\n", __func__);
+             return rc;
+     }
+
+     /* Hotplug handler to register/unregister shared memory with SBI */
+     rc = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN,
+                            "riscv/hw_breakpoint:prepare",
+                            arch_smp_setup_sbi_shmem,
+                            arch_smp_teardown_sbi_shmem);
+
+     if (rc < 0)
+             pr_warn("%s: Failed to setup CPU hotplug state\n", __func__);
+
+     return rc;
+}
+arch_initcall(arch_hw_breakpoint_init);
arch/riscv/kernel/traps.c +6 -0
index 938a8b841f94..2ac471ec79a8 100644
@@ -289,6 +289,12 @@ void handle_break(struct pt_regs *regs)
      if (probe_breakpoint_handler(regs))
              return;
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+     if (notify_die(DIE_DEBUG, "EBREAK", regs, 0, regs->cause, SIGTRAP)
+         == NOTIFY_STOP)
+             return;
+#endif
+
      current->thread.bad_cause = regs->cause;
 
      if (user_mode(regs))
#11 lore raw

RFC PATCH 5/6 riscv: hw_breakpoint: Use icount for single stepping

In reply to Jesse Taube

The Sdtrig RISC-V ISA extension does not have a resume flag for returning to and executing the instruction at the breakpoint. To avoid skipping the instruction or looping, it is necessary to remove the hardware breakpoint and single step. Use the icount feature of Sdtrig to accomplish this. Use icount as default with an option to allow software-based single stepping when hardware or SBI does not have icount functionality, as it may cause unwanted side effects when reading the instruction from memory.

---
 arch/riscv/Kconfig                | 11 +++++
 arch/riscv/kernel/hw_breakpoint.c | 81 +++++++++++++++++++++++++------
 2 files changed, 76 insertions(+), 16 deletions(-)
arch/riscv/Kconfig +11 -0
index 95d3047cab10..bbde5e118470 100644
@@ -1105,6 +1105,17 @@ config PARAVIRT_TIME_ACCOUNTING
 
 	  If in doubt, say N here.
 
+config HW_BREAKPOINT_COMPUTE_STEP
+	bool "Allow computing hardware breakpoint step address"
+	default n
+	depends on HAVE_HW_BREAKPOINT
+	help
+	  Select this option if hardware breakpoints are desired, but
+	  hardware or SBI does not have icount functionality. This may cause
+	  unwanted side affects when reading the instruction from memory.
+
+	  If unsure, say N.
+
 config RELOCATABLE
 	bool "Build a relocatable kernel"
 	depends on !XIP_KERNEL
arch/riscv/kernel/hw_breakpoint.c +65 -16

139 lines not on this page · raw message

Signature · 1 line
2.43.0
#12 lore raw

Re: [RFC PATCH 5/6] riscv: hw_breakpoint: Use icount for single stepping

Quoted 21 lines · Jesse Taube

The Sdtrig RISC-V ISA extension does not have a resume flag for returning to and executing the instruction at the breakpoint. To avoid skipping the instruction or looping, it is necessary to remove the hardware breakpoint and single step. Use the icount feature of Sdtrig to accomplish this. Use icount as default with an option to allow software-based single stepping when hardware or SBI does not have icount functionality, as it may cause unwanted side effects when reading the instruction from memory.

---
 arch/riscv/Kconfig                | 11 +++++
 arch/riscv/kernel/hw_breakpoint.c | 81 +++++++++++++++++++++++++------
 2 files changed, 76 insertions(+), 16 deletions(-)
arch/riscv/Kconfig +0 -0
index 95d3047cab10..bbde5e118470 100644
@@ -1105,6 +1105,17 @@ config PARAVIRT_TIME_ACCOUNTING
 

arch/riscv/Kconfig config PARAVIRT_TIME_ACCOUNTING · line 1115

Quoted 10 lines
arch/riscv/Kconfig +8 -0
 	  If in doubt, say N here.
 
+config HW_BREAKPOINT_COMPUTE_STEP
+	bool "Allow computing hardware breakpoint step address"
+	default n
+	depends on HAVE_HW_BREAKPOINT
+	help
+	  Select this option if hardware breakpoints are desired, but
+	  hardware or SBI does not have icount functionality. This may cause
+	  unwanted side affects when reading the instruction from memory.

Hi Jesse,

Typo: s/affects/effects

Thanks,

Clément

Quoted 158 lines
arch/riscv/Kconfig +3 -0
+
+	  If unsure, say N.
+
 config RELOCATABLE
 	bool "Build a relocatable kernel"
 	depends on !XIP_KERNEL
arch/riscv/kernel/hw_breakpoint.c +65 -16
index 9e3a3b82d300..437fd82b9590 100644
@@ -20,6 +20,7 @@
 #define DBTR_TDATA1_DMODE		BIT_UL(__riscv_xlen - 5)
 
 #define DBTR_TDATA1_TYPE_MCONTROL	(2UL << DBTR_TDATA1_TYPE_SHIFT)
+#define DBTR_TDATA1_TYPE_ICOUNT		(3UL << DBTR_TDATA1_TYPE_SHIFT)
 #define DBTR_TDATA1_TYPE_MCONTROL6	(6UL << DBTR_TDATA1_TYPE_SHIFT)
 
 #define DBTR_TDATA1_MCONTROL6_LOAD		BIT(0)
@@ -55,6 +56,14 @@
 #define DBTR_TDATA1_MCONTROL_SIZELO_64BIT	1
 #define DBTR_TDATA1_MCONTROL_SIZEHI_64BIT	1
 
+#define DBTR_TDATA1_ICOUNT_U			BIT(6)
+#define DBTR_TDATA1_ICOUNT_S			BIT(7)
+#define DBTR_TDATA1_ICOUNT_PENDING		BIT(8)
+#define DBTR_TDATA1_ICOUNT_M			BIT(9)
+#define DBTR_TDATA1_ICOUNT_COUNT_FIELD		GENMASK(23, 10)
+#define DBTR_TDATA1_ICOUNT_VU			BIT(25)
+#define DBTR_TDATA1_ICOUNT_VS			BIT(26)
+
 /* Registered per-cpu bp/wp */
 static DEFINE_PER_CPU(struct perf_event *, pcpu_hw_bp_events[RV_MAX_TRIGGERS]);
 static DEFINE_PER_CPU(unsigned long, ecall_lock_flags);
@@ -65,6 +74,7 @@ static DEFINE_PER_CPU(union sbi_dbtr_shmem_entry, sbi_dbtr_shmem);
 
 /* number of debug triggers on this cpu . */
 static int dbtr_total_num __ro_after_init;
+static bool have_icount __ro_after_init;
 static unsigned long dbtr_type __ro_after_init;
 static unsigned long dbtr_init __ro_after_init;
 
@@ -168,6 +178,7 @@ static int arch_smp_teardown_sbi_shmem(unsigned int cpu)
 static void init_sbi_dbtr(void)
 {
 	struct sbiret ret;
+	unsigned long dbtr_count = 0;
 
 	/*
 	 * Called by hw_breakpoint_slots and arch_hw_breakpoint_init.
@@ -182,6 +193,25 @@ static void init_sbi_dbtr(void)
 		return;
 	}
 
+	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
+		DBTR_TDATA1_TYPE_ICOUNT, 0, 0, 0, 0, 0);
+	if (ret.error) {
+		pr_warn("%s: failed to detect icount triggers. error: %ld.\n",
+			__func__, ret.error);
+	} else if (!ret.value) {
+		if (IS_ENABLED(CONFIG_HW_BREAKPOINT_COMPUTE_STEP)) {
+			pr_warn("%s: No icount triggers available. "
+				"Falling-back to computing single step address.\n", __func__);
+		} else {
+			pr_err("%s: No icount triggers available.\n", __func__);
+			dbtr_total_num = 0;
+			return;
+		}
+	} else {
+		dbtr_count = ret.value;
+		have_icount = true;
+	}
+
 	ret = sbi_ecall(SBI_EXT_DBTR, SBI_EXT_DBTR_NUM_TRIGGERS,
 			DBTR_TDATA1_TYPE_MCONTROL6, 0, 0, 0, 0, 0);
 	if (ret.error) {
@@ -190,7 +220,7 @@ static void init_sbi_dbtr(void)
 	} else if (!ret.value) {
 		pr_warn("%s: No mcontrol6 triggers available.\n", __func__);
 	} else {
-		dbtr_total_num = ret.value;
+		dbtr_total_num = min_not_zero((unsigned long)ret.value, dbtr_count);
 		dbtr_type = DBTR_TDATA1_TYPE_MCONTROL6;
 		return;
 	}
@@ -205,7 +235,7 @@ static void init_sbi_dbtr(void)
 		pr_err("%s: No mcontrol triggers available.\n", __func__);
 		dbtr_total_num = 0;
 	} else {
-		dbtr_total_num = ret.value;
+		dbtr_total_num = min_not_zero((unsigned long)ret.value, dbtr_count);
 		dbtr_type = DBTR_TDATA1_TYPE_MCONTROL;
 	}
 }
@@ -344,6 +374,21 @@ static int rv_init_mcontrol6_trigger(const struct perf_event_attr *attr,
 	return 0;
 }
 
+static int rv_init_icount_trigger(struct arch_hw_breakpoint *hw)
+{
+	unsigned long tdata1 = DBTR_TDATA1_TYPE_ICOUNT;
+
+	/* Step one instruction */
+	tdata1 |= FIELD_PREP(DBTR_TDATA1_ICOUNT_COUNT_FIELD, 1);
+
+	tdata1 |= DBTR_TDATA1_ICOUNT_U;
+
+	hw->tdata1 = tdata1;
+	hw->tdata2 = 0;
+
+	return 0;
+}
+
 int hw_breakpoint_arch_parse(struct perf_event *bp,
 			     const struct perf_event_attr *attr,
 			     struct arch_hw_breakpoint *hw)
@@ -389,24 +434,28 @@ static int setup_singlestep(struct perf_event *event, struct pt_regs *regs)
 	/* Remove breakpoint even if return error as not to loop */
 	arch_uninstall_hw_breakpoint(event);
 
-	ret = get_insn(regs, regs->epc, &insn);
-	if (ret < 0)
-		return ret;
+	if (have_icount) {
+		rv_init_icount_trigger(bp);
+	} else {
+		ret = get_insn(regs, regs->epc, &insn);
+		if (ret < 0)
+			return ret;
 
-	next_addr = get_step_address(regs, insn);
+		next_addr = get_step_address(regs, insn);
 
-	ret = get_insn(regs, next_addr, &insn);
-	if (ret < 0)
-		return ret;
+		ret = get_insn(regs, next_addr, &insn);
+		if (ret < 0)
+			return ret;
 
-	bp_insn.bp_type = HW_BREAKPOINT_X;
-	bp_insn.bp_addr = next_addr;
-	/* Get the size of the intruction */
-	bp_insn.bp_len = GET_INSN_LENGTH(insn);
+		bp_insn.bp_type = HW_BREAKPOINT_X;
+		bp_insn.bp_addr = next_addr;
+		/* Get the size of the intruction */
+		bp_insn.bp_len = GET_INSN_LENGTH(insn);
 
-	ret = hw_breakpoint_arch_parse(NULL, &bp_insn, bp);
-	if (ret)
-		return ret;
+		ret = hw_breakpoint_arch_parse(NULL, &bp_insn, bp);
+		if (ret)
+			return ret;
+	}
 
 	ret = arch_install_hw_breakpoint(event);
 	if (ret)
#13 lore raw

RFC PATCH 6/6 riscv: ptrace: Add hw breakpoint support

In reply to Jesse Taube

Add ability to setup hw breakpoints to ptrace. Call defines a new structure of (ulong[3]){bp_addr, bp_len, bp_type} with bp_type being one of HW_BREAKPOINT_LEN_X and
bp_len being one of HW_BREAKPOINT_X with a value of zero dissabling the breakpoint.

---
 arch/riscv/include/asm/processor.h   |  4 ++
 arch/riscv/include/uapi/asm/ptrace.h |  3 +-
 arch/riscv/kernel/hw_breakpoint.c    | 14 ++++-
 arch/riscv/kernel/process.c          |  4 ++
 arch/riscv/kernel/ptrace.c           | 93 ++++++++++++++++++++++++++++
 5 files changed, 116 insertions(+), 2 deletions(-)
arch/riscv/include/asm/processor.h +4 -0
index 5f56eb9d114a..488d956a951f 100644
@@ -12,6 +12,7 @@
 
 #include <vdso/processor.h>
 
+#include <asm/hw_breakpoint.h>
 #include <asm/ptrace.h>
 
 #define arch_get_mmap_end(addr, len, flags)			\
@@ -108,6 +109,9 @@ struct thread_struct {
 	struct __riscv_v_ext_state vstate;
 	unsigned long align_ctl;
 	struct __riscv_v_ext_state kernel_vstate;
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+	struct perf_event *ptrace_bps[RV_MAX_TRIGGERS];
+#endif
 #ifdef CONFIG_SMP
 	/* Flush the icache on migration */
 	bool force_icache_flush;
arch/riscv/include/uapi/asm/ptrace.h +2 -1
index a38268b19c3d..a7998ed41913 100644
@@ -14,7 +14,8 @@
 
 #define PTRACE_GETFDPIC_EXEC	0
 #define PTRACE_GETFDPIC_INTERP	1
-
+#define PTRACE_GETHBPREGS	2
+#define PTRACE_SETHBPREGS	3
 /*
  * User-mode register state for core dumps, ptrace, sigcontext
  *
arch/riscv/kernel/hw_breakpoint.c +13 -1
index 437fd82b9590..c58145464539 100644
@@ -633,7 +633,19 @@ void arch_uninstall_hw_breakpoint(struct perf_event *event)
 		pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
 }
 
-void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }
+/*
+ * Release the user breakpoints used by ptrace
+ */
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk)
+{
+	int i;
+	struct thread_struct *t = &tsk->thread;
+
+	for (i = 0; i < dbtr_total_num; i++) {
+		unregister_hw_breakpoint(t->ptrace_bps[i]);
+		t->ptrace_bps[i] = NULL;
+	}
+}
 
 void hw_breakpoint_pmu_read(struct perf_event *bp) { }
 
arch/riscv/kernel/process.c +4 -0
index 15d8f75902f8..9cf07ecfb523 100644
@@ -9,6 +9,7 @@
 
 #include <linux/bitfield.h>
 #include <linux/cpu.h>
+#include <linux/hw_breakpoint.h>
 #include <linux/kernel.h>
 #include <linux/sched.h>
 #include <linux/sched/debug.h>
@@ -164,6 +165,7 @@ void start_thread(struct pt_regs *regs, unsigned long pc,
 
 void flush_thread(void)
 {
+	flush_ptrace_hw_breakpoint(current);
 #ifdef CONFIG_FPU
 	/*
 	 * Reset FPU state and context
@@ -218,6 +220,8 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
 		set_bit(MM_CONTEXT_LOCK_PMLEN, &p->mm->context.flags);
 
 	memset(&p->thread.s, 0, sizeof(p->thread.s));
+	if (IS_ENABLED(CONFIG_HAVE_HW_BREAKPOINT))
+		memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
 
 	/* p->thread holds context to be restored by __switch_to() */
 	if (unlikely(args->fn)) {
arch/riscv/kernel/ptrace.c +93 -0

116 lines not on this page · raw message

Signature · 1 line
2.43.0
#14 lore raw

Re: [RFC PATCH 6/6] riscv: ptrace: Add hw breakpoint support

Quoted 42 lines · Jesse Taube

Add ability to setup hw breakpoints to ptrace. Call defines a new structure of (ulong[3]){bp_addr, bp_len, bp_type} with bp_type being one of HW_BREAKPOINT_LEN_X and
bp_len being one of HW_BREAKPOINT_X with a value of zero dissabling the breakpoint.

---

arch/riscv/include/asm/processor.h   |  4 ++
arch/riscv/include/uapi/asm/ptrace.h |  3 +-
arch/riscv/kernel/hw_breakpoint.c    | 14 ++++-
arch/riscv/kernel/process.c          |  4 ++
arch/riscv/kernel/ptrace.c           | 93 ++++++++++++++++++++++++++++
5 files changed, 116 insertions(+), 2 deletions(-)
arch/riscv/include/asm/processor.h +4 -0
index 5f56eb9d114a..488d956a951f 100644
@@ -12,6 +12,7 @@
 
 #include <vdso/processor.h>
 
+#include <asm/hw_breakpoint.h>
 #include <asm/ptrace.h>
 
 #define arch_get_mmap_end(addr, len, flags)			\
@@ -108,6 +109,9 @@ struct thread_struct {
 	struct __riscv_v_ext_state vstate;
 	unsigned long align_ctl;
 	struct __riscv_v_ext_state kernel_vstate;
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+	struct perf_event *ptrace_bps[RV_MAX_TRIGGERS];
+#endif
 #ifdef CONFIG_SMP
 	/* Flush the icache on migration */
 	bool force_icache_flush;
arch/riscv/include/uapi/asm/ptrace.h +0 -0
index a38268b19c3d..a7998ed41913 100644

arch/riscv/include/uapi/asm/ptrace.h line 18

Quoted 6 lines
arch/riscv/include/uapi/asm/ptrace.h +2 -1
@@ -14,7 +14,8 @@
 
 #define PTRACE_GETFDPIC_EXEC	0
 #define PTRACE_GETFDPIC_INTERP	1
-
+#define PTRACE_GETHBPREGS	2
+#define PTRACE_SETHBPREGS	3

Why not use PTRACE_GETREGSET PTRACE_SETREGSET ?

Quoted 127 lines
arch/riscv/include/uapi/asm/ptrace.h +0 -0
 /*
 * User-mode register state for core dumps, ptrace, sigcontext
 *
arch/riscv/kernel/hw_breakpoint.c +13 -1
index 437fd82b9590..c58145464539 100644
@@ -633,7 +633,19 @@ void arch_uninstall_hw_breakpoint(struct perf_event *event)
 		pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
 }
 
-void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }
+/*
+ * Release the user breakpoints used by ptrace
+ */
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk)
+{
+	int i;
+	struct thread_struct *t = &tsk->thread;
+
+	for (i = 0; i < dbtr_total_num; i++) {
+		unregister_hw_breakpoint(t->ptrace_bps[i]);
+		t->ptrace_bps[i] = NULL;
+	}
+}
 
 void hw_breakpoint_pmu_read(struct perf_event *bp) { }
 
arch/riscv/kernel/process.c +4 -0
index 15d8f75902f8..9cf07ecfb523 100644
@@ -9,6 +9,7 @@
 
 #include <linux/bitfield.h>
 #include <linux/cpu.h>
+#include <linux/hw_breakpoint.h>
 #include <linux/kernel.h>
 #include <linux/sched.h>
 #include <linux/sched/debug.h>
@@ -164,6 +165,7 @@ void start_thread(struct pt_regs *regs, unsigned long pc,
 
 void flush_thread(void)
 {
+	flush_ptrace_hw_breakpoint(current);
 #ifdef CONFIG_FPU
 	/*
 	 * Reset FPU state and context
@@ -218,6 +220,8 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
 		set_bit(MM_CONTEXT_LOCK_PMLEN, &p->mm->context.flags);
 
 	memset(&p->thread.s, 0, sizeof(p->thread.s));
+	if (IS_ENABLED(CONFIG_HAVE_HW_BREAKPOINT))
+		memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
 
 	/* p->thread holds context to be restored by __switch_to() */
 	if (unlikely(args->fn)) {
arch/riscv/kernel/ptrace.c +50 -0
index ea67e9fb7a58..b78cfb0f1c0e 100644
@@ -9,11 +9,13 @@
 
 #include <asm/vector.h>
 #include <asm/ptrace.h>
+#include <asm/hw_breakpoint.h>
 #include <asm/syscall.h>
 #include <asm/thread_info.h>
 #include <asm/switch_to.h>
 #include <linux/audit.h>
 #include <linux/compat.h>
+#include <linux/hw_breakpoint.h>
 #include <linux/ptrace.h>
 #include <linux/elf.h>
 #include <linux/regset.h>
@@ -336,12 +338,103 @@ void ptrace_disable(struct task_struct *child)
 {
 }
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+static void ptrace_hbptriggered(struct perf_event *bp,
+				struct perf_sample_data *data,
+				struct pt_regs *regs)
+{
+	struct arch_hw_breakpoint *bkpt = counter_arch_bp(bp);
+	int num = 0;
+
+	force_sig_ptrace_errno_trap(num, (void __user *)bkpt->address);
+}
+
+/*
+ * idx selects the breakpoint index.
+ * Both PTRACE_GETHBPREGS and PTRACE_SETHBPREGS transfer three 32-bit words:
+ * address (0), length (1), type (2).
+ * Instruction breakpoint length is one of HW_BREAKPOINT_LEN_X or 0. 0 will
+ * disable the breakpoint.
+ * Instruction breakpoint type is one of HW_BREAKPOINT_X.
+ */
+
+static long ptrace_gethbpregs(struct task_struct *child, unsigned long idx,
+			      unsigned long __user *datap)
+{
+	struct perf_event *bp;
+	unsigned long user_data[3] = {0};
+
+	if (idx >= RV_MAX_TRIGGERS)
+		return -EINVAL;
+
+	bp = child->thread.ptrace_bps[idx];
+
+	if (!IS_ERR_OR_NULL(bp)) {
+		user_data[0] = bp->attr.bp_addr;
+		user_data[1] = bp->attr.disabled ? 0 : bp->attr.bp_len;
+		user_data[2] = bp->attr.bp_type;
+	}
+
+	if (copy_to_user(datap, user_data, sizeof(user_data)))
+		return -EFAULT;
+
+	return 0;
+}
+
+static long ptrace_sethbpregs(struct task_struct *child, unsigned long idx,
+			      unsigned long __user *datap)
+{
+	struct perf_event *bp;
+	struct perf_event_attr attr;

arch/riscv/kernel/ptrace.c void ptrace_disable(struct task_struct *child) · line 398

Quoted 10 lines
arch/riscv/kernel/ptrace.c +10 -0
+	unsigned long user_data[3];
+
+	if (idx >= RV_MAX_TRIGGERS)
+		return -EINVAL;
+
+	if (copy_from_user(user_data, datap, sizeof(user_data)))
+		return -EFAULT;
+
+	bp = child->thread.ptrace_bps[idx];
+	if (IS_ERR_OR_NULL(bp))

Why not only check for NULL?
IS_ERR_VALUE will always expand to be true. right?

arch/riscv/kernel/ptrace.c void ptrace_disable(struct task_struct *child) · line 406

Quoted 8 lines
arch/riscv/kernel/ptrace.c +8 -0
+		attr = bp->attr;
+	else
+		ptrace_breakpoint_init(&attr);
+
+	attr.bp_addr = user_data[0];
+	attr.bp_len = user_data[1];
+	attr.bp_type = user_data[2];
+	attr.disabled = !attr.bp_len;

Is it okay to not have any sanitization on inputs?

Can these inputs be controlled by user to give kernel address and kernel breakpoint?

Quoted 37 lines
arch/riscv/kernel/ptrace.c +25 -0
+
+	if (IS_ERR_OR_NULL(bp)) {
+		bp = register_user_hw_breakpoint(&attr, ptrace_hbptriggered, NULL,
+					   child);
+		if (IS_ERR(bp))
+			return PTR_ERR(bp);
+
+		child->thread.ptrace_bps[idx] = bp;
+		return 0;
+	} else {
+		return modify_user_hw_breakpoint(bp, &attr);
+	}
+}
+#endif
+
 long arch_ptrace(struct task_struct *child, long request,
 		 unsigned long addr, unsigned long data)
 {
 	long ret = -EIO;
+	unsigned long __user *datap = (unsigned long __user *) data;
 
 	switch (request) {
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+	case PTRACE_GETHBPREGS:
+		ret = ptrace_gethbpregs(child, addr, datap);
+		break;
+
+	case PTRACE_SETHBPREGS:
+		ret = ptrace_sethbpregs(child, addr, datap);
+		break;
+#endif
 	default:
 		ret = ptrace_request(child, request, addr, data);
 		break;
Signature · 1 line
2.43.0
#15 lore raw

Re: [RFC PATCH 6/6] riscv: ptrace: Add hw breakpoint support

Quoted 45 lines · Deepak Gupta
Quoted 43 lines · Jesse Taube

Add ability to setup hw breakpoints to ptrace. Call defines a new structure of (ulong[3]){bp_addr, bp_len, bp_type} with bp_type being one of HW_BREAKPOINT_LEN_X and
bp_len being one of HW_BREAKPOINT_X with a value of zero dissabling the breakpoint.

---

arch/riscv/include/asm/processor.h   |  4 ++
arch/riscv/include/uapi/asm/ptrace.h |  3 +-
arch/riscv/kernel/hw_breakpoint.c    | 14 ++++-
arch/riscv/kernel/process.c          |  4 ++
arch/riscv/kernel/ptrace.c           | 93 ++++++++++++++++++++++++++++
5 files changed, 116 insertions(+), 2 deletions(-)
arch/riscv/include/asm/processor.h +4 -0
index 5f56eb9d114a..488d956a951f 100644
@@ -12,6 +12,7 @@
 
 #include <vdso/processor.h>
 
+#include <asm/hw_breakpoint.h>
 #include <asm/ptrace.h>
 
 #define arch_get_mmap_end(addr, len, flags)                   \
@@ -108,6 +109,9 @@ struct thread_struct {
      struct __riscv_v_ext_state vstate;
      unsigned long align_ctl;
      struct __riscv_v_ext_state kernel_vstate;
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+      struct perf_event *ptrace_bps[RV_MAX_TRIGGERS];
+#endif
 #ifdef CONFIG_SMP
      /* Flush the icache on migration */
      bool force_icache_flush;
arch/riscv/include/uapi/asm/ptrace.h +0 -0
index a38268b19c3d..a7998ed41913 100644
@@ -14,7 +14,8 @@
 
Quoted 7 lines

arch/riscv/include/uapi/asm/ptrace.h line 18

Quoted 5 lines
arch/riscv/include/uapi/asm/ptrace.h +2 -1
 #define PTRACE_GETFDPIC_EXEC  0
 #define PTRACE_GETFDPIC_INTERP        1
-
+#define PTRACE_GETHBPREGS     2
+#define PTRACE_SETHBPREGS     3

Why not use PTRACE_GETREGSET PTRACE_SETREGSET ?

Because it was easier to implement this first, and REGSET will be another commit ontop of this one.
Unless there is a reason to not have this version.

Quoted 133 lines
Quoted 133 lines
arch/riscv/include/uapi/asm/ptrace.h +0 -0
 /*
 * User-mode register state for core dumps, ptrace, sigcontext
 *
arch/riscv/kernel/hw_breakpoint.c +13 -1
index 437fd82b9590..c58145464539 100644
@@ -633,7 +633,19 @@ void arch_uninstall_hw_breakpoint(struct perf_event *event)
              pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
 }
 
-void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }
+/*
+ * Release the user breakpoints used by ptrace
+ */
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk)
+{
+      int i;
+      struct thread_struct *t = &tsk->thread;
+
+      for (i = 0; i < dbtr_total_num; i++) {
+              unregister_hw_breakpoint(t->ptrace_bps[i]);
+              t->ptrace_bps[i] = NULL;
+      }
+}
 
 void hw_breakpoint_pmu_read(struct perf_event *bp) { }
 
arch/riscv/kernel/process.c +4 -0
index 15d8f75902f8..9cf07ecfb523 100644
@@ -9,6 +9,7 @@
 
 #include <linux/bitfield.h>
 #include <linux/cpu.h>
+#include <linux/hw_breakpoint.h>
 #include <linux/kernel.h>
 #include <linux/sched.h>
 #include <linux/sched/debug.h>
@@ -164,6 +165,7 @@ void start_thread(struct pt_regs *regs, unsigned long pc,
 
 void flush_thread(void)
 {
+      flush_ptrace_hw_breakpoint(current);
 #ifdef CONFIG_FPU
      /*
       * Reset FPU state and context
@@ -218,6 +220,8 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
              set_bit(MM_CONTEXT_LOCK_PMLEN, &p->mm->context.flags);
 
      memset(&p->thread.s, 0, sizeof(p->thread.s));
+      if (IS_ENABLED(CONFIG_HAVE_HW_BREAKPOINT))
+              memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
 
      /* p->thread holds context to be restored by __switch_to() */
      if (unlikely(args->fn)) {
arch/riscv/kernel/ptrace.c +55 -0
index ea67e9fb7a58..b78cfb0f1c0e 100644
@@ -9,11 +9,13 @@
 
 #include <asm/vector.h>
 #include <asm/ptrace.h>
+#include <asm/hw_breakpoint.h>
 #include <asm/syscall.h>
 #include <asm/thread_info.h>
 #include <asm/switch_to.h>
 #include <linux/audit.h>
 #include <linux/compat.h>
+#include <linux/hw_breakpoint.h>
 #include <linux/ptrace.h>
 #include <linux/elf.h>
 #include <linux/regset.h>
@@ -336,12 +338,103 @@ void ptrace_disable(struct task_struct *child)
 {
 }
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+static void ptrace_hbptriggered(struct perf_event *bp,
+                              struct perf_sample_data *data,
+                              struct pt_regs *regs)
+{
+      struct arch_hw_breakpoint *bkpt = counter_arch_bp(bp);
+      int num = 0;
+
+      force_sig_ptrace_errno_trap(num, (void __user *)bkpt->address);
+}
+
+/*
+ * idx selects the breakpoint index.
+ * Both PTRACE_GETHBPREGS and PTRACE_SETHBPREGS transfer three 32-bit words:
+ * address (0), length (1), type (2).
+ * Instruction breakpoint length is one of HW_BREAKPOINT_LEN_X or 0. 0 will
+ * disable the breakpoint.
+ * Instruction breakpoint type is one of HW_BREAKPOINT_X.
+ */
+
+static long ptrace_gethbpregs(struct task_struct *child, unsigned long idx,
+                            unsigned long __user *datap)
+{
+      struct perf_event *bp;
+      unsigned long user_data[3] = {0};
+
+      if (idx >= RV_MAX_TRIGGERS)
+              return -EINVAL;
+
+      bp = child->thread.ptrace_bps[idx];
+
+      if (!IS_ERR_OR_NULL(bp)) {
+              user_data[0] = bp->attr.bp_addr;
+              user_data[1] = bp->attr.disabled ? 0 : bp->attr.bp_len;
+              user_data[2] = bp->attr.bp_type;
+      }
+
+      if (copy_to_user(datap, user_data, sizeof(user_data)))
+              return -EFAULT;
+
+      return 0;
+}
+
+static long ptrace_sethbpregs(struct task_struct *child, unsigned long idx,
+                            unsigned long __user *datap)
+{
+      struct perf_event *bp;
+      struct perf_event_attr attr;
+      unsigned long user_data[3];
+
+      if (idx >= RV_MAX_TRIGGERS)
+              return -EINVAL;
+
Quoted 8 lines

arch/riscv/kernel/ptrace.c void ptrace_disable(struct task_struct *child) · line 398

Quoted 5 lines
arch/riscv/kernel/ptrace.c +5 -0
+      if (copy_from_user(user_data, datap, sizeof(user_data)))
+              return -EFAULT;
+
+      bp = child->thread.ptrace_bps[idx];
+      if (IS_ERR_OR_NULL(bp))

Why not only check for NULL?
IS_ERR_VALUE will always expand to be true. right?

Because im dumb and thought i was setting bp to an error code, but i'm not. Yes if (!bp) is right.

Quoted 10 lines

arch/riscv/kernel/ptrace.c void ptrace_disable(struct task_struct *child) · line 406

Quoted 9 lines
arch/riscv/kernel/ptrace.c +8 -0
+              attr = bp->attr;
+      else
+              ptrace_breakpoint_init(&attr);
+
+      attr.bp_addr = user_data[0];
+      attr.bp_len = user_data[1];
+      attr.bp_type = user_data[2];
+      attr.disabled = !attr.bp_len;
Quoted 4 lines

Is it okay to not have any sanitization on inputs?

Can these inputs be controlled by user to give kernel address and kernel breakpoint?

modify_user_hw_breakpoint calls modify_user_hw_breakpoint_check, which eventually checks if we have CAP_SYS_ADMIN.
Same for register. type and len are also checked by the _user_hw_breakpoint_check functions and again in the riscv code.

it would be nice if this could be double checked, but it does seem other architectures don't check addr aswell.

Thanks,
Jesse Taube

Quoted 38 lines
Quoted 38 lines
arch/riscv/kernel/ptrace.c +25 -1
+
+      if (IS_ERR_OR_NULL(bp)) {
+              bp = register_user_hw_breakpoint(&attr, ptrace_hbptriggered, NULL,
+                                         child);
+              if (IS_ERR(bp))
+                      return PTR_ERR(bp);
+
+              child->thread.ptrace_bps[idx] = bp;
+              return 0;
+      } else {
+              return modify_user_hw_breakpoint(bp, &attr);
+      }
+}
+#endif
+
 long arch_ptrace(struct task_struct *child, long request,
               unsigned long addr, unsigned long data)
 {
      long ret = -EIO;
+      unsigned long __user *datap = (unsigned long __user *) data;
 
      switch (request) {
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+      case PTRACE_GETHBPREGS:
+              ret = ptrace_gethbpregs(child, addr, datap);
+              break;
+
+      case PTRACE_SETHBPREGS:
+              ret = ptrace_sethbpregs(child, addr, datap);
+              break;
+#endif
      default:
              ret = ptrace_request(child, request, addr, data);
              break;
--

2.43.0

#16 lore raw

Re: [RFC PATCH 6/6] riscv: ptrace: Add hw breakpoint support

Quoted 54 lines · Jesse Taube
Quoted 45 lines · Deepak Gupta
Quoted 43 lines · Jesse Taube

Add ability to setup hw breakpoints to ptrace. Call defines a new structure of (ulong[3]){bp_addr, bp_len, bp_type} with bp_type being one of HW_BREAKPOINT_LEN_X and
bp_len being one of HW_BREAKPOINT_X with a value of zero dissabling the breakpoint.

---

arch/riscv/include/asm/processor.h   |  4 ++
arch/riscv/include/uapi/asm/ptrace.h |  3 +-
arch/riscv/kernel/hw_breakpoint.c    | 14 ++++-
arch/riscv/kernel/process.c          |  4 ++
arch/riscv/kernel/ptrace.c           | 93 ++++++++++++++++++++++++++++
5 files changed, 116 insertions(+), 2 deletions(-)
arch/riscv/include/asm/processor.h +4 -0
index 5f56eb9d114a..488d956a951f 100644
@@ -12,6 +12,7 @@
 
 #include <vdso/processor.h>
 
+#include <asm/hw_breakpoint.h>
 #include <asm/ptrace.h>
 
 #define arch_get_mmap_end(addr, len, flags)                   \
@@ -108,6 +109,9 @@ struct thread_struct {
      struct __riscv_v_ext_state vstate;
      unsigned long align_ctl;
      struct __riscv_v_ext_state kernel_vstate;
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+      struct perf_event *ptrace_bps[RV_MAX_TRIGGERS];
+#endif
 #ifdef CONFIG_SMP
      /* Flush the icache on migration */
      bool force_icache_flush;
arch/riscv/include/uapi/asm/ptrace.h +0 -0
index a38268b19c3d..a7998ed41913 100644
@@ -14,7 +14,8 @@
 
Quoted 7 lines

arch/riscv/include/uapi/asm/ptrace.h line 18

Quoted 5 lines
arch/riscv/include/uapi/asm/ptrace.h +2 -1
 #define PTRACE_GETFDPIC_EXEC  0
 #define PTRACE_GETFDPIC_INTERP        1
-
+#define PTRACE_GETHBPREGS     2
+#define PTRACE_SETHBPREGS     3

Why not use PTRACE_GETREGSET PTRACE_SETREGSET ?

Quoted 4 lines

Because it was easier to implement this first, and REGSET will be another commit ontop of this one.
Unless there is a reason to not have this version.

Yeah I don't have strong feelings on this. Whatever is best for the tools (gdb, etc) who will consume this interface, lets do that.

Quoted 160 lines
Quoted 133 lines
Quoted 133 lines
arch/riscv/include/uapi/asm/ptrace.h +0 -0
 /*
 * User-mode register state for core dumps, ptrace, sigcontext
 *
arch/riscv/kernel/hw_breakpoint.c +13 -1
index 437fd82b9590..c58145464539 100644
@@ -633,7 +633,19 @@ void arch_uninstall_hw_breakpoint(struct perf_event *event)
              pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
 }
 
-void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }
+/*
+ * Release the user breakpoints used by ptrace
+ */
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk)
+{
+      int i;
+      struct thread_struct *t = &tsk->thread;
+
+      for (i = 0; i < dbtr_total_num; i++) {
+              unregister_hw_breakpoint(t->ptrace_bps[i]);
+              t->ptrace_bps[i] = NULL;
+      }
+}
 
 void hw_breakpoint_pmu_read(struct perf_event *bp) { }
 
arch/riscv/kernel/process.c +4 -0
index 15d8f75902f8..9cf07ecfb523 100644
@@ -9,6 +9,7 @@
 
 #include <linux/bitfield.h>
 #include <linux/cpu.h>
+#include <linux/hw_breakpoint.h>
 #include <linux/kernel.h>
 #include <linux/sched.h>
 #include <linux/sched/debug.h>
@@ -164,6 +165,7 @@ void start_thread(struct pt_regs *regs, unsigned long pc,
 
 void flush_thread(void)
 {
+      flush_ptrace_hw_breakpoint(current);
 #ifdef CONFIG_FPU
      /*
       * Reset FPU state and context
@@ -218,6 +220,8 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
              set_bit(MM_CONTEXT_LOCK_PMLEN, &p->mm->context.flags);
 
      memset(&p->thread.s, 0, sizeof(p->thread.s));
+      if (IS_ENABLED(CONFIG_HAVE_HW_BREAKPOINT))
+              memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
 
      /* p->thread holds context to be restored by __switch_to() */
      if (unlikely(args->fn)) {
arch/riscv/kernel/ptrace.c +55 -0
index ea67e9fb7a58..b78cfb0f1c0e 100644
@@ -9,11 +9,13 @@
 
 #include <asm/vector.h>
 #include <asm/ptrace.h>
+#include <asm/hw_breakpoint.h>
 #include <asm/syscall.h>
 #include <asm/thread_info.h>
 #include <asm/switch_to.h>
 #include <linux/audit.h>
 #include <linux/compat.h>
+#include <linux/hw_breakpoint.h>
 #include <linux/ptrace.h>
 #include <linux/elf.h>
 #include <linux/regset.h>
@@ -336,12 +338,103 @@ void ptrace_disable(struct task_struct *child)
 {
 }
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+static void ptrace_hbptriggered(struct perf_event *bp,
+                              struct perf_sample_data *data,
+                              struct pt_regs *regs)
+{
+      struct arch_hw_breakpoint *bkpt = counter_arch_bp(bp);
+      int num = 0;
+
+      force_sig_ptrace_errno_trap(num, (void __user *)bkpt->address);
+}
+
+/*
+ * idx selects the breakpoint index.
+ * Both PTRACE_GETHBPREGS and PTRACE_SETHBPREGS transfer three 32-bit words:
+ * address (0), length (1), type (2).
+ * Instruction breakpoint length is one of HW_BREAKPOINT_LEN_X or 0. 0 will
+ * disable the breakpoint.
+ * Instruction breakpoint type is one of HW_BREAKPOINT_X.
+ */
+
+static long ptrace_gethbpregs(struct task_struct *child, unsigned long idx,
+                            unsigned long __user *datap)
+{
+      struct perf_event *bp;
+      unsigned long user_data[3] = {0};
+
+      if (idx >= RV_MAX_TRIGGERS)
+              return -EINVAL;
+
+      bp = child->thread.ptrace_bps[idx];
+
+      if (!IS_ERR_OR_NULL(bp)) {
+              user_data[0] = bp->attr.bp_addr;
+              user_data[1] = bp->attr.disabled ? 0 : bp->attr.bp_len;
+              user_data[2] = bp->attr.bp_type;
+      }
+
+      if (copy_to_user(datap, user_data, sizeof(user_data)))
+              return -EFAULT;
+
+      return 0;
+}
+
+static long ptrace_sethbpregs(struct task_struct *child, unsigned long idx,
+                            unsigned long __user *datap)
+{
+      struct perf_event *bp;
+      struct perf_event_attr attr;
+      unsigned long user_data[3];
+
+      if (idx >= RV_MAX_TRIGGERS)
+              return -EINVAL;
+
Quoted 8 lines

arch/riscv/kernel/ptrace.c void ptrace_disable(struct task_struct *child) · line 398

Quoted 5 lines
arch/riscv/kernel/ptrace.c +5 -0
+      if (copy_from_user(user_data, datap, sizeof(user_data)))
+              return -EFAULT;
+
+      bp = child->thread.ptrace_bps[idx];
+      if (IS_ERR_OR_NULL(bp))

Why not only check for NULL?
IS_ERR_VALUE will always expand to be true. right?

Because im dumb and thought i was setting bp to an error code, but i'm not. Yes if (!bp) is right.

Quoted 10 lines

arch/riscv/kernel/ptrace.c void ptrace_disable(struct task_struct *child) · line 406

Quoted 9 lines
arch/riscv/kernel/ptrace.c +8 -0
+              attr = bp->attr;
+      else
+              ptrace_breakpoint_init(&attr);
+
+      attr.bp_addr = user_data[0];
+      attr.bp_len = user_data[1];
+      attr.bp_type = user_data[2];
+      attr.disabled = !attr.bp_len;
Quoted 4 lines

Is it okay to not have any sanitization on inputs?

Can these inputs be controlled by user to give kernel address and kernel breakpoint?

Quoted 7 lines

modify_user_hw_breakpoint calls modify_user_hw_breakpoint_check, which eventually checks if we have CAP_SYS_ADMIN.
Same for register. type and len are also checked by the _user_hw_breakpoint_check functions and again in the riscv code.

it would be nice if this could be double checked, but it does seem other architectures don't check addr aswell.

I see. That's interesting.

Quoted 42 lines

Thanks,
Jesse Taube

Quoted 38 lines
Quoted 38 lines
arch/riscv/kernel/ptrace.c +25 -1
+
+      if (IS_ERR_OR_NULL(bp)) {
+              bp = register_user_hw_breakpoint(&attr, ptrace_hbptriggered, NULL,
+                                         child);
+              if (IS_ERR(bp))
+                      return PTR_ERR(bp);
+
+              child->thread.ptrace_bps[idx] = bp;
+              return 0;
+      } else {
+              return modify_user_hw_breakpoint(bp, &attr);
+      }
+}
+#endif
+
 long arch_ptrace(struct task_struct *child, long request,
               unsigned long addr, unsigned long data)
 {
      long ret = -EIO;
+      unsigned long __user *datap = (unsigned long __user *) data;
 
      switch (request) {
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+      case PTRACE_GETHBPREGS:
+              ret = ptrace_gethbpregs(child, addr, datap);
+              break;
+
+      case PTRACE_SETHBPREGS:
+              ret = ptrace_sethbpregs(child, addr, datap);
+              break;
+#endif
      default:
              ret = ptrace_request(child, request, addr, data);
              break;
--

2.43.0

#17 lore raw

Re: [RFC PATCH 6/6] riscv: ptrace: Add hw breakpoint support

In reply to Jesse Taube
Quoted 63 lines · Jesse Taube

Add ability to setup hw breakpoints to ptrace. Call defines a new structure of (ulong[3]){bp_addr, bp_len, bp_type} with bp_type being one of HW_BREAKPOINT_LEN_X and
bp_len being one of HW_BREAKPOINT_X with a value of zero dissabling the breakpoint.

---
 arch/riscv/include/asm/processor.h   |  4 ++
 arch/riscv/include/uapi/asm/ptrace.h |  3 +-
 arch/riscv/kernel/hw_breakpoint.c    | 14 ++++-
 arch/riscv/kernel/process.c          |  4 ++
 arch/riscv/kernel/ptrace.c           | 93 ++++++++++++++++++++++++++++
 5 files changed, 116 insertions(+), 2 deletions(-)
arch/riscv/include/asm/processor.h +4 -0
index 5f56eb9d114a..488d956a951f 100644
@@ -12,6 +12,7 @@
 
 #include <vdso/processor.h>
 
+#include <asm/hw_breakpoint.h>
 #include <asm/ptrace.h>
 
 #define arch_get_mmap_end(addr, len, flags)			\
@@ -108,6 +109,9 @@ struct thread_struct {
 	struct __riscv_v_ext_state vstate;
 	unsigned long align_ctl;
 	struct __riscv_v_ext_state kernel_vstate;
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+	struct perf_event *ptrace_bps[RV_MAX_TRIGGERS];
+#endif
 #ifdef CONFIG_SMP
 	/* Flush the icache on migration */
 	bool force_icache_flush;
arch/riscv/include/uapi/asm/ptrace.h +2 -1
index a38268b19c3d..a7998ed41913 100644
@@ -14,7 +14,8 @@
 
 #define PTRACE_GETFDPIC_EXEC	0
 #define PTRACE_GETFDPIC_INTERP	1
-
+#define PTRACE_GETHBPREGS	2
+#define PTRACE_SETHBPREGS	3
 /*
  * User-mode register state for core dumps, ptrace, sigcontext
  *
arch/riscv/kernel/hw_breakpoint.c +3 -1
index 437fd82b9590..c58145464539 100644
@@ -633,7 +633,19 @@ void arch_uninstall_hw_breakpoint(struct perf_event *event)
 		pr_warn("%s: Failed to uninstall trigger %d. error: %ld\n", __func__, i, ret.error);
 }
 
-void flush_ptrace_hw_breakpoint(struct task_struct *tsk) { }
+/*
+ * Release the user breakpoints used by ptrace
+ */

arch/riscv/kernel/hw_breakpoint.c void arch_uninstall_hw_breakpoint(struct perf_event *event) · line 648

Quoted 10 lines
arch/riscv/kernel/hw_breakpoint.c +10 -0
+void flush_ptrace_hw_breakpoint(struct task_struct *tsk)
+{
+	int i;
+	struct thread_struct *t = &tsk->thread;
+
+	for (i = 0; i < dbtr_total_num; i++) {
+		unregister_hw_breakpoint(t->ptrace_bps[i]);
+		t->ptrace_bps[i] = NULL;
+	}
+}

Hi Jesse,

You can discard my comment in the previous patch about implementing this function ;)

Thanks,

Clément

Quoted 154 lines
arch/riscv/kernel/hw_breakpoint.c +0 -0
 void hw_breakpoint_pmu_read(struct perf_event *bp) { }
 
arch/riscv/kernel/process.c +4 -0
index 15d8f75902f8..9cf07ecfb523 100644
@@ -9,6 +9,7 @@
 
 #include <linux/bitfield.h>
 #include <linux/cpu.h>
+#include <linux/hw_breakpoint.h>
 #include <linux/kernel.h>
 #include <linux/sched.h>
 #include <linux/sched/debug.h>
@@ -164,6 +165,7 @@ void start_thread(struct pt_regs *regs, unsigned long pc,
 
 void flush_thread(void)
 {
+	flush_ptrace_hw_breakpoint(current);
 #ifdef CONFIG_FPU
 	/*
 	 * Reset FPU state and context
@@ -218,6 +220,8 @@ int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
 		set_bit(MM_CONTEXT_LOCK_PMLEN, &p->mm->context.flags);
 
 	memset(&p->thread.s, 0, sizeof(p->thread.s));
+	if (IS_ENABLED(CONFIG_HAVE_HW_BREAKPOINT))
+		memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
 
 	/* p->thread holds context to be restored by __switch_to() */
 	if (unlikely(args->fn)) {
arch/riscv/kernel/ptrace.c +93 -0
index ea67e9fb7a58..b78cfb0f1c0e 100644
@@ -9,11 +9,13 @@
 
 #include <asm/vector.h>
 #include <asm/ptrace.h>
+#include <asm/hw_breakpoint.h>
 #include <asm/syscall.h>
 #include <asm/thread_info.h>
 #include <asm/switch_to.h>
 #include <linux/audit.h>
 #include <linux/compat.h>
+#include <linux/hw_breakpoint.h>
 #include <linux/ptrace.h>
 #include <linux/elf.h>
 #include <linux/regset.h>
@@ -336,12 +338,103 @@ void ptrace_disable(struct task_struct *child)
 {
 }
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+static void ptrace_hbptriggered(struct perf_event *bp,
+				struct perf_sample_data *data,
+				struct pt_regs *regs)
+{
+	struct arch_hw_breakpoint *bkpt = counter_arch_bp(bp);
+	int num = 0;
+
+	force_sig_ptrace_errno_trap(num, (void __user *)bkpt->address);
+}
+
+/*
+ * idx selects the breakpoint index.
+ * Both PTRACE_GETHBPREGS and PTRACE_SETHBPREGS transfer three 32-bit words:
+ * address (0), length (1), type (2).
+ * Instruction breakpoint length is one of HW_BREAKPOINT_LEN_X or 0. 0 will
+ * disable the breakpoint.
+ * Instruction breakpoint type is one of HW_BREAKPOINT_X.
+ */
+
+static long ptrace_gethbpregs(struct task_struct *child, unsigned long idx,
+			      unsigned long __user *datap)
+{
+	struct perf_event *bp;
+	unsigned long user_data[3] = {0};
+
+	if (idx >= RV_MAX_TRIGGERS)
+		return -EINVAL;
+
+	bp = child->thread.ptrace_bps[idx];
+
+	if (!IS_ERR_OR_NULL(bp)) {
+		user_data[0] = bp->attr.bp_addr;
+		user_data[1] = bp->attr.disabled ? 0 : bp->attr.bp_len;
+		user_data[2] = bp->attr.bp_type;
+	}
+
+	if (copy_to_user(datap, user_data, sizeof(user_data)))
+		return -EFAULT;
+
+	return 0;
+}
+
+static long ptrace_sethbpregs(struct task_struct *child, unsigned long idx,
+			      unsigned long __user *datap)
+{
+	struct perf_event *bp;
+	struct perf_event_attr attr;
+	unsigned long user_data[3];
+
+	if (idx >= RV_MAX_TRIGGERS)
+		return -EINVAL;
+
+	if (copy_from_user(user_data, datap, sizeof(user_data)))
+		return -EFAULT;
+
+	bp = child->thread.ptrace_bps[idx];
+	if (IS_ERR_OR_NULL(bp))
+		attr = bp->attr;
+	else
+		ptrace_breakpoint_init(&attr);
+
+	attr.bp_addr = user_data[0];
+	attr.bp_len = user_data[1];
+	attr.bp_type = user_data[2];
+	attr.disabled = !attr.bp_len;
+
+	if (IS_ERR_OR_NULL(bp)) {
+		bp = register_user_hw_breakpoint(&attr, ptrace_hbptriggered, NULL,
+					   child);
+		if (IS_ERR(bp))
+			return PTR_ERR(bp);
+
+		child->thread.ptrace_bps[idx] = bp;
+		return 0;
+	} else {
+		return modify_user_hw_breakpoint(bp, &attr);
+	}
+}
+#endif
+
 long arch_ptrace(struct task_struct *child, long request,
 		 unsigned long addr, unsigned long data)
 {
 	long ret = -EIO;
+	unsigned long __user *datap = (unsigned long __user *) data;
 
 	switch (request) {
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+	case PTRACE_GETHBPREGS:
+		ret = ptrace_gethbpregs(child, addr, datap);
+		break;
+
+	case PTRACE_SETHBPREGS:
+		ret = ptrace_sethbpregs(child, addr, datap);
+		break;
+#endif
 	default:
 		ret = ptrace_request(child, request, addr, data);
 		break;