1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2020 SiFive
6 #include <linux/spinlock.h>
8 #include <linux/memory.h>
9 #include <linux/uaccess.h>
10 #include <linux/stop_machine.h>
11 #include <asm/kprobes.h>
12 #include <asm/cacheflush.h>
13 #include <asm/fixmap.h>
14 #include <asm/patch.h>
24 * The fix_to_virt(, idx) needs a const value (not a dynamic variable of
25 * reg-a0) or BUILD_BUG_ON failed with "idx >= __end_of_fixed_addresses".
26 * So use '__always_inline' and 'const unsigned int fixmap' here.
28 static __always_inline void *patch_map(void *addr, const unsigned int fixmap)
30 uintptr_t uintaddr = (uintptr_t) addr;
33 if (core_kernel_text(uintaddr))
34 page = phys_to_page(__pa_symbol(addr));
35 else if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
36 page = vmalloc_to_page(addr);
42 return (void *)set_fixmap_offset(fixmap, page_to_phys(page) +
43 (uintaddr & ~PAGE_MASK));
46 static void patch_unmap(int fixmap)
50 NOKPROBE_SYMBOL(patch_unmap);
52 static int patch_insn_write(void *addr, const void *insn, size_t len)
55 bool across_pages = (((uintptr_t) addr & ~PAGE_MASK) + len) > PAGE_SIZE;
59 * Before reaching here, it was expected to lock the text_mutex
60 * already, so we don't need to give another lock here and could
61 * ensure that it was safe between each cores.
63 lockdep_assert_held(&text_mutex);
66 patch_map(addr + len, FIX_TEXT_POKE1);
68 waddr = patch_map(addr, FIX_TEXT_POKE0);
70 ret = copy_to_kernel_nofault(waddr, insn, len);
72 patch_unmap(FIX_TEXT_POKE0);
75 patch_unmap(FIX_TEXT_POKE1);
79 NOKPROBE_SYMBOL(patch_insn_write);
81 static int patch_insn_write(void *addr, const void *insn, size_t len)
83 return copy_to_kernel_nofault(addr, insn, len);
85 NOKPROBE_SYMBOL(patch_insn_write);
86 #endif /* CONFIG_MMU */
88 int patch_text_nosync(void *addr, const void *insns, size_t len)
93 ret = patch_insn_write(tp, insns, len);
96 flush_icache_range((uintptr_t) tp, (uintptr_t) tp + len);
100 NOKPROBE_SYMBOL(patch_text_nosync);
102 static int patch_text_cb(void *data)
104 struct patch_insn *patch = data;
107 if (atomic_inc_return(&patch->cpu_count) == 1) {
109 patch_text_nosync(patch->addr, &patch->insn,
110 GET_INSN_LENGTH(patch->insn));
111 atomic_inc(&patch->cpu_count);
113 while (atomic_read(&patch->cpu_count) <= num_online_cpus())
120 NOKPROBE_SYMBOL(patch_text_cb);
122 int patch_text(void *addr, u32 insn)
124 struct patch_insn patch = {
127 .cpu_count = ATOMIC_INIT(0),
130 return stop_machine_cpuslocked(patch_text_cb,
131 &patch, cpu_online_mask);
133 NOKPROBE_SYMBOL(patch_text);