Skip to contentSkip to conversation

mm/ksw: Introduce real-time Kernel Stack Watch debugging tool

PATCH Superseded Jinchao Wang 5 participants 36 messages Sep 4, 2025 – Sep 10, 2025

Subsystems (5)

v2 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v2 cover mm/ksw: Introduce real-time Kernel Stack Watch debugging tool

This patch series introduces **KStackWatch**, a lightweight kernel debugging tool for detecting kernel stack corruption in real time.

The motivation comes from scenarios where corruption occurs silently in one function but manifests later as a crash in another. Using KASAN may not reproduce the issue due to its heavy overhead. with no direct call trace linking the two. Such bugs are often extremely hard to debug with existing tools.
I demonstrate this scenario in **test2 (silent corruption test)**.

KStackWatch works by combining a hardware breakpoint with kprobe and fprobe. It can watch a stack canary or a selected local variable and detects the moment the corruption actually occurs. This allows developers to pinpoint the real source rather than only observing the final crash.

Key features include:

- Lightweight overhead with minimal impact on bug reproducibility
- Real-time detection of stack corruption
- Simple configuration through /proc/kstackwatch
- Support for recursive depth filter

To validate the approach, the patch includes a test module and a test script.

---
V2 incorporates feedback and builds on the previously proposed RFC [1] and V1 [2]. The changes are as follows:
V2:
* Make hardware breakpoint and stack operations architecture-independent.
V1:
Core Implementation

* Replaced kretprobe with fprobe for function exit hooking, as suggested
by Masami Hiramatsu

  *   Introduced per-task depth logic to track recursion across scheduling
  *   Removed the use of workqueue for a more efficient corruption check
  *   Reordered patches for better logical flow
  *   Simplified and improved commit messages throughout the series
  *   Removed initial archcheck which should be improved later

Testing and Architecture

* Replaced the multiple-thread test with silent corruption test
* Split self-tests into a separate patch to improve clarity.

Maintenance
* Added a new entry for KStackWatch to the MAINTAINERS file.

