1 // SPDX-License-Identifier: GPL-2.0
3 * functions to patch RO kernel text during runtime
5 * Copyright (c) 2019 Sven Schnelle <svens@stackframe.org>
8 #include <linux/kernel.h>
9 #include <linux/spinlock.h>
10 #include <linux/kprobes.h>
12 #include <linux/stop_machine.h>
14 #include <asm/cacheflush.h>
15 #include <asm/fixmap.h>
16 #include <asm/patch.h>
24 static DEFINE_RAW_SPINLOCK(patch_lock);
26 static void __kprobes *patch_map(void *addr, int fixmap, unsigned long *flags,
29 unsigned long uintaddr = (uintptr_t) addr;
30 bool module = !core_kernel_text(uintaddr);
34 if (module && IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
35 page = vmalloc_to_page(addr);
36 else if (!module && IS_ENABLED(CONFIG_STRICT_KERNEL_RWX))
37 page = virt_to_page(addr);
42 set_fixmap(fixmap, page_to_phys(page));
43 raw_spin_lock_irqsave(&patch_lock, *flags);
45 return (void *) (__fix_to_virt(fixmap) + (uintaddr & ~PAGE_MASK));
48 static void __kprobes patch_unmap(int fixmap, unsigned long *flags)
52 raw_spin_unlock_irqrestore(&patch_lock, *flags);
55 void __kprobes __patch_text_multiple(void *addr, u32 *insn, unsigned int len)
57 unsigned long start = (unsigned long)addr;
58 unsigned long end = (unsigned long)addr + len;
63 /* Make sure we don't have any aliases in cache */
64 flush_kernel_dcache_range_asm(start, end);
65 flush_kernel_icache_range_asm(start, end);
66 flush_tlb_kernel_range(start, end);
68 p = fixmap = patch_map(addr, FIX_TEXT_POKE0, &flags, &mapped);
74 if (len && offset_in_page(addr) == 0) {
76 * We're crossing a page boundary, so
79 flush_kernel_dcache_range_asm((unsigned long)fixmap,
81 flush_tlb_kernel_range((unsigned long)fixmap,
84 patch_unmap(FIX_TEXT_POKE0, &flags);
85 p = fixmap = patch_map(addr, FIX_TEXT_POKE0, &flags,
90 flush_kernel_dcache_range_asm((unsigned long)fixmap, (unsigned long)p);
91 flush_tlb_kernel_range((unsigned long)fixmap, (unsigned long)p);
93 patch_unmap(FIX_TEXT_POKE0, &flags);
96 void __kprobes __patch_text(void *addr, u32 insn)
98 __patch_text_multiple(addr, &insn, sizeof(insn));
101 static int __kprobes patch_text_stop_machine(void *data)
103 struct patch *patch = data;
105 __patch_text_multiple(patch->addr, patch->insn, patch->len);
109 void __kprobes patch_text(void *addr, unsigned int insn)
111 struct patch patch = {
117 stop_machine_cpuslocked(patch_text_stop_machine, &patch, NULL);
120 void __kprobes patch_text_multiple(void *addr, u32 *insn, unsigned int len)
123 struct patch patch = {
129 stop_machine_cpuslocked(patch_text_stop_machine, &patch, NULL);