Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  * data_breakpoint.c - Sample HW Breakpoint file to watch kernel data address
0004  *
0005  * usage: insmod data_breakpoint.ko ksym=<ksym_name>
0006  *
0007  * This file is a kernel module that places a breakpoint over ksym_name kernel
0008  * variable using Hardware Breakpoint register. The corresponding handler which
0009  * prints a backtrace is invoked every time a write operation is performed on
0010  * that variable.
0011  *
0012  * Copyright (C) IBM Corporation, 2009
0013  *
0014  * Author: K.Prasad <prasad@linux.vnet.ibm.com>
0015  */
0016 #include <linux/module.h>   /* Needed by all modules */
0017 #include <linux/kernel.h>   /* Needed for KERN_INFO */
0018 #include <linux/init.h>     /* Needed for the macros */
0019 #include <linux/kallsyms.h>
0020 
0021 #include <linux/perf_event.h>
0022 #include <linux/hw_breakpoint.h>
0023 
0024 struct perf_event * __percpu *sample_hbp;
0025 
0026 static char ksym_name[KSYM_NAME_LEN] = "jiffies";
0027 module_param_string(ksym, ksym_name, KSYM_NAME_LEN, S_IRUGO);
0028 MODULE_PARM_DESC(ksym, "Kernel symbol to monitor; this module will report any"
0029             " write operations on the kernel symbol");
0030 
0031 static void sample_hbp_handler(struct perf_event *bp,
0032                    struct perf_sample_data *data,
0033                    struct pt_regs *regs)
0034 {
0035     printk(KERN_INFO "%s value is changed\n", ksym_name);
0036     dump_stack();
0037     printk(KERN_INFO "Dump stack from sample_hbp_handler\n");
0038 }
0039 
0040 static int __init hw_break_module_init(void)
0041 {
0042     int ret;
0043     struct perf_event_attr attr;
0044     void *addr = __symbol_get(ksym_name);
0045 
0046     if (!addr)
0047         return -ENXIO;
0048 
0049     hw_breakpoint_init(&attr);
0050     attr.bp_addr = (unsigned long)addr;
0051     attr.bp_len = HW_BREAKPOINT_LEN_4;
0052     attr.bp_type = HW_BREAKPOINT_W;
0053 
0054     sample_hbp = register_wide_hw_breakpoint(&attr, sample_hbp_handler, NULL);
0055     if (IS_ERR((void __force *)sample_hbp)) {
0056         ret = PTR_ERR((void __force *)sample_hbp);
0057         goto fail;
0058     }
0059 
0060     printk(KERN_INFO "HW Breakpoint for %s write installed\n", ksym_name);
0061 
0062     return 0;
0063 
0064 fail:
0065     printk(KERN_INFO "Breakpoint registration failed\n");
0066 
0067     return ret;
0068 }
0069 
0070 static void __exit hw_break_module_exit(void)
0071 {
0072     unregister_wide_hw_breakpoint(sample_hbp);
0073     symbol_put(ksym_name);
0074     printk(KERN_INFO "HW Breakpoint for %s write uninstalled\n", ksym_name);
0075 }
0076 
0077 module_init(hw_break_module_init);
0078 module_exit(hw_break_module_exit);
0079 
0080 MODULE_LICENSE("GPL");
0081 MODULE_AUTHOR("K.Prasad");
0082 MODULE_DESCRIPTION("ksym breakpoint");