[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/
---

The series is structured as follows:

Jinchao Wang (18):
mm/ksw: add build system support
mm/ksw: add ksw_config struct and parser
mm/ksw: add /proc/kstackwatch interface
mm/ksw: add HWBP pre-allocation support
x86/hw_breakpoint: introduce arch_reinstall_hw_breakpoint() for atomic
context
perf/hw_breakpoint: add arch-independent hw_breakpoint_modify_local() mm/ksw: add atomic watch on/off operations
mm/ksw: add stack probe support
mm/ksw: implement stack canary and local var resolution logic mm/ksw: add per-task recursion depth tracking
mm/ksw: coordinate watch and stack for full functionality mm/ksw: add self-debug functions for kstackwatch watch mm/ksw: add test module
mm/ksw: add stack overflow test
mm/ksw: add simplified silent corruption test
mm/ksw: add recursive corruption test
tools/kstackwatch: add interactive test script for KStackWatch
MAINTAINERS: add entry for KStackWatch (Kernel Stack Watch)

 MAINTAINERS                           |   6 +
 arch/x86/include/asm/hw_breakpoint.h  |   1 +
 arch/x86/kernel/hw_breakpoint.c       |  50 +++++
 include/linux/hw_breakpoint.h         |   1 +
 kernel/events/hw_breakpoint.c         |  18 ++
 mm/Kconfig.debug                      |  20 ++
 mm/Makefile                           |   1 +
 mm/kstackwatch/Makefile               |   8 +
 mm/kstackwatch/kernel.c               | 260 +++++++++++++++++++++++
 mm/kstackwatch/kstackwatch.h          |  53 +++++
 mm/kstackwatch/kstackwatch_test.c     | 261 +++++++++++++++++++++++
 mm/kstackwatch/stack.c                | 286 ++++++++++++++++++++++++++
 mm/kstackwatch/watch.c                | 175 ++++++++++++++++
 tools/kstackwatch/kstackwatch_test.sh | 118 +++++++++++
 14 files changed, 1258 insertions(+)
 create mode 100644 mm/kstackwatch/Makefile
 create mode 100644 mm/kstackwatch/kernel.c
 create mode 100644 mm/kstackwatch/kstackwatch.h
 create mode 100644 mm/kstackwatch/kstackwatch_test.c
 create mode 100644 mm/kstackwatch/stack.c
 create mode 100644 mm/kstackwatch/watch.c
 create mode 100755 tools/kstackwatch/kstackwatch_test.sh
Signature · 1 line
2.43.0
#1 lore raw

PATCH v2 1/18 mm/ksw: add build system support

Add Kconfig and Makefile infrastructure for KStackWatch, a real-time tool for debugging kernel stack corruption.

The implementation is located under mm/kstackwatch/.

---
 mm/Kconfig.debug             | 10 ++++++++++
 mm/Makefile                  |  1 +
 mm/kstackwatch/Makefile      |  2 ++
 mm/kstackwatch/kernel.c      | 24 ++++++++++++++++++++++++
 mm/kstackwatch/kstackwatch.h |  5 +++++
 mm/kstackwatch/stack.c       |  1 +
 mm/kstackwatch/watch.c       |  1 +
 7 files changed, 44 insertions(+)
 create mode 100644 mm/kstackwatch/Makefile
 create mode 100644 mm/kstackwatch/kernel.c
 create mode 100644 mm/kstackwatch/kstackwatch.h
 create mode 100644 mm/kstackwatch/stack.c
 create mode 100644 mm/kstackwatch/watch.c
mm/Kconfig.debug +10 -0
index 32b65073d0cc..c2cc8c7b595f 100644
@@ -309,3 +309,13 @@ config PER_VMA_LOCK_STATS
 	  overhead in the page fault path.
 
 	  If in doubt, say N.
+
+config KSTACK_WATCH
+	tristate "Kernel Stack Watch"
+	depends on STACKPROTECTOR && HAVE_HW_BREAKPOINT && KPROBES && FPROBE
+	help
+	  A lightweight real-time debugging tool to detect stack corruption.
+	  It can watch either the canary or local variable and tracks
+	  the recursive depth of the monitored function.
+
+	  If unsure, say N.
mm/Makefile +1 -0
index ef54aa615d9d..665c9f2bf987 100644
@@ -92,6 +92,7 @@ obj-$(CONFIG_PAGE_POISONING) += page_poison.o
 obj-$(CONFIG_KASAN)	+= kasan/
 obj-$(CONFIG_KFENCE) += kfence/
 obj-$(CONFIG_KMSAN)	+= kmsan/
+obj-$(CONFIG_KSTACK_WATCH)	+= kstackwatch/
 obj-$(CONFIG_FAILSLAB) += failslab.o
 obj-$(CONFIG_FAIL_PAGE_ALLOC) += fail_page_alloc.o
 obj-$(CONFIG_MEMTEST)		+= memtest.o
mm/kstackwatch/Makefile new file +2 -0
new file mode 100644
index 000000000000..84a46cb9a766
@@ -0,0 +1,2 @@
+obj-$(CONFIG_KSTACK_WATCH)	+= kstackwatch.o
+kstackwatch-y := kernel.o stack.o watch.o
mm/kstackwatch/kernel.c new file +24 -0
new file mode 100644
index 000000000000..93379a0a0f7e
@@ -0,0 +1,24 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/module.h>
+
+MODULE_AUTHOR("Jinchao Wang");
+MODULE_DESCRIPTION("Kernel Stack Watch");
+MODULE_LICENSE("GPL");
+
+static int __init kstackwatch_init(void)
+{
+	pr_info("KSW: module loaded\n");
+	pr_info("KSW: usage:\n");
+	pr_info("KSW: echo 'function+ip_offset[+depth] [local_var_offset:local_var_len]' > /proc/kstackwatch\n");
+
+	return 0;
+}
+
+static void __exit kstackwatch_exit(void)
+{
+	pr_info("KSW: Module unloaded\n");
+}
+
+module_init(kstackwatch_init);
+module_exit(kstackwatch_exit);
mm/kstackwatch/kstackwatch.h new file +5 -0
new file mode 100644
index 000000000000..0273ef478a26
@@ -0,0 +1,5 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _KSTACKWATCH_H
+#define _KSTACKWATCH_H
+
+#endif /* _KSTACKWATCH_H */
mm/kstackwatch/stack.c new file +1 -0
new file mode 100644
index 000000000000..cec594032515
@@ -0,0 +1 @@
+// SPDX-License-Identifier: GPL-2.0
mm/kstackwatch/watch.c new file +1 -0
new file mode 100644
index 000000000000..cec594032515
@@ -0,0 +1 @@
+// SPDX-License-Identifier: GPL-2.0
Signature · 1 line
2.43.0
reviewer
#2 lore raw

Re: [PATCH v2 01/18] mm/ksw: add build system support

Quoted 2 lines · Jinchao Wang

Add Kconfig and Makefile infrastructure for KStackWatch, a real-time tool for debugging kernel stack corruption.

...

mm/kstackwatch/kernel.c line 13

Quoted 5 lines
mm/kstackwatch/kernel.c new file +5 -0
+static int __init kstackwatch_init(void)
+{
+	pr_info("KSW: module loaded\n");
+	pr_info("KSW: usage:\n");
+	pr_info("KSW: echo 'function+ip_offset[+depth] [local_var_offset:local_var_len]' > /proc/kstackwatch\n");

It feels like this belongs to Documentation/ rather than the kernel log.

Quoted 3 lines
mm/kstackwatch/kernel.c new file +3 -0
+	return 0;
+}
+
Signature · 2 lines
Sincerely yours,
Mike.
#3 lore raw

Re: [PATCH v2 01/18] mm/ksw: add build system support

Quoted 6 lines · Mike Rapoport
Quoted 2 lines · Jinchao Wang

Add Kconfig and Makefile infrastructure for KStackWatch, a real-time tool for debugging kernel stack corruption.

...

Quoted 7 lines

mm/kstackwatch/kernel.c line 13

Quoted 5 lines
mm/kstackwatch/kernel.c new file +5 -0
+static int __init kstackwatch_init(void)
+{
+	pr_info("KSW: module loaded\n");
+	pr_info("KSW: usage:\n");
+	pr_info("KSW: echo 'function+ip_offset[+depth] [local_var_offset:local_var_len]' > /proc/kstackwatch\n");

It feels like this belongs to Documentation/ rather than the kernel log.

Thanks for the feedback, I will add a document to replace these logs.

Quoted 8 lines
Quoted 4 lines
mm/kstackwatch/kernel.c new file +3 -0
+	return 0;
+}
+
Signature · 2 lines
Sincerely yours,
Mike.
#4 lore raw

PATCH v2 2/18 mm/ksw: add ksw_config struct and parser

In reply to Jinchao Wang

Add struct ksw_config and ksw_parse_config() to parse user string.

Update Makefile to pass compilation.

---
 mm/kstackwatch/Makefile      |  2 ++
 mm/kstackwatch/kernel.c      | 70 +++++++++++++++++++++++++++++++++++-
 mm/kstackwatch/kstackwatch.h | 34 ++++++++++++++++++
 3 files changed, 105 insertions(+), 1 deletion(-)
mm/kstackwatch/Makefile +2 -0
index 84a46cb9a766..d422f0e114dd 100644
@@ -1,2 +1,4 @@
 obj-$(CONFIG_KSTACK_WATCH)	+= kstackwatch.o
 kstackwatch-y := kernel.o stack.o watch.o
+
+CFLAGS_kernel.o := -Wno-error=unused-function
mm/kstackwatch/kernel.c +69 -1

80 lines not on this page · raw message

mm/kstackwatch/kstackwatch.h +34 -0
index 0273ef478a26..b5f1835586c1 100644
@@ -2,4 +2,38 @@
 #ifndef _KSTACKWATCH_H
 #define _KSTACKWATCH_H
 
+#include <linux/types.h>
+
+#define MAX_FUNC_NAME_LEN 64
+#define MAX_CONFIG_STR_LEN 128
+#define MAX_FRAME_SEARCH 128
+
+enum watch_type {
+	WATCH_CANARY = 0,
+	WATCH_LOCAL_VAR,
+};
+
+struct ksw_config {
+	/* function part */
+	char function[MAX_FUNC_NAME_LEN];
+	u16 ip_offset;
+	u16 depth;
+
+	/* local var, useless for canary watch */
+	/* offset from rsp at function+ip_offset */
+	u16 local_var_offset;
+
+	/*
+	 * local var size (1,2,4,8 bytes)
+	 * it will be the watching len
+	 */
+	u16 local_var_len;
+
+	/* easy for understand*/
+	enum watch_type type;
+
+	/* save to show */
+	char config_str[MAX_CONFIG_STR_LEN];
+};
+
 #endif /* _KSTACKWATCH_H */
Signature · 1 line
2.43.0
reviewer
#5 lore raw

Re: [PATCH v2 02/18] mm/ksw: add ksw_config struct and parser

Quoted 16 lines · Jinchao Wang

Add struct ksw_config and ksw_parse_config() to parse user string.

Update Makefile to pass compilation.

---
 mm/kstackwatch/Makefile      |  2 ++
 mm/kstackwatch/kernel.c      | 70 +++++++++++++++++++++++++++++++++++-
 mm/kstackwatch/kstackwatch.h | 34 ++++++++++++++++++
 3 files changed, 105 insertions(+), 1 deletion(-)
mm/kstackwatch/Makefile +0 -0
index 84a46cb9a766..d422f0e114dd 100644

mm/kstackwatch/Makefile line 4

Quoted 4 lines
mm/kstackwatch/Makefile +2 -0
@@ -1,2 +1,4 @@
 obj-$(CONFIG_KSTACK_WATCH)	+= kstackwatch.o
 kstackwatch-y := kernel.o stack.o watch.o
+
+CFLAGS_kernel.o := -Wno-error=unused-function

Can't you just add the function along with the code that uses it?

Signature · 2 lines
Sincerely yours,
Mike.
#6 lore raw

Re: [PATCH v2 02/18] mm/ksw: add ksw_config struct and parser

Quoted 12 lines · Mike Rapoport
Quoted 11 lines · Jinchao Wang

Add struct ksw_config and ksw_parse_config() to parse user string.

Update Makefile to pass compilation.

---
 mm/kstackwatch/Makefile      |  2 ++
 mm/kstackwatch/kernel.c      | 70 +++++++++++++++++++++++++++++++++++-
 mm/kstackwatch/kstackwatch.h | 34 ++++++++++++++++++
 3 files changed, 105 insertions(+), 1 deletion(-)
Quoted 11 lines

mm/kstackwatch/Makefile line 4

Quoted 9 lines
mm/kstackwatch/Makefile +2 -0
index 84a46cb9a766..d422f0e114dd 100644
@@ -1,2 +1,4 @@
 obj-$(CONFIG_KSTACK_WATCH)	+= kstackwatch.o
 kstackwatch-y := kernel.o stack.o watch.o
+
+CFLAGS_kernel.o := -Wno-error=unused-function

Can't you just add the function along with the code that uses it?

Thanks for the feedback.

The function ksw_parse_config is called deeply in a later patch, so the 'error: ununsed function' would persist even if I added the caller now.

To keep this patch clean for review, I only include functions that form a self-contained unit.

I will add a TODO comment to indicate that the CFLAGS addition is temporary for this patch only and will be removed in a follow-up patch.

Quoted 4 lines
Signature · 3 lines
-- 
Sincerely yours,
Mike.
#7 lore raw

PATCH v2 3/18 mm/ksw: add /proc/kstackwatch interface

In reply to Jinchao Wang

Provide the /proc/kstackwatch file to read or update the KSW configuration. Writing a valid config string starts watching; empty input stops watching. Invalid input stops watching and reports an error.

Allocate a ksw_config struct on module init and free it on exit. Manage watching state with ksw_start_watching() and ksw_stop_watching().

---
 mm/kstackwatch/kernel.c | 140 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 140 insertions(+)
mm/kstackwatch/kernel.c +140 -0
index 4a6dc49449fe..95ade95abde1 100644
@@ -1,7 +1,10 @@
 // SPDX-License-Identifier: GPL-2.0
 #include <linux/kstrtox.h>
 #include <linux/module.h>
+#include <linux/proc_fs.h>
+#include <linux/seq_file.h>
 #include <linux/string.h>
+#include <linux/uaccess.h>
 
 #include "kstackwatch.h"
 
@@ -9,6 +12,29 @@ MODULE_AUTHOR("Jinchao Wang");
 MODULE_DESCRIPTION("Kernel Stack Watch");
 MODULE_LICENSE("GPL");
 
+struct ksw_config *ksw_config;
+bool watching_active;
+
+bool panic_on_catch;
+module_param(panic_on_catch, bool, 0644);
+MODULE_PARM_DESC(panic_on_catch,
+		 "Trigger a kernel panic immediately on corruption catch");
+
+static int ksw_start_watching(void)
+{
+	watching_active = true;
+
+	pr_info("KSW: start watching %s\n", ksw_config->config_str);
+	return 0;
+}
+
+static void ksw_stop_watching(void)
+{
+	watching_active = false;
+
+	pr_info("KSW: stop watching %s\n", ksw_config->config_str);
+}
+
 /*
  * Format of the configuration string:
  *    function+ip_offset[+depth] [local_var_offset:local_var_len]
@@ -74,8 +100,114 @@ static int ksw_parse_config(char *buf, struct ksw_config *config)
 	return 0;
 }
 
+/**
+ * kstackwatch_proc_write - Handle writes to the /proc/kstackwatch file
+ * @file: file struct for the proc entry
+ * @buffer: user-space buffer containing the command string
+ * @count: the number of bytes from the user-space buffer
+ * @pos: file offset
+ *
+ * This function processes user input to control the kernel stack watcher
+ * Before attempting to process any new configuration. It handles three
+ * cases based on the input string, In all three cases, the system will
+ * clear its state first, with subsequent actions determined by the input:
+ *
+ * 1. An empty or whitespace-only string
+ *    Return a success code
+ *
+ * 2. An invalid configuration string
+ *    Return a error code
+ *
+ * 3. A valid configuration string
+ *    Start a new stack watch, return a success code
+ *
+ * Return: The number of bytes successfully processed on success,
+ * or a negative error code on failure.
+ */
+static ssize_t kstackwatch_proc_write(struct file *file,
+				      const char __user *buffer, size_t count,
+				      loff_t *pos)
+{
+	char input[MAX_CONFIG_STR_LEN];
+	int ret;
+
+	if (count == 0 || count >= sizeof(input))
+		return -EINVAL;
+
+	if (copy_from_user(input, buffer, count))
+		return -EFAULT;
+
+	if (watching_active)
+		ksw_stop_watching();
+	memset(ksw_config, 0, sizeof(*ksw_config));
+
+	input[count] = '\0';
+	strim(input);
+
+	/* case 1 */
+	if (!strlen(input)) {
+		pr_info("KSW: config cleared\n");
+		return count;
+	}
+
+	ret = ksw_parse_config(input, ksw_config);
+	if (ret) {
+		/* case 2 */
+		pr_err("KSW: Failed to parse config %d\n", ret);
+		return ret;
+	}
+
+	/* case 3 */
+	ret = ksw_start_watching();
+	if (ret) {
+		pr_err("KSW: Failed to start watching with %d\n", ret);
+		return ret;
+	}
+
+	return count;
+}
+
+static int kstackwatch_proc_show(struct seq_file *m, void *v)
+{
+	if (watching_active) {
+		seq_printf(m, "%s\n", ksw_config->config_str);
+	} else {
+		seq_puts(m, "not watching\n");
+		seq_puts(m, "\nusage:\n");
+		seq_puts(
+			m,
+			" echo 'function+ip_offset[+depth] [local_var_offset:local_var_len]' > /proc/kstackwatch\n");
+		seq_puts(m, "  Watch the canary without the local var part.");
+	}
+
+	return 0;
+}
+
+static int kstackwatch_proc_open(struct inode *inode, struct file *file)
+{
+	return single_open(file, kstackwatch_proc_show, NULL);
+}
+
+static const struct proc_ops kstackwatch_proc_ops = {
+	.proc_open = kstackwatch_proc_open,
+	.proc_read = seq_read,
+	.proc_write = kstackwatch_proc_write,
+	.proc_lseek = seq_lseek,
+	.proc_release = single_release,
+};
+
 static int __init kstackwatch_init(void)
 {
+	ksw_config = kmalloc(sizeof(*ksw_config), GFP_KERNEL);
+	if (!ksw_config)
+		return -ENOMEM;
+
+	/* Create proc interface */
+	if (!proc_create("kstackwatch", 0644, NULL, &kstackwatch_proc_ops)) {
+		pr_err("KSW: create proc kstackwatch fail");
+		return -ENOMEM;
+	}
+
 	pr_info("KSW: module loaded\n");
 	pr_info("KSW: usage:\n");
 	pr_info("KSW: echo 'function+ip_offset[+depth] [local_var_offset:local_var_len]' > /proc/kstackwatch\n");
@@ -85,6 +217,14 @@ static int __init kstackwatch_init(void)
 
 static void __exit kstackwatch_exit(void)
 {
+	/* Cleanup active watching */
+	if (watching_active)
+		ksw_stop_watching();
+
+	/* Remove proc interface */
+	remove_proc_entry("kstackwatch", NULL);
+	kfree(ksw_config);
+
 	pr_info("KSW: Module unloaded\n");
 }
 
Signature · 1 line
2.43.0
reviewer
#8 lore raw

Re: [PATCH v2 03/18] mm/ksw: add /proc/kstackwatch interface

Quoted 28 lines · Jinchao Wang

Provide the /proc/kstackwatch file to read or update the KSW configuration. Writing a valid config string starts watching; empty input stops watching. Invalid input stops watching and reports an error.

Allocate a ksw_config struct on module init and free it on exit. Manage watching state with ksw_start_watching() and ksw_stop_watching().

---
 mm/kstackwatch/kernel.c | 140 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 140 insertions(+)
mm/kstackwatch/kernel.c +3 -0
index 4a6dc49449fe..95ade95abde1 100644
@@ -1,7 +1,10 @@
 // SPDX-License-Identifier: GPL-2.0
 #include <linux/kstrtox.h>
 #include <linux/module.h>
+#include <linux/proc_fs.h>
+#include <linux/seq_file.h>
 #include <linux/string.h>
+#include <linux/uaccess.h>
 
 #include "kstackwatch.h"
 

mm/kstackwatch/kernel.c MODULE_AUTHOR("Jinchao Wang"); · line 15

Quoted 4 lines
mm/kstackwatch/kernel.c +1 -0
@@ -9,6 +12,29 @@ MODULE_AUTHOR("Jinchao Wang");
 MODULE_DESCRIPTION("Kernel Stack Watch");
 MODULE_LICENSE("GPL");
 
+struct ksw_config *ksw_config;

Does a global ksw_config imply that this is a singleton? What happens when there are several "echo .. > /proc/kstackwatch"? And even more interesting what happens if they are parallel?

Quoted 10 lines
mm/kstackwatch/kernel.c +10 -0
+bool watching_active;
+
+bool panic_on_catch;
+module_param(panic_on_catch, bool, 0644);
+MODULE_PARM_DESC(panic_on_catch,
+		 "Trigger a kernel panic immediately on corruption catch");
+
+static int ksw_start_watching(void)
+{
+	watching_active = true;

mm/kstackwatch/kernel.c MODULE_AUTHOR("Jinchao Wang"); · line 35

Quoted 10 lines
mm/kstackwatch/kernel.c +10 -0
+
+	pr_info("KSW: start watching %s\n", ksw_config->config_str);
+	return 0;
+}
+
+static void ksw_stop_watching(void)
+{
+	watching_active = false;
+
+	pr_info("KSW: stop watching %s\n", ksw_config->config_str);

This module is overly verbose. Do you really need all the printks?

Quoted 1 line
mm/kstackwatch/kernel.c +1 -0
+}

...

mm/kstackwatch/kernel.c static int ksw_parse_config(char *buf, struct ksw_config *config) · line 206

Quoted 8 lines

static int __init kstackwatch_init(void)
{

mm/kstackwatch/kernel.c +6 -0
+	ksw_config = kmalloc(sizeof(*ksw_config), GFP_KERNEL);
+	if (!ksw_config)
+		return -ENOMEM;
+
+	/* Create proc interface */
+	if (!proc_create("kstackwatch", 0644, NULL, &kstackwatch_proc_ops)) {

ksw_config must be freed here

Quoted 25 lines
mm/kstackwatch/kernel.c +12 -0
+		pr_err("KSW: create proc kstackwatch fail");
+		return -ENOMEM;
+	}
+
 	pr_info("KSW: module loaded\n");
 	pr_info("KSW: usage:\n");
 	pr_info("KSW: echo 'function+ip_offset[+depth] [local_var_offset:local_var_len]' > /proc/kstackwatch\n");
@@ -85,6 +217,14 @@ static int __init kstackwatch_init(void)
 
 static void __exit kstackwatch_exit(void)
 {
+	/* Cleanup active watching */
+	if (watching_active)
+		ksw_stop_watching();
+
+	/* Remove proc interface */
+	remove_proc_entry("kstackwatch", NULL);
+	kfree(ksw_config);
+
 	pr_info("KSW: Module unloaded\n");
 }
 
Signature · 1 line
2.43.0
Signature · 2 lines
Sincerely yours,
Mike.
#9 lore raw

Re: [PATCH v2 03/18] mm/ksw: add /proc/kstackwatch interface

Quoted 28 lines · Mike Rapoport
Quoted 27 lines · Jinchao Wang

Provide the /proc/kstackwatch file to read or update the KSW configuration. Writing a valid config string starts watching; empty input stops watching. Invalid input stops watching and reports an error.

Allocate a ksw_config struct on module init and free it on exit. Manage watching state with ksw_start_watching() and ksw_stop_watching().

---
 mm/kstackwatch/kernel.c | 140 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 140 insertions(+)
mm/kstackwatch/kernel.c +3 -0
index 4a6dc49449fe..95ade95abde1 100644
@@ -1,7 +1,10 @@
 // SPDX-License-Identifier: GPL-2.0
 #include <linux/kstrtox.h>
 #include <linux/module.h>
+#include <linux/proc_fs.h>
+#include <linux/seq_file.h>
 #include <linux/string.h>
+#include <linux/uaccess.h>
 
 #include "kstackwatch.h"
 
Quoted 7 lines

mm/kstackwatch/kernel.c MODULE_AUTHOR("Jinchao Wang"); · line 15

Quoted 5 lines
mm/kstackwatch/kernel.c +1 -0
@@ -9,6 +12,29 @@ MODULE_AUTHOR("Jinchao Wang");
 MODULE_DESCRIPTION("Kernel Stack Watch");
 MODULE_LICENSE("GPL");
 
+struct ksw_config *ksw_config;

Does a global ksw_config imply that this is a singleton?

Yes, it is.

Quoted 2 lines

What happens when there are several "echo .. > /proc/kstackwatch"? And even more interesting what happens if they are parallel?

I did not consider this deeply enough.
I will address it properly in the next series.
Thank you for pointing it out.

Quoted 15 lines
Quoted 15 lines
mm/kstackwatch/kernel.c +14 -0
+bool watching_active;
+
+bool panic_on_catch;
+module_param(panic_on_catch, bool, 0644);
+MODULE_PARM_DESC(panic_on_catch,
+		 "Trigger a kernel panic immediately on corruption catch");
+
+static int ksw_start_watching(void)
+{
+	watching_active = true;
+
+	pr_info("KSW: start watching %s\n", ksw_config->config_str);
+	return 0;
+}
Quoted 8 lines

mm/kstackwatch/kernel.c MODULE_AUTHOR("Jinchao Wang"); · line 35

Quoted 6 lines
mm/kstackwatch/kernel.c +6 -0
+
+static void ksw_stop_watching(void)
+{
+	watching_active = false;
+
+	pr_info("KSW: stop watching %s\n", ksw_config->config_str);

This module is overly verbose. Do you really need all the printks?

You’re right — many of these printks are for early debugging and not needed for production. I will remove or downgrade them to pr_debug() in the next version.

For critical paths, I’ll ensure only actionable or WARN-level messages remain.

Appreciate the push for cleaner logging.

Quoted 45 lines
Quoted 2 lines
mm/kstackwatch/kernel.c +1 -0
+}

...

mm/kstackwatch/kernel.c static int ksw_parse_config(char *buf, struct ksw_config *config) · line 206

Quoted 8 lines

static int __init kstackwatch_init(void)
{

mm/kstackwatch/kernel.c +6 -0
+	ksw_config = kmalloc(sizeof(*ksw_config), GFP_KERNEL);
+	if (!ksw_config)
+		return -ENOMEM;
+
+	/* Create proc interface */
+	if (!proc_create("kstackwatch", 0644, NULL, &kstackwatch_proc_ops)) {

ksw_config must be freed here

Quoted 25 lines
mm/kstackwatch/kernel.c +12 -0
+		pr_err("KSW: create proc kstackwatch fail");
+		return -ENOMEM;
+	}
+
 	pr_info("KSW: module loaded\n");
 	pr_info("KSW: usage:\n");
 	pr_info("KSW: echo 'function+ip_offset[+depth] [local_var_offset:local_var_len]' > /proc/kstackwatch\n");
@@ -85,6 +217,14 @@ static int __init kstackwatch_init(void)
 
 static void __exit kstackwatch_exit(void)
 {
+	/* Cleanup active watching */
+	if (watching_active)
+		ksw_stop_watching();
+
+	/* Remove proc interface */
+	remove_proc_entry("kstackwatch", NULL);
+	kfree(ksw_config);
+
 	pr_info("KSW: Module unloaded\n");
 }
 
Signature · 1 line
2.43.0
Signature · 2 lines
Sincerely yours,
Mike.
#10 lore raw

PATCH v2 4/18 mm/ksw: add HWBP pre-allocation support

In reply to Jinchao Wang

Pre-allocate per-CPU hardware breakpoints at init with a dummy address, which will be retargeted dynamically in kprobe handler. This avoids allocation in atomic contexts.

---
 mm/kstackwatch/kstackwatch.h |  6 ++++
 mm/kstackwatch/watch.c       | 62 ++++++++++++++++++++++++++++++++++++
 2 files changed, 68 insertions(+)
mm/kstackwatch/kstackwatch.h +6 -0
index b5f1835586c1..2318779bde70 100644
@@ -36,4 +36,10 @@ struct ksw_config {
 	char config_str[MAX_CONFIG_STR_LEN];
 };
 
+extern bool panic_on_catch;
+
+/* watch management */
+int ksw_watch_init(struct ksw_config *config);
+void ksw_watch_exit(void);
+
 #endif /* _KSTACKWATCH_H */
mm/kstackwatch/watch.c +62 -0

63 lines not on this page · raw message

Signature · 1 line
2.43.0
#11 lore raw

PATCH v2 5/18 x86/hw_breakpoint: introduce arch_reinstall_hw_breakpoint() for atomic context

In reply to Jinchao Wang

Introduce arch_reinstall_hw_breakpoint() to update hardware breakpoint parameters (address, length, type) without freeing and reallocating the debug register slot.

This allows atomic updates in contexts where memory allocation is not permitted, such as kprobe handlers.

---
 arch/x86/include/asm/hw_breakpoint.h |  1 +
 arch/x86/kernel/hw_breakpoint.c      | 50 ++++++++++++++++++++++++++++
 2 files changed, 51 insertions(+)
arch/x86/include/asm/hw_breakpoint.h +1 -0
index 0bc931cd0698..bb7c70ad22fe 100644
@@ -59,6 +59,7 @@ extern int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
 
 
 int arch_install_hw_breakpoint(struct perf_event *bp);
+int arch_reinstall_hw_breakpoint(struct perf_event *bp);
 void arch_uninstall_hw_breakpoint(struct perf_event *bp);
 void hw_breakpoint_pmu_read(struct perf_event *bp);
 void hw_breakpoint_pmu_unthrottle(struct perf_event *bp);
arch/x86/kernel/hw_breakpoint.c +50 -0

56 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#12 lore raw

Re: [PATCH v2 05/18] x86/hw_breakpoint: introduce arch_reinstall_hw_breakpoint() for atomic context

Quoted 72 lines · Jinchao Wang

Introduce arch_reinstall_hw_breakpoint() to update hardware breakpoint parameters (address, length, type) without freeing and reallocating the debug register slot.

This allows atomic updates in contexts where memory allocation is not permitted, such as kprobe handlers.

---
 arch/x86/include/asm/hw_breakpoint.h |  1 +
 arch/x86/kernel/hw_breakpoint.c      | 50 ++++++++++++++++++++++++++++
 2 files changed, 51 insertions(+)
arch/x86/include/asm/hw_breakpoint.h +1 -0
index 0bc931cd0698..bb7c70ad22fe 100644
@@ -59,6 +59,7 @@ extern int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
 
 
 int arch_install_hw_breakpoint(struct perf_event *bp);
+int arch_reinstall_hw_breakpoint(struct perf_event *bp);
 void arch_uninstall_hw_breakpoint(struct perf_event *bp);
 void hw_breakpoint_pmu_read(struct perf_event *bp);
 void hw_breakpoint_pmu_unthrottle(struct perf_event *bp);
arch/x86/kernel/hw_breakpoint.c +39 -0
index b01644c949b2..89135229ed21 100644
@@ -132,6 +132,56 @@ int arch_install_hw_breakpoint(struct perf_event *bp)
 	return 0;
 }
 
+/*
+ * Reinstall a hardware breakpoint on the current CPU.
+ *
+ * This function is used to re-establish a perf counter hardware breakpoint.
+ * It finds the debug address register slot previously allocated for the
+ * breakpoint and re-enables it by writing the address to the debug register
+ * and setting the corresponding bits in the debug control register (DR7).
+ *
+ * It is expected that the breakpoint's event context lock is already held
+ * and interrupts are disabled, ensuring atomicity and safety from other
+ * event handlers.
+ */
+int arch_reinstall_hw_breakpoint(struct perf_event *bp)
+{
+	struct arch_hw_breakpoint *info = counter_arch_bp(bp);
+	unsigned long *dr7;
+	int i;
+
+	lockdep_assert_irqs_disabled();
+
+	for (i = 0; i < HBP_NUM; i++) {
+		struct perf_event **slot = this_cpu_ptr(&bp_per_reg[i]);
+
+		if (*slot == bp)
+			break;
+	}
+
+	if (WARN_ONCE(i == HBP_NUM, "Can't find a matching breakpoint slot"))
+		return -EINVAL;
+
+	set_debugreg(info->address, i);
+	__this_cpu_write(cpu_debugreg[i], info->address);
+
+	dr7 = this_cpu_ptr(&cpu_dr7);
+	*dr7 |= encode_dr7(i, info->len, info->type);
+
+	/*
+	 * Ensure we first write cpu_dr7 before we set the DR7 register.
+	 * This ensures an NMI never see cpu_dr7 0 when DR7 is not.

arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 183

Quoted 10 lines
arch/x86/kernel/hw_breakpoint.c +10 -0
+	 */
+	barrier();
+
+	set_debugreg(*dr7, 7);
+	if (info->mask)
+		amd_set_dr_addr_mask(info->mask, i);
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(arch_reinstall_hw_breakpoint);

Yeah, I think not. For one this is an almost verbatim copy of arch_install_hw_breakpoint() with zero re-use. Surely you've been taught better?

And why would we want to export guts like this?

#13 lore raw

Re: [PATCH v2 05/18] x86/hw_breakpoint: introduce arch_reinstall_hw_breakpoint() for atomic context

Quoted 79 lines · Peter Zijlstra
Quoted 78 lines · Jinchao Wang

Introduce arch_reinstall_hw_breakpoint() to update hardware breakpoint parameters (address, length, type) without freeing and reallocating the debug register slot.

This allows atomic updates in contexts where memory allocation is not permitted, such as kprobe handlers.

---
 arch/x86/include/asm/hw_breakpoint.h |  1 +
 arch/x86/kernel/hw_breakpoint.c      | 50 ++++++++++++++++++++++++++++
 2 files changed, 51 insertions(+)
arch/x86/include/asm/hw_breakpoint.h +1 -0
index 0bc931cd0698..bb7c70ad22fe 100644
@@ -59,6 +59,7 @@ extern int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
 
 
 int arch_install_hw_breakpoint(struct perf_event *bp);
+int arch_reinstall_hw_breakpoint(struct perf_event *bp);
 void arch_uninstall_hw_breakpoint(struct perf_event *bp);
 void hw_breakpoint_pmu_read(struct perf_event *bp);
 void hw_breakpoint_pmu_unthrottle(struct perf_event *bp);
arch/x86/kernel/hw_breakpoint.c +45 -0
index b01644c949b2..89135229ed21 100644
@@ -132,6 +132,56 @@ int arch_install_hw_breakpoint(struct perf_event *bp)
 	return 0;
 }
 
+/*
+ * Reinstall a hardware breakpoint on the current CPU.
+ *
+ * This function is used to re-establish a perf counter hardware breakpoint.
+ * It finds the debug address register slot previously allocated for the
+ * breakpoint and re-enables it by writing the address to the debug register
+ * and setting the corresponding bits in the debug control register (DR7).
+ *
+ * It is expected that the breakpoint's event context lock is already held
+ * and interrupts are disabled, ensuring atomicity and safety from other
+ * event handlers.
+ */
+int arch_reinstall_hw_breakpoint(struct perf_event *bp)
+{
+	struct arch_hw_breakpoint *info = counter_arch_bp(bp);
+	unsigned long *dr7;
+	int i;
+
+	lockdep_assert_irqs_disabled();
+
+	for (i = 0; i < HBP_NUM; i++) {
+		struct perf_event **slot = this_cpu_ptr(&bp_per_reg[i]);
+
+		if (*slot == bp)
+			break;
+	}
+
+	if (WARN_ONCE(i == HBP_NUM, "Can't find a matching breakpoint slot"))
+		return -EINVAL;
+
+	set_debugreg(info->address, i);
+	__this_cpu_write(cpu_debugreg[i], info->address);
+
+	dr7 = this_cpu_ptr(&cpu_dr7);
+	*dr7 |= encode_dr7(i, info->len, info->type);
+
+	/*
+	 * Ensure we first write cpu_dr7 before we set the DR7 register.
+	 * This ensures an NMI never see cpu_dr7 0 when DR7 is not.
+	 */
+	barrier();
+
+	set_debugreg(*dr7, 7);
+	if (info->mask)
+		amd_set_dr_addr_mask(info->mask, i);
Quoted 8 lines

arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 183

Quoted 4 lines
arch/x86/kernel/hw_breakpoint.c +4 -0
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(arch_reinstall_hw_breakpoint);

Yeah, I think not. For one this is an almost verbatim copy of arch_install_hw_breakpoint() with zero re-use. Surely you've been taught better?

I introduced this to modify bp_addr in atomic context in my RFC series. I thought it was clearer to split the introduction and refactor. And then It was used in the wprobe series, so I left it as introduced in the RFC series.

I agree your suggestion is right. I am willing to refactor after wprobe.

Quoted 2 lines

And why would we want to export guts like this?

I wanted to introduce a real-time stack corruption debugging tool, which needs a helper to change bp_addr in atomic context (kprobe handler). And wprobe needs it also.

#14 lore raw

Re: [PATCH v2 05/18] x86/hw_breakpoint: introduce arch_reinstall_hw_breakpoint() for atomic context

Quoted 88 lines · On Mon, 8 Sep 2025 13:20:51 +0800 Jinchao Wang <[email protected]> wrote:
Quoted 79 lines · Peter Zijlstra
Quoted 78 lines · Jinchao Wang

Introduce arch_reinstall_hw_breakpoint() to update hardware breakpoint parameters (address, length, type) without freeing and reallocating the debug register slot.

This allows atomic updates in contexts where memory allocation is not permitted, such as kprobe handlers.

---
 arch/x86/include/asm/hw_breakpoint.h |  1 +
 arch/x86/kernel/hw_breakpoint.c      | 50 ++++++++++++++++++++++++++++
 2 files changed, 51 insertions(+)
arch/x86/include/asm/hw_breakpoint.h +1 -0
index 0bc931cd0698..bb7c70ad22fe 100644
@@ -59,6 +59,7 @@ extern int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
 
 
 int arch_install_hw_breakpoint(struct perf_event *bp);
+int arch_reinstall_hw_breakpoint(struct perf_event *bp);
 void arch_uninstall_hw_breakpoint(struct perf_event *bp);
 void hw_breakpoint_pmu_read(struct perf_event *bp);
 void hw_breakpoint_pmu_unthrottle(struct perf_event *bp);
arch/x86/kernel/hw_breakpoint.c +45 -0
index b01644c949b2..89135229ed21 100644
@@ -132,6 +132,56 @@ int arch_install_hw_breakpoint(struct perf_event *bp)
 	return 0;
 }
 
+/*
+ * Reinstall a hardware breakpoint on the current CPU.
+ *
+ * This function is used to re-establish a perf counter hardware breakpoint.
+ * It finds the debug address register slot previously allocated for the
+ * breakpoint and re-enables it by writing the address to the debug register
+ * and setting the corresponding bits in the debug control register (DR7).
+ *
+ * It is expected that the breakpoint's event context lock is already held
+ * and interrupts are disabled, ensuring atomicity and safety from other
+ * event handlers.
+ */
+int arch_reinstall_hw_breakpoint(struct perf_event *bp)
+{
+	struct arch_hw_breakpoint *info = counter_arch_bp(bp);
+	unsigned long *dr7;
+	int i;
+
+	lockdep_assert_irqs_disabled();
+
+	for (i = 0; i < HBP_NUM; i++) {
+		struct perf_event **slot = this_cpu_ptr(&bp_per_reg[i]);
+
+		if (*slot == bp)
+			break;
+	}
+
+	if (WARN_ONCE(i == HBP_NUM, "Can't find a matching breakpoint slot"))
+		return -EINVAL;
+
+	set_debugreg(info->address, i);
+	__this_cpu_write(cpu_debugreg[i], info->address);
+
+	dr7 = this_cpu_ptr(&cpu_dr7);
+	*dr7 |= encode_dr7(i, info->len, info->type);
+
+	/*
+	 * Ensure we first write cpu_dr7 before we set the DR7 register.
+	 * This ensures an NMI never see cpu_dr7 0 when DR7 is not.
+	 */
+	barrier();
+
+	set_debugreg(*dr7, 7);
+	if (info->mask)
+		amd_set_dr_addr_mask(info->mask, i);
Quoted 8 lines

arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 183

Quoted 4 lines
arch/x86/kernel/hw_breakpoint.c +4 -0
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(arch_reinstall_hw_breakpoint);

Yeah, I think not. For one this is an almost verbatim copy of arch_install_hw_breakpoint() with zero re-use. Surely you've been taught better?

Quoted 6 lines

I introduced this to modify bp_addr in atomic context in my RFC series. I thought it was clearer to split the introduction and refactor. And then It was used in the wprobe series, so I left it as introduced in the RFC series.

I agree your suggestion is right. I am willing to refactor after wprobe.

I'm OK to refactor it to reuse arch_install_hw_breakpoint(). My point is to have CONFIG_HAVE_REINSTALL_HW_BREAKPOINT so that we can easily implement the dependency for other features which requires this feature in Kconfig level.

Quoted 4 lines
Quoted 1 line

And why would we want to export guts like this?

I wanted to introduce a real-time stack corruption debugging tool, which needs a helper to change bp_addr in atomic context (kprobe handler). And wprobe needs it also.

I agree with Peter, it should not expose the architecture dependent code directly. Instead, we need a wrapper.

Thank you,

Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
#15 lore raw

Re: [PATCH v2 05/18] x86/hw_breakpoint: introduce arch_reinstall_hw_breakpoint() for atomic context

Quoted 101 lines · Masami Hiramatsu (Google)
Quoted 87 lines · On Mon, 8 Sep 2025 13:20:51 +0800 Jinchao Wang <[email protected]> wrote:
Quoted 78 lines · Peter Zijlstra
Quoted 77 lines · Jinchao Wang

Introduce arch_reinstall_hw_breakpoint() to update hardware breakpoint parameters (address, length, type) without freeing and reallocating the debug register slot.

This allows atomic updates in contexts where memory allocation is not permitted, such as kprobe handlers.

---
  arch/x86/include/asm/hw_breakpoint.h |  1 +
  arch/x86/kernel/hw_breakpoint.c      | 50 ++++++++++++++++++++++++++++
  2 files changed, 51 insertions(+)
arch/x86/include/asm/hw_breakpoint.h +1 -0
index 0bc931cd0698..bb7c70ad22fe 100644
@@ -59,6 +59,7 @@ extern int hw_breakpoint_exceptions_notify(struct notifier_block *unused,
 
 
  int arch_install_hw_breakpoint(struct perf_event *bp);
+int arch_reinstall_hw_breakpoint(struct perf_event *bp);
  void arch_uninstall_hw_breakpoint(struct perf_event *bp);
  void hw_breakpoint_pmu_read(struct perf_event *bp);
  void hw_breakpoint_pmu_unthrottle(struct perf_event *bp);
arch/x86/kernel/hw_breakpoint.c +44 -0
index b01644c949b2..89135229ed21 100644
@@ -132,6 +132,56 @@ int arch_install_hw_breakpoint(struct perf_event *bp)
  	return 0;
  }
 
+/*
+ * Reinstall a hardware breakpoint on the current CPU.
+ *
+ * This function is used to re-establish a perf counter hardware breakpoint.
+ * It finds the debug address register slot previously allocated for the
+ * breakpoint and re-enables it by writing the address to the debug register
+ * and setting the corresponding bits in the debug control register (DR7).
+ *
+ * It is expected that the breakpoint's event context lock is already held
+ * and interrupts are disabled, ensuring atomicity and safety from other
+ * event handlers.
+ */
+int arch_reinstall_hw_breakpoint(struct perf_event *bp)
+{
+	struct arch_hw_breakpoint *info = counter_arch_bp(bp);
+	unsigned long *dr7;
+	int i;
+
+	lockdep_assert_irqs_disabled();
+
+	for (i = 0; i < HBP_NUM; i++) {
+		struct perf_event **slot = this_cpu_ptr(&bp_per_reg[i]);
+
+		if (*slot == bp)
+			break;
+	}
+
+	if (WARN_ONCE(i == HBP_NUM, "Can't find a matching breakpoint slot"))
+		return -EINVAL;
+
+	set_debugreg(info->address, i);
+	__this_cpu_write(cpu_debugreg[i], info->address);
+
+	dr7 = this_cpu_ptr(&cpu_dr7);
+	*dr7 |= encode_dr7(i, info->len, info->type);
+
+	/*
+	 * Ensure we first write cpu_dr7 before we set the DR7 register.
+	 * This ensures an NMI never see cpu_dr7 0 when DR7 is not.
+	 */
+	barrier();
+
+	set_debugreg(*dr7, 7);
+	if (info->mask)
Quoted 8 lines

arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 183

Quoted 5 lines
arch/x86/kernel/hw_breakpoint.c +5 -0
+		amd_set_dr_addr_mask(info->mask, i);
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(arch_reinstall_hw_breakpoint);

Yeah, I think not. For one this is an almost verbatim copy of arch_install_hw_breakpoint() with zero re-use. Surely you've been taught better?

Quoted 6 lines

I introduced this to modify bp_addr in atomic context in my RFC series. I thought it was clearer to split the introduction and refactor. And then It was used in the wprobe series, so I left it as introduced in the RFC series.

I agree your suggestion is right. I am willing to refactor after wprobe.

I'm OK to refactor it to reuse arch_install_hw_breakpoint(). My point is to have CONFIG_HAVE_REINSTALL_HW_BREAKPOINT so that we can easily implement the dependency for other features which requires this feature in Kconfig level.

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

And why would we want to export guts like this?

I wanted to introduce a real-time stack corruption debugging tool, which needs a helper to change bp_addr in atomic context (kprobe handler). And wprobe needs it also.

I agree with Peter, it should not expose the architecture dependent code directly. Instead, we need a wrapper.

Thank you,

Understood, I will use the wrapper instead.

#16 lore raw

Re: [PATCH v2 05/18] x86/hw_breakpoint: introduce arch_reinstall_hw_breakpoint() for atomic context

Quoted 21 lines · Jinchao Wang
Quoted 19 lines · Masami Hiramatsu (Google)
Quoted 11 lines · On Mon, 8 Sep 2025 13:20:51 +0800 Jinchao Wang <[email protected]> wrote:
Quoted 5 lines

...

Yeah, I think not. For one this is an almost verbatim copy of arch_install_hw_breakpoint() with zero re-use. Surely you've been taught better?

I introduced this to modify bp_addr in atomic context in my RFC series. I thought it was clearer to split the introduction and refactor. And then It was used in the wprobe series, so I left it as introduced in the RFC series.

I agree your suggestion is right. I am willing to refactor after wprobe.

I'm OK to refactor it to reuse arch_install_hw_breakpoint(). My point is to have CONFIG_HAVE_REINSTALL_HW_BREAKPOINT so that we can easily implement the dependency for other features which requires this feature in Kconfig level.

Quoted 1 line
Quoted 1 line

And why would we want to export guts like this?

Quoted 10 lines
Quoted 7 lines
Quoted 3 lines

I wanted to introduce a real-time stack corruption debugging tool, which needs a helper to change bp_addr in atomic context (kprobe handler). And wprobe needs it also.

I agree with Peter, it should not expose the architecture dependent code directly. Instead, we need a wrapper.

Thank you,

Understood, I will use the wrapper instead.

Hi Masami,
I would like to ask for your advice regarding a development workflow issue.

I have a patch series that refactors |arch_reinstall_hw_breakpoint|, which
I know you are using in your |wprobe| series. My new feature, |kstackwatch|, is dependent on my patches and also on your wrapper patch for |modify_wide_hw_breakpoint_local|.

Since we are working on different subsystems with different maintainers, I am concerned about how to handle the dependencies between our patches to avoid introducing trouble.

What is the best practice for this type of cross-subsystem dependency? Should one of us carry all the patches until they are merged, or is there a standard procedure for this situation?

Thank you for your guidance.

Signature · 2 lines
Thanks,
Jinchao
#17 lore raw

PATCH v2 6/18 perf/hw_breakpoint: add arch-independent hw_breakpoint_modify_local()

In reply to Jinchao Wang

Introduce hw_breakpoint_modify_local() as a generic helper to modify an existing hardware breakpoint. The function invokes hw_breakpoint_arch_parse() and delegates the reinstall step to the architecture via arch_reinstall_hw_breakpoint().

A weak default implementation of arch_reinstall_hw_breakpoint() is provided, returning -EOPNOTSUPP on architectures without support.

This makes the interface arch-independent while allowing x86 (and others) to provide their own implementation.

---
 include/linux/hw_breakpoint.h |  1 +
 kernel/events/hw_breakpoint.c | 18 ++++++++++++++++++
 2 files changed, 19 insertions(+)
include/linux/hw_breakpoint.h +1 -0
index db199d653dd1..9453b5bdb443 100644
@@ -67,6 +67,7 @@ extern int
 modify_user_hw_breakpoint_check(struct perf_event *bp, struct perf_event_attr *attr,
 				bool check);
 
+int hw_breakpoint_modify_local(struct perf_event *bp, struct perf_event_attr *attr);
 /*
  * Kernel breakpoints are not associated with any particular thread.
  */
kernel/events/hw_breakpoint.c +18 -0
index 8ec2cb688903..ff428739f71e 100644
@@ -983,6 +983,24 @@ static void hw_breakpoint_del(struct perf_event *bp, int flags)
 	arch_uninstall_hw_breakpoint(bp);
 }
 
+int hw_breakpoint_modify_local(struct perf_event *bp, struct perf_event_attr *attr)
+{
+	int err;
+
+	err = hw_breakpoint_arch_parse(bp, attr, counter_arch_bp(bp));
+	if (err)
+		return err;
+
+	return arch_reinstall_hw_breakpoint(bp);
+}
+EXPORT_SYMBOL(hw_breakpoint_modify_local);
+
+/* weak fallback for arches without support */
+__weak int arch_reinstall_hw_breakpoint(struct perf_event *bp)
+{
+	return -EOPNOTSUPP;
+}
+
 static void hw_breakpoint_start(struct perf_event *bp, int flags)
 {
 	bp->hw.state = 0;
Signature · 1 line
2.43.0
maintainer
#18 lore raw

Re: [PATCH v2 06/18] perf/hw_breakpoint: add arch-independent hw_breakpoint_modify_local()

Quoted 44 lines · Jinchao Wang

Introduce hw_breakpoint_modify_local() as a generic helper to modify an existing hardware breakpoint. The function invokes hw_breakpoint_arch_parse() and delegates the reinstall step to the architecture via arch_reinstall_hw_breakpoint().

A weak default implementation of arch_reinstall_hw_breakpoint() is provided, returning -EOPNOTSUPP on architectures without support.

This makes the interface arch-independent while allowing x86 (and others) to provide their own implementation.

---
 include/linux/hw_breakpoint.h |  1 +
 kernel/events/hw_breakpoint.c | 18 ++++++++++++++++++
 2 files changed, 19 insertions(+)
include/linux/hw_breakpoint.h +1 -0
index db199d653dd1..9453b5bdb443 100644
@@ -67,6 +67,7 @@ extern int
 modify_user_hw_breakpoint_check(struct perf_event *bp, struct perf_event_attr *attr,
 				bool check);
 
+int hw_breakpoint_modify_local(struct perf_event *bp, struct perf_event_attr *attr);
 /*
  * Kernel breakpoints are not associated with any particular thread.
  */
kernel/events/hw_breakpoint.c +7 -0
index 8ec2cb688903..ff428739f71e 100644
@@ -983,6 +983,24 @@ static void hw_breakpoint_del(struct perf_event *bp, int flags)
 	arch_uninstall_hw_breakpoint(bp);
 }
 
+int hw_breakpoint_modify_local(struct perf_event *bp, struct perf_event_attr *attr)
+{
+	int err;
+
+	err = hw_breakpoint_arch_parse(bp, attr, counter_arch_bp(bp));
+	if (err)
+		return err;

kernel/events/hw_breakpoint.c static void hw_breakpoint_del(struct perf_event *bp, int flags) · line 1002

Quoted 10 lines
kernel/events/hw_breakpoint.c +10 -0
+
+	return arch_reinstall_hw_breakpoint(bp);
+}
+EXPORT_SYMBOL(hw_breakpoint_modify_local);
+
+/* weak fallback for arches without support */
+__weak int arch_reinstall_hw_breakpoint(struct perf_event *bp)
+{
+	return -EOPNOTSUPP;
+}

Again, so much fail :/

So we have:

{register,modify,unregister}_user_hw_breakpoint()

and

{register,unregister}_wide_hw_breakpoint()

And you choose to extend this latter with hw_breakpoint_modify_local() instead of sticking with the naming scheme and say adding:

modify_wide_hw_breakpoint_local().

Also, again, that EXPORT is a fail, these other interfaces are all EXPORT_SYMBOL_GPL().

Also note that modify_user_hw_breakpoint() doesn't seem to need new arch hooks. Yet you fail to explain why you think you do.

#19 lore raw

Re: [PATCH v2 06/18] perf/hw_breakpoint: add arch-independent hw_breakpoint_modify_local()

Quoted 67 lines · Peter Zijlstra
Quoted 44 lines · Jinchao Wang

Introduce hw_breakpoint_modify_local() as a generic helper to modify an existing hardware breakpoint. The function invokes hw_breakpoint_arch_parse() and delegates the reinstall step to the architecture via arch_reinstall_hw_breakpoint().

A weak default implementation of arch_reinstall_hw_breakpoint() is provided, returning -EOPNOTSUPP on architectures without support.

This makes the interface arch-independent while allowing x86 (and others) to provide their own implementation.

---
 include/linux/hw_breakpoint.h |  1 +
 kernel/events/hw_breakpoint.c | 18 ++++++++++++++++++
 2 files changed, 19 insertions(+)
include/linux/hw_breakpoint.h +1 -0
index db199d653dd1..9453b5bdb443 100644
@@ -67,6 +67,7 @@ extern int
 modify_user_hw_breakpoint_check(struct perf_event *bp, struct perf_event_attr *attr,
 				bool check);
 
+int hw_breakpoint_modify_local(struct perf_event *bp, struct perf_event_attr *attr);
 /*
  * Kernel breakpoints are not associated with any particular thread.
  */
kernel/events/hw_breakpoint.c +7 -0
index 8ec2cb688903..ff428739f71e 100644
@@ -983,6 +983,24 @@ static void hw_breakpoint_del(struct perf_event *bp, int flags)
 	arch_uninstall_hw_breakpoint(bp);
 }
 
+int hw_breakpoint_modify_local(struct perf_event *bp, struct perf_event_attr *attr)
+{
+	int err;
+
+	err = hw_breakpoint_arch_parse(bp, attr, counter_arch_bp(bp));
+	if (err)
+		return err;

kernel/events/hw_breakpoint.c static void hw_breakpoint_del(struct perf_event *bp, int flags) · line 1002

Quoted 10 lines
kernel/events/hw_breakpoint.c +10 -0
+
+	return arch_reinstall_hw_breakpoint(bp);
+}
+EXPORT_SYMBOL(hw_breakpoint_modify_local);
+
+/* weak fallback for arches without support */
+__weak int arch_reinstall_hw_breakpoint(struct perf_event *bp)
+{
+	return -EOPNOTSUPP;
+}

Again, so much fail :/

So we have:

{register,modify,unregister}_user_hw_breakpoint()

and

{register,unregister}_wide_hw_breakpoint()

Quoted 8 lines

And you choose to extend this latter with hw_breakpoint_modify_local() instead of sticking with the naming scheme and say adding:

modify_wide_hw_breakpoint_local().

Also, again, that EXPORT is a fail, these other interfaces are all EXPORT_SYMBOL_GPL().

Thanks for your patience.

I was misled by another family:
- hw_breakpoint_add
- hw_breakpoint_del
- hw_breakpoint_start
- hw_breakpoint_stop

Since this logic was also added in the wprobe series by Masami, I will adopt his version instead.

Quoted 2 lines

Also note that modify_user_hw_breakpoint() doesn't seem to need new arch hooks. Yet you fail to explain why you think you do.

Thanks for feedback, I will study existing code to better handle the arch dependencies.

#20 lore raw

Re: [PATCH v2 06/18] perf/hw_breakpoint: add arch-independent hw_breakpoint_modify_local()

In reply to Jinchao Wang
kernel test robot noticed the following build warnings:

Hi Jinchao,

kernel test robot noticed the following build warnings:

[auto build test WARNING on akpm-mm/mm-everything]

url:    https://github.com/intel-lab-lkp/linux/commits/Jinchao-Wang/mm-ksw-add-build-system-support/20250904-082544
base:   https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything
patch link:    https://lore.kernel.org/r/20250904002126.1514566-7-wangjinchao600%40gmail.com
patch subject: [PATCH v2 06/18] perf/hw_breakpoint: add arch-independent hw_breakpoint_modify_local()
config: sh-randconfig-001-20250905 (https://download.01.org/0day-ci/archive/20250905/[email protected]/config)
compiler: sh4-linux-gcc (GCC) 15.1.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250905/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

kernel/events/hw_breakpoint.c: In function 'hw_breakpoint_modify_local':
kernel/events/hw_breakpoint.c:994:16: error: implicit declaration of function 'arch_reinstall_hw_breakpoint'; did you mean 'arch_uninstall_hw_breakpoint'? [-Wimplicit-function-declaration]

     994 |         return arch_reinstall_hw_breakpoint(bp);
         |                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
         |                arch_uninstall_hw_breakpoint
   kernel/events/hw_breakpoint.c: At top level:
>> kernel/events/hw_breakpoint.c:999:12: warning: no previous prototype for 'arch_reinstall_hw_breakpoint' [-Wmissing-prototypes]

999 | __weak int arch_reinstall_hw_breakpoint(struct perf_event *bp)
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~

vim +/arch_reinstall_hw_breakpoint +999 kernel/events/hw_breakpoint.c

997
998 /* weak fallback for arches without support */

 > 999	__weak int arch_reinstall_hw_breakpoint(struct perf_event *bp)

1000 {
1001 return -EOPNOTSUPP;
1002 }
1003

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#21 lore raw

Re: [PATCH v2 06/18] perf/hw_breakpoint: add arch-independent hw_breakpoint_modify_local()

In reply to Jinchao Wang
kernel test robot noticed the following build errors:

Hi Jinchao,

kernel test robot noticed the following build errors:

[auto build test ERROR on akpm-mm/mm-everything]

url:    https://github.com/intel-lab-lkp/linux/commits/Jinchao-Wang/mm-ksw-add-build-system-support/20250904-082544
base:   https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-everything
patch link:    https://lore.kernel.org/r/20250904002126.1514566-7-wangjinchao600%40gmail.com
patch subject: [PATCH v2 06/18] perf/hw_breakpoint: add arch-independent hw_breakpoint_modify_local()
config: sh-randconfig-001-20250905 (https://download.01.org/0day-ci/archive/20250906/[email protected]/config)
compiler: sh4-linux-gcc (GCC) 15.1.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250906/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

kernel/events/hw_breakpoint.c: In function 'hw_breakpoint_modify_local':

>> kernel/events/hw_breakpoint.c:994:16: error: implicit declaration of function 'arch_reinstall_hw_breakpoint'; did you mean 'arch_uninstall_hw_breakpoint'? [-Wimplicit-function-declaration]
     994 |         return arch_reinstall_hw_breakpoint(bp);
         |                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
         |                arch_uninstall_hw_breakpoint

kernel/events/hw_breakpoint.c: At top level:
kernel/events/hw_breakpoint.c:999:12: warning: no previous prototype for 'arch_reinstall_hw_breakpoint' [-Wmissing-prototypes]
999 | __weak int arch_reinstall_hw_breakpoint(struct perf_event *bp)
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~

vim +994 kernel/events/hw_breakpoint.c

985
986 int hw_breakpoint_modify_local(struct perf_event *bp, struct perf_event_attr *attr)
987 {
988 int err;
989
990 err = hw_breakpoint_arch_parse(bp, attr, counter_arch_bp(bp));
991 if (err)
992 return err;
993

 > 994		return arch_reinstall_hw_breakpoint(bp);

995 }
996 EXPORT_SYMBOL(hw_breakpoint_modify_local);
997

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#22 lore raw

PATCH v2 7/18 mm/ksw: add atomic watch on/off operations

In reply to Jinchao Wang

Add support to atomically turn the hardware watch on and off without allocation overhead.

The watch is pre-allocated and later retargeted using hw_breakpoint_modify_local(). The current CPU is updated directly, while other CPUs are updated asynchronously via smp_call_function_single_async().

This allows KStackWatch to switch the watch in kprobe/fprobe handlers.

---
 mm/kstackwatch/kstackwatch.h |  2 +
 mm/kstackwatch/watch.c       | 97 ++++++++++++++++++++++++++++++++++++
 2 files changed, 99 insertions(+)
mm/kstackwatch/kstackwatch.h +2 -0
index 2318779bde70..13ef8c79f855 100644
@@ -41,5 +41,7 @@ extern bool panic_on_catch;
 /* watch management */
 int ksw_watch_init(struct ksw_config *config);
 void ksw_watch_exit(void);
+int ksw_watch_on(u64 watch_addr, u64 watch_len);
+void ksw_watch_off(void);
 
 #endif /* _KSTACKWATCH_H */
mm/kstackwatch/watch.c +97 -0

112 lines not on this page · raw message

Signature · 1 line
2.43.0
maintainer
#23 lore raw

Re: [PATCH v2 07/18] mm/ksw: add atomic watch on/off operations

Quoted 39 lines · Jinchao Wang
mm/kstackwatch/watch.c +38 -0
+static DEFINE_PER_CPU(call_single_data_t,
+		      watch_csd) = CSD_INIT(ksw_watch_on_local_cpu,
+					    &watch_info);
+
 
+int ksw_watch_on(u64 watch_addr, u64 watch_len)
+{
+	unsigned long flags;
+	int cpu;
+
+	if (!watch_addr) {
+		pr_err("KSW: watch with invalid address\n");
+		return -EINVAL;
+	}
+
+	spin_lock_irqsave(&watch_lock, flags);
+
+	/*
+	 * check if already watched
+	 */
+	if (watch_info.addr != 0 && // not uninit
+	    watch_info.addr != (unsigned long)&watch_holder && // installed
+	    watch_addr != (unsigned long)&watch_holder) { //not restore
+		spin_unlock_irqrestore(&watch_lock, flags);
+		return -EBUSY;
+	}
+
+	watch_info.addr = watch_addr;
+	watch_info.len = watch_len;
+
+	spin_unlock_irqrestore(&watch_lock, flags);
+
+	if (watch_addr == (unsigned long)&watch_holder)
+		pr_debug("KSW: watch off starting\n");
+	else
+		pr_debug("KSW: watch on starting\n");
+
+	for_each_online_cpu(cpu) {
+		if (cpu == raw_smp_processor_id()) {

mm/kstackwatch/watch.c static void ksw_watch_handler(struct perf_event *bp, · line 125

Quoted 10 lines
mm/kstackwatch/watch.c +10 -0
+			ksw_watch_on_local_cpu(&watch_info);
+		} else {
+			call_single_data_t *csd = &per_cpu(watch_csd, cpu);
+
+			smp_call_function_single_async(cpu, csd);
+		}
+	}
+
+	return 0;
+}

What do you think happens when two ksw_watch_on() instances run concurrently?

What happens if a CPU comes online/offline concurrently with ksw_watch_on()?

#24 lore raw

Re: [PATCH v2 07/18] mm/ksw: add atomic watch on/off operations

Quoted 55 lines · Peter Zijlstra
Quoted 39 lines · Jinchao Wang
mm/kstackwatch/watch.c +38 -0
+static DEFINE_PER_CPU(call_single_data_t,
+		      watch_csd) = CSD_INIT(ksw_watch_on_local_cpu,
+					    &watch_info);
+
 
+int ksw_watch_on(u64 watch_addr, u64 watch_len)
+{
+	unsigned long flags;
+	int cpu;
+
+	if (!watch_addr) {
+		pr_err("KSW: watch with invalid address\n");
+		return -EINVAL;
+	}
+
+	spin_lock_irqsave(&watch_lock, flags);
+
+	/*
+	 * check if already watched
+	 */
+	if (watch_info.addr != 0 && // not uninit
+	    watch_info.addr != (unsigned long)&watch_holder && // installed
+	    watch_addr != (unsigned long)&watch_holder) { //not restore
+		spin_unlock_irqrestore(&watch_lock, flags);
+		return -EBUSY;
+	}
+
+	watch_info.addr = watch_addr;
+	watch_info.len = watch_len;
+
+	spin_unlock_irqrestore(&watch_lock, flags);
+
+	if (watch_addr == (unsigned long)&watch_holder)
+		pr_debug("KSW: watch off starting\n");
+	else
+		pr_debug("KSW: watch on starting\n");
+
+	for_each_online_cpu(cpu) {
+		if (cpu == raw_smp_processor_id()) {

mm/kstackwatch/watch.c static void ksw_watch_handler(struct perf_event *bp, · line 125

Quoted 10 lines
mm/kstackwatch/watch.c +10 -0
+			ksw_watch_on_local_cpu(&watch_info);
+		} else {
+			call_single_data_t *csd = &per_cpu(watch_csd, cpu);
+
+			smp_call_function_single_async(cpu, csd);
+		}
+	}
+
+	return 0;
+}

What do you think happens when two ksw_watch_on() instances run concurrently?

Quoted 2 lines

What happens if a CPU comes online/offline concurrently with ksw_watch_on()?

Thanks for pointing that out. I did not think much about it. I will think more and address it in the next series.

#25 lore raw

PATCH v2 8/18 mm/ksw: add stack probe support

In reply to Jinchao Wang

Introduce stack management for KStackWatch using kprobes and fprobes to enable dynamic watch switching:

- Entry: prepare target address/length and enable watch
- Exit: disable watch

---
 mm/kstackwatch/kstackwatch.h |  4 ++
 mm/kstackwatch/stack.c       | 91 ++++++++++++++++++++++++++++++++++++
 2 files changed, 95 insertions(+)
mm/kstackwatch/kstackwatch.h +4 -0
index 13ef8c79f855..bc8664af4fa6 100644
@@ -38,6 +38,10 @@ struct ksw_config {
 
 extern bool panic_on_catch;
 
+/* stack management */
+int ksw_stack_init(struct ksw_config *config);
+void ksw_stack_exit(void);
+
 /* watch management */
 int ksw_watch_init(struct ksw_config *config);
 void ksw_watch_exit(void);
mm/kstackwatch/stack.c +91 -0

92 lines not on this page · raw message

Signature · 1 line
2.43.0
#26 lore raw

PATCH v2 9/18 mm/ksw: implement stack canary and local var resolution logic

In reply to Jinchao Wang

Implement logic to resolve stack watch target for kstackwatch:
- Locate the stack canary within the current frame
- Resolve local variable offsets relative to the stack pointer
- Validate addresses against current task's stack bounds

This logic prepares watch addr and len for use in kprobe/fprobe handlers, enabling dynamic stack monitoring.

---
 mm/kstackwatch/stack.c | 99 ++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 96 insertions(+), 3 deletions(-)
mm/kstackwatch/stack.c +96 -3
index 3b72177315cc..00cb38085a9f 100644
@@ -1,22 +1,115 @@
 // SPDX-License-Identifier: GPL-2.0
 
 #include <linux/fprobe.h>
+#include <linux/interrupt.h>
 #include <linux/kprobes.h>
+#include <linux/percpu.h>
 #include <linux/sched.h>
 #include <linux/spinlock.h>
+#include <linux/stackprotector.h>
 
 #include "kstackwatch.h"
 
 struct ksw_config *probe_config;
 
+/* Find canary address in current stack frame */
+static unsigned long ksw_stack_find_canary(struct pt_regs *regs)
+{
+	unsigned long *stack_ptr, *stack_end;
+	unsigned long expected_canary;
+	unsigned int i;
+
+	stack_ptr = (unsigned long *)kernel_stack_pointer(regs);
+	stack_end =
+		(unsigned long *)current->stack + THREAD_SIZE / sizeof(long);
+	expected_canary = current->stack_canary;
+
+	for (i = 0; i < MAX_FRAME_SEARCH && &stack_ptr[i] < stack_end; i++) {
+		if (stack_ptr[i] == expected_canary) {
+			pr_info("KSW: canary found i:%d 0x%px\n", i,
+				&stack_ptr[i]);
+			return (unsigned long)&stack_ptr[i];
+		}
+	}
+
+	return 0;
+}
+
+/* Resolve stack offset to actual address */
+static unsigned long ksw_stack_resolve_offset(struct pt_regs *regs,
+					      s64 local_var_offset)
+{
+	unsigned long stack_base;
+	unsigned long target_addr;
+
+	if (!regs)
+		return 0;
+
+	/* Use stack pointer as base for offset calculation */
+	stack_base = kernel_stack_pointer(regs);
+	target_addr = stack_base + local_var_offset;
+
+	pr_debug("KSW: stack resolve offset target: 0x%lx\n", target_addr);
+
+	return target_addr;
+}
+
+/* Validate that address is within current stack bounds */
+static int ksw_stack_validate_addr(unsigned long addr, size_t size)
+{
+	unsigned long stack_start, stack_end;
+
+	if (!addr || !size)
+		return -EINVAL;
+
+	stack_start = (unsigned long)current->stack;
+	stack_end = stack_start + THREAD_SIZE;
+
+	if (addr < stack_start || (addr + size) > stack_end) {
+		pr_warn("KSW: address 0x%lx (size %zu) outside stack bounds [0x%lx-0x%lx]\n",
+			addr, size, stack_start, stack_end);
+		return -ERANGE;
+	}
+
+	return 0;
+}
+
 /* prepare watch_addr and watch_len for watch */
 static int ksw_stack_prepare_watch(struct pt_regs *regs,
 				   struct ksw_config *config, u64 *watch_addr,
 				   u64 *watch_len)
 {
-	/* TODO: implement logic */
-	*watch_addr = 0;
-	*watch_len = 0;
+	u64 addr;
+	u64 len;
+
+	/* Resolve addresses for all active watches */
+	switch (config->type) {
+	case WATCH_CANARY:
+		addr = ksw_stack_find_canary(regs);
+		len = 8;
+		break;
+
+	case WATCH_LOCAL_VAR:
+		addr = ksw_stack_resolve_offset(regs, config->local_var_offset);
+		if (!addr) {
+			pr_err("KSW: invalid stack var offset %u\n",
+			       config->local_var_offset);
+			return -EINVAL;
+		}
+		if (ksw_stack_validate_addr(addr, config->local_var_len)) {
+			pr_err("KSW: invalid stack var len %u\n",
+			       config->local_var_len);
+		}
+		len = config->local_var_len;
+		break;
+
+	default:
+		pr_warn("KSW: Unknown watch type %d\n", config->type);
+		return -EINVAL;
+	}
+
+	*watch_addr = addr;
+	*watch_len = len;
 	return 0;
 }
 
Signature · 1 line
2.43.0
#27 lore raw

PATCH v2 10/18 mm/ksw: add per-task recursion depth tracking

In reply to Jinchao Wang

Implement depth tracking for KStackWatch to support stack-level filtering. Each task's recursive entry depth is stored in a global hash table keyed by pid:

- get_recursive_depth()/set_recursive_depth() manage per-task depth
- reset_recursive_depth() clears all tracked entries
- entry/exit handlers increment or decrement depth and skip if the current depth does not match the configured depth.

This works even across task scheduling or in interrupt context, since depth is tracked per-task, ensuring KStackWatch can selectively monitor a specific recursion level without redundant triggers.

---
 mm/kstackwatch/stack.c | 105 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 103 insertions(+), 2 deletions(-)
mm/kstackwatch/stack.c +103 -2
index 00cb38085a9f..8758b8b94f7f 100644
@@ -1,6 +1,8 @@
 // SPDX-License-Identifier: GPL-2.0
 
 #include <linux/fprobe.h>
+#include <linux/hashtable.h>
+#include <linux/hash.h>
 #include <linux/interrupt.h>
 #include <linux/kprobes.h>
 #include <linux/percpu.h>
@@ -12,6 +14,81 @@
 
 struct ksw_config *probe_config;
 
+#define DEPTH_HASH_BITS 8
+#define DEPTH_HASH_SIZE BIT(DEPTH_HASH_BITS)
+
+struct depth_entry {
+	pid_t pid;
+	int depth; /* starts from 0 */
+	struct hlist_node node;
+};
+
+static DEFINE_HASHTABLE(depth_hash, DEPTH_HASH_BITS);
+static DEFINE_SPINLOCK(depth_hash_lock);
+
+static int get_recursive_depth(void)
+{
+	struct depth_entry *entry;
+	pid_t pid = current->pid;
+	int depth = 0;
+
+	spin_lock(&depth_hash_lock);
+	hash_for_each_possible(depth_hash, entry, node,
+			       hash_32(pid, DEPTH_HASH_BITS)) {
+		if (entry->pid == pid) {
+			depth = entry->depth;
+			break;
+		}
+	}
+	spin_unlock(&depth_hash_lock);
+	return depth;
+}
+
+static void set_recursive_depth(int depth)
+{
+	struct depth_entry *entry;
+	pid_t pid = current->pid;
+	bool found = false;
+
+	spin_lock(&depth_hash_lock);
+	hash_for_each_possible(depth_hash, entry, node,
+			       hash_32(pid, DEPTH_HASH_BITS)) {
+		if (entry->pid == pid) {
+			entry->depth = depth;
+			found = true;
+			break;
+		}
+	}
+
+	if (!found && depth > 0) {
+		entry = kmalloc(sizeof(*entry), GFP_ATOMIC);
+		if (entry) {
+			entry->pid = pid;
+			entry->depth = depth;
+			hash_add(depth_hash, &entry->node,
+				 hash_32(pid, DEPTH_HASH_BITS));
+		}
+	} else if (found && depth == 0) {
+		hash_del(&entry->node);
+		kfree(entry);
+	}
+	spin_unlock(&depth_hash_lock);
+}
+
+static void reset_recursive_depth(void)
+{
+	struct depth_entry *entry;
+	struct hlist_node *tmp;
+	int bkt;
+
+	spin_lock(&depth_hash_lock);
+	hash_for_each_safe(depth_hash, bkt, tmp, entry, node) {
+		hash_del(&entry->node);
+		kfree(entry);
+	}
+	spin_unlock(&depth_hash_lock);
+}
+
 /* Find canary address in current stack frame */
 static unsigned long ksw_stack_find_canary(struct pt_regs *regs)
 {
@@ -119,10 +196,21 @@ static struct fprobe exit_probe_fprobe;
 static void ksw_stack_entry_handler(struct kprobe *p, struct pt_regs *regs,
 				    unsigned long flags)
 {
+	int cur_depth;
 	int ret;
 	u64 watch_addr;
 	u64 watch_len;
 
+	cur_depth = get_recursive_depth();
+	set_recursive_depth(cur_depth + 1);
+
+	/* depth start from 0 */
+	if (cur_depth != probe_config->depth) {
+		pr_info("KSW: config_depth:%u cur_depth:%d entry skipping\n",
+			probe_config->depth, cur_depth);
+		return;
+	}
+
 	ret = ksw_stack_prepare_watch(regs, probe_config, &watch_addr,
 				      &watch_len);
 	if (ret) {
@@ -132,8 +220,8 @@ static void ksw_stack_entry_handler(struct kprobe *p, struct pt_regs *regs,
 
 	ret = ksw_watch_on(watch_addr, watch_len);
 	if (ret) {
-		pr_err("KSW: failed to watch on addr:0x%llx len:%llx %d\n",
-		       watch_addr, watch_len, ret);
+		pr_err("KSW: failed to watch on depth:%d addr:0x%llx len:%llx %d\n",
+		       cur_depth, watch_addr, watch_len, ret);
 		return;
 	}
 }
@@ -142,6 +230,17 @@ static void ksw_stack_exit_handler(struct fprobe *fp, unsigned long ip,
 				   unsigned long ret_ip,
 				   struct ftrace_regs *regs, void *data)
 {
+	int cur_depth;
+
+	cur_depth = get_recursive_depth() - 1;
+	set_recursive_depth(cur_depth);
+
+	if (cur_depth != probe_config->depth) {
+		pr_info("KSW: config_depth:%u cur_depth:%d exit skipping\n",
+			probe_config->depth, cur_depth);
+		return;
+	}
+
 	ksw_watch_off();
 }
 
@@ -150,6 +249,8 @@ int ksw_stack_init(struct ksw_config *config)
 	int ret;
 	char *symbuf = NULL;
 
+	reset_recursive_depth();
+
 	/* Setup entry probe */
 	memset(&entry_probe, 0, sizeof(entry_probe));
 	entry_probe.symbol_name = config->function;
Signature · 1 line
2.43.0
#28 lore raw

PATCH v2 11/18 mm/ksw: coordinate watch and stack for full functionality

In reply to Jinchao Wang

This patch connects the watch and stack so that all components function together.

---
 mm/kstackwatch/kernel.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
mm/kstackwatch/kernel.c +28 -0
index 95ade95abde1..4c5fbcaddab0 100644
@@ -1,10 +1,13 @@
 // SPDX-License-Identifier: GPL-2.0
+#include <linux/kern_levels.h>
+#include <linux/kernel.h>
 #include <linux/kstrtox.h>
 #include <linux/module.h>
 #include <linux/proc_fs.h>
 #include <linux/seq_file.h>
 #include <linux/string.h>
 #include <linux/uaccess.h>
+#include <linux/utsname.h>
 
 #include "kstackwatch.h"
 
@@ -22,6 +25,29 @@ MODULE_PARM_DESC(panic_on_catch,
 
 static int ksw_start_watching(void)
 {
+	int ret;
+
+	if (strlen(ksw_config->function) == 0) {
+		pr_err("KSW: no target function specified\n");
+		return -EINVAL;
+	}
+
+	/*
+	 * Watch init will preallocate the HWBP,
+	 * so it must happen before stack init
+	 */
+	ret = ksw_watch_init(ksw_config);
+	if (ret) {
+		pr_err("KSW: ksw_watch_init ret: %d\n", ret);
+		return ret;
+	}
+
+	ret = ksw_stack_init(ksw_config);
+	if (ret) {
+		pr_err("KSW: ksw_stack_init_fprobe ret: %d\n", ret);
+		ksw_watch_exit();
+		return ret;
+	}
 	watching_active = true;
 
 	pr_info("KSW: start watching %s\n", ksw_config->config_str);
@@ -30,6 +56,8 @@ static int ksw_start_watching(void)
 
 static void ksw_stop_watching(void)
 {
+	ksw_stack_exit();
+	ksw_watch_exit();
 	watching_active = false;
 
 	pr_info("KSW: stop watching %s\n", ksw_config->config_str);
Signature · 1 line
2.43.0
#29 lore raw

PATCH v2 12/18 mm/ksw: add self-debug functions for kstackwatch watch

In reply to Jinchao Wang

Introduce ksw_watch_show() and ksw_watch_fire() for runtime debugging of kstackwatch's watch mechanism:

- ksw_watch_show(): prints the currently armed watch address and length
- ksw_watch_fire(): forcibly triggers the watch by writing to the watched address

These functions help validate the dynamic watch behavior and facilitate testing without requiring real events.

---
 mm/kstackwatch/kstackwatch.h |  2 ++
 mm/kstackwatch/watch.c       | 17 ++++++++++++++++-
 2 files changed, 18 insertions(+), 1 deletion(-)
mm/kstackwatch/kstackwatch.h +2 -0
index bc8664af4fa6..d1bb5ae75aae 100644
@@ -47,5 +47,7 @@ int ksw_watch_init(struct ksw_config *config);
 void ksw_watch_exit(void);
 int ksw_watch_on(u64 watch_addr, u64 watch_len);
 void ksw_watch_off(void);
+void ksw_watch_show(void);
+void ksw_watch_fire(void);
 
 #endif /* _KSTACKWATCH_H */
mm/kstackwatch/watch.c +16 -1
index c563f8d17829..8f3f6cb9f17a 100644
@@ -116,7 +116,6 @@ int ksw_watch_on(u64 watch_addr, u64 watch_len)
 			ksw_watch_on_local_cpu(&watch_info);
 		} else {
 			call_single_data_t *csd = &per_cpu(watch_csd, cpu);
-
 			smp_call_function_single_async(cpu, csd);
 		}
 	}
@@ -158,3 +157,19 @@ void ksw_watch_exit(void)
 
 	pr_info("KSW: watch exited\n");
 }
+
+/* self debug function */
+void ksw_watch_show(void)
+{
+	pr_info("KSW: watch target bp_addr: 0x%llx len:%llu\n",
+		watch_info.addr, watch_info.len);
+}
+
+/* self debug function */
+void ksw_watch_fire(void)
+{
+	char *ptr = (char *)watch_info.addr;
+
+	pr_warn("KSW: watch triggered immediately\n");
+	*ptr = 0x42; // This should trigger immediately
+}
Signature · 1 line
2.43.0
#30 lore raw

PATCH v2 13/18 mm/ksw: add test module

In reply to Jinchao Wang

Introduce a separate test module to validate KStackWatch functionality in controlled scenarios, such as stack canary writes and simulated corruption.

The module provides a proc interface (/proc/kstackwatch_test) that allows triggering specific test cases via simple commands:

- test0: directly corrupt the canary to verify watch/fire behavior

This helps development and validation of KStackWatch without affecting normal kernel operation. Test module is built with optimizations disabled to ensure predictable behavior.

---
 mm/Kconfig.debug                  |  10 +++
 mm/kstackwatch/Makefile           |   6 +-
 mm/kstackwatch/kstackwatch_test.c | 118 ++++++++++++++++++++++++++++++
 3 files changed, 133 insertions(+), 1 deletion(-)
 create mode 100644 mm/kstackwatch/kstackwatch_test.c
mm/Kconfig.debug +10 -0
index c2cc8c7b595f..7fdf7b03d458 100644
@@ -319,3 +319,13 @@ config KSTACK_WATCH
 	  the recursive depth of the monitored function.
 
 	  If unsure, say N.
+
+config KSTACK_WATCH_TEST
+	tristate "KStackWatch Test Module"
+	depends on KSTACK_WATCH
+	help
+	  This module provides controlled stack exhaustion and overflow scenarios
+	  to verify the functionality of KStackWatch. It is particularly useful
+	  for development and validation of the KStachWatch mechanism.
+
+	  If unsure, say N.
mm/kstackwatch/Makefile +5 -1
index d422f0e114dd..c04c0780da01 100644
@@ -1,4 +1,8 @@
 obj-$(CONFIG_KSTACK_WATCH)	+= kstackwatch.o
 kstackwatch-y := kernel.o stack.o watch.o
 
-CFLAGS_kernel.o := -Wno-error=unused-function
+obj-$(CONFIG_KSTACK_WATCH_TEST)	+= kstackwatch_test.o
+CFLAGS_kstackwatch_test.o := -fno-ipa-sra -fno-inline \
+                             -fno-optimize-sibling-calls \
+                             -fno-section-anchors \
+                             -fno-pic -fno-pie -O0 -Og
mm/kstackwatch/kstackwatch_test.c new file +118 -0

118 lines not on this page · raw message

Signature · 1 line
2.43.0
#31 lore raw

PATCH v2 14/18 mm/ksw: add stack overflow test

In reply to Jinchao Wang

Extend the test module with a new test case (test1) that intentionally overflows a local u64 buffer to corrupt the stack canary. This helps validate KStackWatch's detection of stack corruption under overflow conditions.

The proc interface is updated to document the new test:

- test1: stack canary overflow test

---
 mm/kstackwatch/kstackwatch_test.c | 29 +++++++++++++++++++++++++++--
 1 file changed, 27 insertions(+), 2 deletions(-)
mm/kstackwatch/kstackwatch_test.c +27 -2
index bba2ab8530ed..138163472b03 100644
@@ -42,6 +42,27 @@ static void canary_test_write(void)
 	pr_info("KSW: test: canary write test completed\n");
 }
 
+/*
+ * Test Case 1: Stack Overflow (Canary Test)
+ * This function uses a u64 buffer 64-bit write
+ * to corrupt the stack canary with a single operation
+ */
+static void canary_test_overflow(void)
+{
+	u64 buffer[BUFFER_SIZE];
+
+	pr_info("KSW: test: starting %s with u64 write\n", __func__);
+	pr_info("KSW: test: buffer 0x%px\n", buffer);
+
+	/* intentionally overflow the u64 buffer. */
+	buffer[BUFFER_SIZE] = 0xdeadbeefdeadbeef;
+
+	/* make sure the compiler do not drop assign action */
+	barrier_data(buffer);
+
+	pr_info("KSW: test: canary overflow test completed\n");
+}
+
 static ssize_t test_proc_write(struct file *file, const char __user *buffer,
 			       size_t count, loff_t *pos)
 {
@@ -65,7 +86,10 @@ static ssize_t test_proc_write(struct file *file, const char __user *buffer,
 			pr_info("KSW: test: triggering canary write test\n");
 			canary_test_write();
 			break;
-
+		case 1:
+			pr_info("KSW: test: triggering canary overflow test\n");
+			canary_test_overflow();
+			break;
 		default:
 			pr_err("KSW: test: Unknown test number %d\n", test_num);
 			return -EINVAL;
@@ -85,7 +109,8 @@ static ssize_t test_proc_read(struct file *file, char __user *buffer,
 		"KStackWatch Simplified Test Module\n"
 		"==================================\n"
 		"Usage:\n"
-		"  echo 'test0' > /proc/kstackwatch_test  - canary write test\n";
+		"  echo 'test0' > /proc/kstackwatch_test  - Canary write test\n"
+		"  echo 'test1' > /proc/kstackwatch_test  - Canary overflow test\n";
 
 	return simple_read_from_buffer(buffer, count, pos, usage,
 				       strlen(usage));
Signature · 1 line
2.43.0
#32 lore raw

PATCH v2 15/18 mm/ksw: add simplified silent corruption test

In reply to Jinchao Wang

Introduce a lightweight test case simulating “silent” stack corruption where hapless() is unaware its local variable may have been modified. This test is much simpler than real production scenarios but demonstrates the core logic.

Test logic:
- buggy(): exposes a local variable via a global pointer without resetting it, creating a dangling reference.
- unwitting(): a background kernel thread accesses the global pointer and modifies the pointed memory.
- hapless(): operates on its local variable, unaware it may be modified.

This controlled, minimal scenario provides a simple way to validate KStackWatch’s detection of unintended stack modifications or silient corruption.

---
 mm/kstackwatch/kstackwatch_test.c | 90 ++++++++++++++++++++++++++++++-
 1 file changed, 89 insertions(+), 1 deletion(-)
mm/kstackwatch/kstackwatch_test.c +89 -1
index 138163472b03..1f0d616db7c5 100644
@@ -22,6 +22,9 @@ static struct proc_dir_entry *test_proc;
 #define BUFFER_SIZE 4
 #define MAX_DEPTH 4
 
+/* global variables for silient corruption test */
+static u64 *g_corrupt_ptr;
+
 /*
  * Test Case 0: Write to the canary position directly (Canary Test)
  * use a u64 buffer array to ensure the canary will be placed
@@ -63,6 +66,86 @@ static void canary_test_overflow(void)
 	pr_info("KSW: test: canary overflow test completed\n");
 }
 
+static void do_something(int min_ms, int max_ms)
+{
+	u32 rand;
+
+	get_random_bytes(&rand, sizeof(rand));
+	rand = min_ms + rand % (max_ms - min_ms + 1);
+	msleep(rand);
+}
+
+static void silent_corruption_buggy(int i)
+{
+	u64 local_var;
+
+	pr_info("KSW: test: starting %s\n", __func__);
+
+	pr_info("KSW: test: %s %d local_var addr: 0x%px\n", __func__, i,
+		&local_var);
+	WRITE_ONCE(g_corrupt_ptr, &local_var);
+
+	//buggy: return without reset g_corrupt_ptr
+}
+
+static int silent_corruption_unwitting(void *data)
+{
+	pr_debug("KSW: test: starting %s\n", __func__);
+	u64 *local_ptr;
+
+	do {
+		local_ptr = READ_ONCE(g_corrupt_ptr);
+		do_something(0, 300);
+	} while (!local_ptr);
+
+	local_ptr[0] = 0;
+
+	return 0;
+}
+
+static void silent_corruption_hapless(int i)
+{
+	u64 local_var;
+
+	pr_debug("KSW: test: starting %s %d\n", __func__, i);
+	get_random_bytes(&local_var, sizeof(local_var));
+	local_var = 0xff0000 + local_var % 0xffff;
+	pr_debug("KSW: test: %s local_var addr: 0x%px\n", __func__, &local_var);
+
+	do_something(50, 150);
+	if (local_var >= 0xff0000)
+		pr_info("KSW: test: %s %d happy with 0x%llx", __func__, i,
+			local_var);
+	else
+		pr_info("KSW: test: %s %d unhappy with 0x%llx", __func__, i,
+			local_var);
+}
+
+/*
+ * Test Case 2: Silient Corruption
+ * buggy() does not protect its local var correctly
+ * unwitting() simply does its intended work
+ * hapless() is unaware know what happened
+ */
+static void silent_corruption_test(void)
+{
+	struct task_struct *unwitting;
+
+	pr_info("KSW: test: starting %s\n", __func__);
+	WRITE_ONCE(g_corrupt_ptr, NULL);
+
+	unwitting = kthread_run(silent_corruption_unwitting, NULL,
+				"unwitting");
+	if (IS_ERR(unwitting)) {
+		pr_err("KSW: test: failed to create thread2\n");
+		return;
+	}
+
+	silent_corruption_buggy(0);
+	for (int i = 0; i < 10; i++)
+		silent_corruption_hapless(i);
+}
+
 static ssize_t test_proc_write(struct file *file, const char __user *buffer,
 			       size_t count, loff_t *pos)
 {
@@ -90,6 +173,10 @@ static ssize_t test_proc_write(struct file *file, const char __user *buffer,
 			pr_info("KSW: test: triggering canary overflow test\n");
 			canary_test_overflow();
 			break;
+		case 2:
+			pr_info("KSW: test: triggering silent corruption test\n");
+			silent_corruption_test();
+			break;
 		default:
 			pr_err("KSW: test: Unknown test number %d\n", test_num);
 			return -EINVAL;
@@ -110,7 +197,8 @@ static ssize_t test_proc_read(struct file *file, char __user *buffer,
 		"==================================\n"
 		"Usage:\n"
 		"  echo 'test0' > /proc/kstackwatch_test  - Canary write test\n"
-		"  echo 'test1' > /proc/kstackwatch_test  - Canary overflow test\n";
+		"  echo 'test1' > /proc/kstackwatch_test  - Canary overflow test\n"
+		"  echo 'test2' > /proc/kstackwatch_test  - Silent corruption test\n";
 
 	return simple_read_from_buffer(buffer, count, pos, usage,
 				       strlen(usage));
Signature · 1 line
2.43.0
#33 lore raw

PATCH v2 16/18 mm/ksw: add recursive corruption test

In reply to Jinchao Wang

Introduce a test case simulating stack corruption across recursive calls. This scenario writes to a local buffer at every recursion depth up to a configured maximum, allowing validation that KStackWatch can detect corruption in nested stack frames.

---
 mm/kstackwatch/kstackwatch_test.c | 32 ++++++++++++++++++++++++++++++-
 1 file changed, 31 insertions(+), 1 deletion(-)
mm/kstackwatch/kstackwatch_test.c +31 -1
index 1f0d616db7c5..cb216b6ee5d7 100644
@@ -146,6 +146,30 @@ static void silent_corruption_test(void)
 		silent_corruption_hapless(i);
 }
 
+/*
+ * Test Case 3: Recursive Call Corruption
+ * Check whether KStackWatch can handle corruption in a recursive call
+ * Write the local variable at every depth
+ * Configure /proc/kstackwatch to specify the corruption depth
+ * Verify that the watch is triggered
+ */
+static void recursive_corruption_test(int depth)
+{
+	u64 buffer[BUFFER_SIZE];
+
+	pr_info("KSW: test: recursive call at depth %d\n", depth);
+	pr_info("KSW: test: buffer 0x%px\n", buffer);
+	if (depth <= MAX_DEPTH)
+		recursive_corruption_test(depth + 1);
+
+	buffer[0] = depth;
+
+	/* make sure the compiler do not drop assign action */
+	barrier_data(buffer);
+
+	pr_info("KSW: test: returning from depth %d\n", depth);
+}
+
 static ssize_t test_proc_write(struct file *file, const char __user *buffer,
 			       size_t count, loff_t *pos)
 {
@@ -177,6 +201,11 @@ static ssize_t test_proc_write(struct file *file, const char __user *buffer,
 			pr_info("KSW: test: triggering silent corruption test\n");
 			silent_corruption_test();
 			break;
+		case 3:
+			pr_info("KSW: test: triggering recursive corruption test\n");
+			/* depth start with 0 */
+			recursive_corruption_test(0);
+			break;
 		default:
 			pr_err("KSW: test: Unknown test number %d\n", test_num);
 			return -EINVAL;
@@ -198,7 +227,8 @@ static ssize_t test_proc_read(struct file *file, char __user *buffer,
 		"Usage:\n"
 		"  echo 'test0' > /proc/kstackwatch_test  - Canary write test\n"
 		"  echo 'test1' > /proc/kstackwatch_test  - Canary overflow test\n"
-		"  echo 'test2' > /proc/kstackwatch_test  - Silent corruption test\n";
+		"  echo 'test2' > /proc/kstackwatch_test  - Silent corruption test\n"
+		"  echo 'test3' > /proc/kstackwatch_test  - Recursive corruption test\n";
 
 	return simple_read_from_buffer(buffer, count, pos, usage,
 				       strlen(usage));
Signature · 1 line
2.43.0
#34 lore raw

PATCH v2 17/18 tools/kstackwatch: add interactive test script for KStackWatch

In reply to Jinchao Wang

Introduce kstackwatch_test.sh, a shell script to facilitate running various test scenarios interactively or via command-line arguments.

---
 tools/kstackwatch/kstackwatch_test.sh | 118 ++++++++++++++++++++++++++
 1 file changed, 118 insertions(+)
 create mode 100755 tools/kstackwatch/kstackwatch_test.sh
tools/kstackwatch/kstackwatch_test.sh new file +118 -0
new file mode 100755
index 000000000000..fcdb5ac9b607
@@ -0,0 +1,118 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+
+# --- Usage function ---
+usage() {
+	echo "======================================"
+	echo "  KStackWatch Test Script Usage"
+	echo "======================================"
+	echo ""
+	echo "IMPORTANT: Before running, make sure you have updated the offset values!"
+	echo ""
+	echo "To find your offsets, use objdump:"
+	echo "  objdump -S --disassemble=canary_test_write vmlinux"
+	echo ""
+	echo "Then search for your function names to find the instruction addresses."
+	echo "- Instruction offset: address relative to function's start"
+	echo "- Stack var offset: distance from stack base (%rbp) to the variable"
+	echo ""
+	echo "Usage: $0 [test_case_number]"
+	echo ""
+	echo "Available test cases:"
+	echo "  0  - Canary Write Test"
+	echo "  1  - Canary Overflow Test"
+	echo "  2  - Silent Corruption Test"
+	echo "  3  - Recursive Corruption Test"
+	echo ""
+	echo "======================================"
+	echo ""
+}
+
+# --- Interactive menu ---
+show_menu() {
+	echo "Select a test case to run:"
+	echo "  0) Canary Write Test"
+	echo "  1) Canary Overflow Test"
+	echo "  2) Silent Corruption Test"
+	echo "  3) Recursive Corruption Test"
+	echo "  q) Quit"
+	echo ""
+	echo "WARNING: Each test may cause system crash/hang!"
+	echo ""
+	read -p "Enter your choice [0-3/q]: " choice
+	echo ""
+
+	case "$choice" in
+	0) test0 ;;
+	1) test1 ;;
+	2) test2 ;;
+	3) test3 ;;
+	q | Q)
+		echo "Exiting..."
+		exit 0
+		;;
+	*)
+		echo "Invalid choice. Please try again."
+		echo ""
+		show_menu
+		;;
+	esac
+}
+
+# --- Test Case 0: Canary Write ---
+test0() {
+	echo "=== Running Test Case 0: Canary Write ==="
+	# function+instruction_off[+depth] [local_var_offset:local_var_len]
+	echo "canary_test_write+0x12" >/proc/kstackwatch
+	echo "test0" >/proc/kstackwatch_test
+	echo >/proc/kstackwatch
+}
+
+# --- Test Case 1: Canary Overflow ---
+test1() {
+	echo "=== Running Test Case 1: Canary Overflow ==="
+	# function+instruction_off[+depth] [local_var_offset:local_var_len]
+	echo "canary_test_overflow+0x12" >/proc/kstackwatch
+	echo "test1" >/proc/kstackwatch_test
+	echo >/proc/kstackwatch
+
+}
+
+# --- Test Case 2: Silent Corruption ---
+test2() {
+	echo "=== Running Test Case 2: Silent Corruption ==="
+	# function+instruction_off[+depth] [local_var_offset:local_var_len]
+	echo "silent_corruption_hapless+0x7f 0:8" >/proc/kstackwatch
+	echo "test2" >/proc/kstackwatch_test
+	echo >/proc/kstackwatch
+}
+
+# --- Test Case 3: Recursive Corruption ---
+test3() {
+	echo "=== Running Test Case 3: Recursive Corruption ==="
+	# function+instruction_off[+depth] [local_var_offset:local_var_len]
+	echo "recursive_corruption_test+0x1b+3 0:8" >/proc/kstackwatch
+	echo "test3" >/proc/kstackwatch_test
+	echo >/proc/kstackwatch
+}
+
+# --- Main ---
+if [ -z "$1" ]; then
+	usage
+	echo ""
+	show_menu
+else
+	case "$1" in
+	0) test0 ;;
+	1) test1 ;;
+	2) test2 ;;
+	3) test3 ;;
+	help | --help | -h) usage ;;
+	*)
+		echo "Error: Invalid argument '$1'"
+		echo ""
+		usage
+		exit 1
+		;;
+	esac
+fi
Signature · 1 line
2.43.0
#35 lore raw

PATCH v2 18/18 MAINTAINERS: add entry for KStackWatch (Kernel Stack Watch)

In reply to Jinchao Wang

Add Jinchao Wang as the maintainer for KStackWatch, including its kernel module and test script.

---
 MAINTAINERS | 6 ++++++
 1 file changed, 6 insertions(+)
MAINTAINERS +6 -0
index fed6cd812d79..097a0462e604 100644
@@ -13354,6 +13354,12 @@ T:	git git://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git
 F:	Documentation/dev-tools/kselftest*
 F:	tools/testing/selftests/
 
+KERNEL STACK WATCH
+M:	Jinchao Wang <[email protected]>
+S:	Maintained
+F:	mm/kstackwatch/
+F:	tools/kstackwatch/
+
 KERNEL SMB3 SERVER (KSMBD)
 M:	Namjae Jeon <[email protected]>
 M:	Namjae Jeon <[email protected]>
Signature · 1 line
2.43.0