1 // SPDX-License-Identifier: GPL-2.0-only
2 #define pr_fmt(fmt) "SMP alternatives: " fmt
4 #include <linux/module.h>
5 #include <linux/sched.h>
6 #include <linux/perf_event.h>
7 #include <linux/mutex.h>
8 #include <linux/list.h>
9 #include <linux/stringify.h>
10 #include <linux/highmem.h>
12 #include <linux/vmalloc.h>
13 #include <linux/memory.h>
14 #include <linux/stop_machine.h>
15 #include <linux/slab.h>
16 #include <linux/kdebug.h>
17 #include <linux/kprobes.h>
18 #include <linux/mmu_context.h>
19 #include <linux/bsearch.h>
20 #include <linux/sync_core.h>
21 #include <asm/text-patching.h>
22 #include <asm/alternative.h>
23 #include <asm/sections.h>
26 #include <asm/cacheflush.h>
27 #include <asm/tlbflush.h>
30 #include <asm/fixmap.h>
31 #include <asm/paravirt.h>
32 #include <asm/asm-prototypes.h>
34 int __read_mostly alternatives_patched;
36 EXPORT_SYMBOL_GPL(alternatives_patched);
38 #define MAX_PATCH_LEN (255-1)
40 static int __initdata_or_module debug_alternative;
42 static int __init debug_alt(char *str)
44 debug_alternative = 1;
47 __setup("debug-alternative", debug_alt);
49 static int noreplace_smp;
51 static int __init setup_noreplace_smp(char *str)
56 __setup("noreplace-smp", setup_noreplace_smp);
58 #define DPRINTK(fmt, args...) \
60 if (debug_alternative) \
61 printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \
64 #define DUMP_BYTES(buf, len, fmt, args...) \
66 if (unlikely(debug_alternative)) { \
72 printk(KERN_DEBUG pr_fmt(fmt), ##args); \
73 for (j = 0; j < (len) - 1; j++) \
74 printk(KERN_CONT "%02hhx ", buf[j]); \
75 printk(KERN_CONT "%02hhx\n", buf[j]); \
79 static const unsigned char x86nops[] =
91 const unsigned char * const x86_nops[ASM_NOP_MAX+1] =
98 x86nops + 1 + 2 + 3 + 4,
99 x86nops + 1 + 2 + 3 + 4 + 5,
100 x86nops + 1 + 2 + 3 + 4 + 5 + 6,
101 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
104 /* Use this to add nops to a buffer, then text_poke the whole buffer. */
105 static void __init_or_module add_nops(void *insns, unsigned int len)
108 unsigned int noplen = len;
109 if (noplen > ASM_NOP_MAX)
110 noplen = ASM_NOP_MAX;
111 memcpy(insns, x86_nops[noplen], noplen);
117 extern s32 __retpoline_sites[], __retpoline_sites_end[];
118 extern s32 __return_sites[], __return_sites_end[];
119 extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
120 extern s32 __smp_locks[], __smp_locks_end[];
121 void text_poke_early(void *addr, const void *opcode, size_t len);
124 * Are we looking at a near JMP with a 1 or 4-byte displacement.
126 static inline bool is_jmp(const u8 opcode)
128 return opcode == 0xeb || opcode == 0xe9;
131 static void __init_or_module
132 recompute_jump(struct alt_instr *a, u8 *orig_insn, u8 *repl_insn, u8 *insn_buff)
134 u8 *next_rip, *tgt_rip;
138 if (a->replacementlen != 5)
141 o_dspl = *(s32 *)(insn_buff + 1);
143 /* next_rip of the replacement JMP */
144 next_rip = repl_insn + a->replacementlen;
145 /* target rip of the replacement JMP */
146 tgt_rip = next_rip + o_dspl;
147 n_dspl = tgt_rip - orig_insn;
149 DPRINTK("target RIP: %px, new_displ: 0x%x", tgt_rip, n_dspl);
151 if (tgt_rip - orig_insn >= 0) {
152 if (n_dspl - 2 <= 127)
156 /* negative offset */
158 if (((n_dspl - 2) & 0xff) == (n_dspl - 2))
168 insn_buff[1] = (s8)n_dspl;
169 add_nops(insn_buff + 2, 3);
178 *(s32 *)&insn_buff[1] = n_dspl;
184 DPRINTK("final displ: 0x%08x, JMP 0x%lx",
185 n_dspl, (unsigned long)orig_insn + n_dspl + repl_len);
189 * optimize_nops_range() - Optimize a sequence of single byte NOPs (0x90)
191 * @instr: instruction byte stream
192 * @instrlen: length of the above
193 * @off: offset within @instr where the first NOP has been detected
195 * Return: number of NOPs found (and replaced).
197 static __always_inline int optimize_nops_range(u8 *instr, u8 instrlen, int off)
202 while (i < instrlen) {
203 if (instr[i] != 0x90)
214 local_irq_save(flags);
215 add_nops(instr + off, nnops);
216 local_irq_restore(flags);
218 DUMP_BYTES(instr, instrlen, "%px: [%d:%d) optimized NOPs: ", instr, off, i);
224 * "noinline" to cause control flow change and thus invalidate I$ and
225 * cause refetch after modification.
227 static void __init_or_module noinline optimize_nops(u8 *instr, size_t len)
233 * Jump over the non-NOP insns and optimize single-byte NOPs into bigger
237 if (insn_decode_kernel(&insn, &instr[i]))
241 * See if this and any potentially following NOPs can be
244 if (insn.length == 1 && insn.opcode.bytes[0] == 0x90)
245 i += optimize_nops_range(instr, len, i);
255 * Replace instructions with better alternatives for this CPU type. This runs
256 * before SMP is initialized to avoid SMP problems with self modifying code.
257 * This implies that asymmetric systems where APs have less capabilities than
258 * the boot processor are not handled. Tough. Make sure you disable such
261 * Marked "noinline" to cause control flow change and thus insn cache
262 * to refetch changed I$ lines.
264 void __init_or_module noinline apply_alternatives(struct alt_instr *start,
265 struct alt_instr *end)
268 u8 *instr, *replacement;
269 u8 insn_buff[MAX_PATCH_LEN];
271 DPRINTK("alt table %px, -> %px", start, end);
274 * In the case CONFIG_X86_5LEVEL=y, KASAN_SHADOW_START is defined using
275 * cpu_feature_enabled(X86_FEATURE_LA57) and is therefore patched here.
276 * During the process, KASAN becomes confused seeing partial LA57
277 * conversion and triggers a false-positive out-of-bound report.
279 * Disable KASAN until the patching is complete.
281 kasan_disable_current();
284 * The scan order should be from start to end. A later scanned
285 * alternative code can overwrite previously scanned alternative code.
286 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
289 * So be careful if you want to change the scan order to any other
292 for (a = start; a < end; a++) {
293 int insn_buff_sz = 0;
294 /* Mask away "NOT" flag bit for feature to test. */
295 u16 feature = a->cpuid & ~ALTINSTR_FLAG_INV;
297 instr = (u8 *)&a->instr_offset + a->instr_offset;
298 replacement = (u8 *)&a->repl_offset + a->repl_offset;
299 BUG_ON(a->instrlen > sizeof(insn_buff));
300 BUG_ON(feature >= (NCAPINTS + NBUGINTS) * 32);
304 * - feature is present
305 * - feature not present but ALTINSTR_FLAG_INV is set to mean,
306 * patch if feature is *NOT* present.
308 if (!boot_cpu_has(feature) == !(a->cpuid & ALTINSTR_FLAG_INV))
311 DPRINTK("feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)",
312 (a->cpuid & ALTINSTR_FLAG_INV) ? "!" : "",
315 instr, instr, a->instrlen,
316 replacement, a->replacementlen);
318 DUMP_BYTES(instr, a->instrlen, "%px: old_insn: ", instr);
319 DUMP_BYTES(replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
321 memcpy(insn_buff, replacement, a->replacementlen);
322 insn_buff_sz = a->replacementlen;
325 * 0xe8 is a relative jump; fix the offset.
327 * Instruction length is checked before the opcode to avoid
328 * accessing uninitialized bytes for zero-length replacements.
330 if (a->replacementlen == 5 && *insn_buff == 0xe8) {
331 *(s32 *)(insn_buff + 1) += replacement - instr;
332 DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
333 *(s32 *)(insn_buff + 1),
334 (unsigned long)instr + *(s32 *)(insn_buff + 1) + 5);
337 if (a->replacementlen && is_jmp(replacement[0]))
338 recompute_jump(a, instr, replacement, insn_buff);
340 for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
341 insn_buff[insn_buff_sz] = 0x90;
343 DUMP_BYTES(insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
345 text_poke_early(instr, insn_buff, insn_buff_sz);
348 optimize_nops(instr, a->instrlen);
351 kasan_enable_current();
354 #if defined(CONFIG_RETPOLINE) && defined(CONFIG_STACK_VALIDATION)
359 static int emit_indirect(int op, int reg, u8 *bytes)
365 case CALL_INSN_OPCODE:
366 modrm = 0x10; /* Reg = 2; CALL r/m */
369 case JMP32_INSN_OPCODE:
370 modrm = 0x20; /* Reg = 4; JMP r/m */
379 bytes[i++] = 0x41; /* REX.B prefix */
383 modrm |= 0xc0; /* Mod = 3 */
386 bytes[i++] = 0xff; /* opcode */
393 * Rewrite the compiler generated retpoline thunk calls.
395 * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
396 * indirect instructions, avoiding the extra indirection.
398 * For example, convert:
400 * CALL __x86_indirect_thunk_\reg
406 * It also tries to inline spectre_v2=retpoline,amd when size permits.
408 static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
410 retpoline_thunk_t *target;
414 target = addr + insn->length + insn->immediate.value;
415 reg = target - __x86_indirect_thunk_array;
417 if (WARN_ON_ONCE(reg & ~0xf))
420 /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
423 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
424 !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE))
427 op = insn->opcode.bytes[0];
432 * Jcc.d32 __x86_indirect_thunk_\reg
442 /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
443 if (op == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80) {
444 cc = insn->opcode.bytes[1] & 0xf;
445 cc ^= 1; /* invert condition */
447 bytes[i++] = 0x70 + cc; /* Jcc.d8 */
448 bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
450 /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
451 op = JMP32_INSN_OPCODE;
455 * For RETPOLINE_AMD: prepend the indirect CALL/JMP with an LFENCE.
457 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
460 bytes[i++] = 0xe8; /* LFENCE */
463 ret = emit_indirect(op, reg, bytes + i);
468 for (; i < insn->length;)
469 bytes[i++] = BYTES_NOP1;
475 * Generated by 'objtool --retpoline'.
477 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
481 for (s = start; s < end; s++) {
482 void *addr = (void *)s + *s;
488 ret = insn_decode_kernel(&insn, addr);
489 if (WARN_ON_ONCE(ret < 0))
492 op1 = insn.opcode.bytes[0];
493 op2 = insn.opcode.bytes[1];
496 case CALL_INSN_OPCODE:
497 case JMP32_INSN_OPCODE:
500 case 0x0f: /* escape */
501 if (op2 >= 0x80 && op2 <= 0x8f)
509 DPRINTK("retpoline at: %pS (%px) len: %d to: %pS",
510 addr, addr, insn.length,
511 addr + insn.length + insn.immediate.value);
513 len = patch_retpoline(addr, &insn, bytes);
514 if (len == insn.length) {
515 optimize_nops(bytes, len);
516 DUMP_BYTES(((u8*)addr), len, "%px: orig: ", addr);
517 DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
518 text_poke_early(addr, bytes, len);
523 #ifdef CONFIG_RETHUNK
525 * Rewrite the compiler generated return thunk tail-calls.
527 * For example, convert:
529 * JMP __x86_return_thunk
535 static int patch_return(void *addr, struct insn *insn, u8 *bytes)
539 if (cpu_feature_enabled(X86_FEATURE_RETHUNK))
542 bytes[i++] = RET_INSN_OPCODE;
544 for (; i < insn->length;)
545 bytes[i++] = INT3_INSN_OPCODE;
550 void __init_or_module noinline apply_returns(s32 *start, s32 *end)
554 for (s = start; s < end; s++) {
555 void *dest = NULL, *addr = (void *)s + *s;
561 ret = insn_decode_kernel(&insn, addr);
562 if (WARN_ON_ONCE(ret < 0))
565 op = insn.opcode.bytes[0];
566 if (op == JMP32_INSN_OPCODE)
567 dest = addr + insn.length + insn.immediate.value;
569 if (__static_call_fixup(addr, op, dest) ||
570 WARN_ONCE(dest != &__x86_return_thunk,
571 "missing return thunk: %pS-%pS: %*ph",
572 addr, dest, 5, addr))
575 DPRINTK("return thunk at: %pS (%px) len: %d to: %pS",
576 addr, addr, insn.length,
577 addr + insn.length + insn.immediate.value);
579 len = patch_return(addr, &insn, bytes);
580 if (len == insn.length) {
581 DUMP_BYTES(((u8*)addr), len, "%px: orig: ", addr);
582 DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
583 text_poke_early(addr, bytes, len);
588 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
589 #endif /* CONFIG_RETHUNK */
591 #else /* !RETPOLINES || !CONFIG_STACK_VALIDATION */
593 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
594 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
596 #endif /* CONFIG_RETPOLINE && CONFIG_STACK_VALIDATION */
599 static void alternatives_smp_lock(const s32 *start, const s32 *end,
600 u8 *text, u8 *text_end)
604 for (poff = start; poff < end; poff++) {
605 u8 *ptr = (u8 *)poff + *poff;
607 if (!*poff || ptr < text || ptr >= text_end)
609 /* turn DS segment override prefix into lock prefix */
611 text_poke(ptr, ((unsigned char []){0xf0}), 1);
615 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
616 u8 *text, u8 *text_end)
620 for (poff = start; poff < end; poff++) {
621 u8 *ptr = (u8 *)poff + *poff;
623 if (!*poff || ptr < text || ptr >= text_end)
625 /* turn lock prefix into DS segment override prefix */
627 text_poke(ptr, ((unsigned char []){0x3E}), 1);
631 struct smp_alt_module {
632 /* what is this ??? */
636 /* ptrs to lock prefixes */
638 const s32 *locks_end;
640 /* .text segment, needed to avoid patching init code ;) */
644 struct list_head next;
646 static LIST_HEAD(smp_alt_modules);
647 static bool uniproc_patched = false; /* protected by text_mutex */
649 void __init_or_module alternatives_smp_module_add(struct module *mod,
651 void *locks, void *locks_end,
652 void *text, void *text_end)
654 struct smp_alt_module *smp;
656 mutex_lock(&text_mutex);
657 if (!uniproc_patched)
660 if (num_possible_cpus() == 1)
661 /* Don't bother remembering, we'll never have to undo it. */
664 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
666 /* we'll run the (safe but slow) SMP code then ... */
672 smp->locks_end = locks_end;
674 smp->text_end = text_end;
675 DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
676 smp->locks, smp->locks_end,
677 smp->text, smp->text_end, smp->name);
679 list_add_tail(&smp->next, &smp_alt_modules);
681 alternatives_smp_unlock(locks, locks_end, text, text_end);
683 mutex_unlock(&text_mutex);
686 void __init_or_module alternatives_smp_module_del(struct module *mod)
688 struct smp_alt_module *item;
690 mutex_lock(&text_mutex);
691 list_for_each_entry(item, &smp_alt_modules, next) {
692 if (mod != item->mod)
694 list_del(&item->next);
698 mutex_unlock(&text_mutex);
701 void alternatives_enable_smp(void)
703 struct smp_alt_module *mod;
705 /* Why bother if there are no other CPUs? */
706 BUG_ON(num_possible_cpus() == 1);
708 mutex_lock(&text_mutex);
710 if (uniproc_patched) {
711 pr_info("switching to SMP code\n");
712 BUG_ON(num_online_cpus() != 1);
713 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
714 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
715 list_for_each_entry(mod, &smp_alt_modules, next)
716 alternatives_smp_lock(mod->locks, mod->locks_end,
717 mod->text, mod->text_end);
718 uniproc_patched = false;
720 mutex_unlock(&text_mutex);
724 * Return 1 if the address range is reserved for SMP-alternatives.
725 * Must hold text_mutex.
727 int alternatives_text_reserved(void *start, void *end)
729 struct smp_alt_module *mod;
731 u8 *text_start = start;
734 lockdep_assert_held(&text_mutex);
736 list_for_each_entry(mod, &smp_alt_modules, next) {
737 if (mod->text > text_end || mod->text_end < text_start)
739 for (poff = mod->locks; poff < mod->locks_end; poff++) {
740 const u8 *ptr = (const u8 *)poff + *poff;
742 if (text_start <= ptr && text_end > ptr)
749 #endif /* CONFIG_SMP */
751 #ifdef CONFIG_PARAVIRT
752 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
753 struct paravirt_patch_site *end)
755 struct paravirt_patch_site *p;
756 char insn_buff[MAX_PATCH_LEN];
758 for (p = start; p < end; p++) {
761 BUG_ON(p->len > MAX_PATCH_LEN);
762 /* prep the buffer with the original instructions */
763 memcpy(insn_buff, p->instr, p->len);
764 used = paravirt_patch(p->type, insn_buff, (unsigned long)p->instr, p->len);
766 BUG_ON(used > p->len);
768 /* Pad the rest with nops */
769 add_nops(insn_buff + used, p->len - used);
770 text_poke_early(p->instr, insn_buff, p->len);
773 extern struct paravirt_patch_site __start_parainstructions[],
774 __stop_parainstructions[];
775 #endif /* CONFIG_PARAVIRT */
778 * Self-test for the INT3 based CALL emulation code.
780 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
781 * properly and that there is a stack gap between the INT3 frame and the
782 * previous context. Without this gap doing a virtual PUSH on the interrupted
783 * stack would corrupt the INT3 IRET frame.
785 * See entry_{32,64}.S for more details.
789 * We define the int3_magic() function in assembly to control the calling
790 * convention such that we can 'call' it from assembly.
793 extern void int3_magic(unsigned int *ptr); /* defined in asm */
796 " .pushsection .init.text, \"ax\", @progbits\n"
797 " .type int3_magic, @function\n"
799 " movl $1, (%" _ASM_ARG1 ")\n"
801 " .size int3_magic, .-int3_magic\n"
805 extern __initdata unsigned long int3_selftest_ip; /* defined in asm below */
808 int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
810 struct die_args *args = data;
811 struct pt_regs *regs = args->regs;
813 if (!regs || user_mode(regs))
819 if (regs->ip - INT3_INSN_SIZE != int3_selftest_ip)
822 int3_emulate_call(regs, (unsigned long)&int3_magic);
826 static void __init int3_selftest(void)
828 static __initdata struct notifier_block int3_exception_nb = {
829 .notifier_call = int3_exception_notify,
830 .priority = INT_MAX-1, /* last */
832 unsigned int val = 0;
834 BUG_ON(register_die_notifier(&int3_exception_nb));
837 * Basically: int3_magic(&val); but really complicated :-)
839 * Stick the address of the INT3 instruction into int3_selftest_ip,
840 * then trigger the INT3, padded with NOPs to match a CALL instruction
843 asm volatile ("1: int3; nop; nop; nop; nop\n\t"
844 ".pushsection .init.data,\"aw\"\n\t"
845 ".align " __ASM_SEL(4, 8) "\n\t"
846 ".type int3_selftest_ip, @object\n\t"
847 ".size int3_selftest_ip, " __ASM_SEL(4, 8) "\n\t"
848 "int3_selftest_ip:\n\t"
849 __ASM_SEL(.long, .quad) " 1b\n\t"
851 : ASM_CALL_CONSTRAINT
852 : __ASM_SEL_RAW(a, D) (&val)
857 unregister_die_notifier(&int3_exception_nb);
860 void __init alternative_instructions(void)
865 * The patching is not fully atomic, so try to avoid local
866 * interruptions that might execute the to be patched code.
867 * Other CPUs are not running.
872 * Don't stop machine check exceptions while patching.
873 * MCEs only happen when something got corrupted and in this
874 * case we must do something about the corruption.
875 * Ignoring it is worse than an unlikely patching race.
876 * Also machine checks tend to be broadcast and if one CPU
877 * goes into machine check the others follow quickly, so we don't
878 * expect a machine check to cause undue problems during to code
883 * Paravirt patching and alternative patching can be combined to
884 * replace a function call with a short direct code sequence (e.g.
885 * by setting a constant return value instead of doing that in an
886 * external function).
887 * In order to make this work the following sequence is required:
888 * 1. set (artificial) features depending on used paravirt
889 * functions which can later influence alternative patching
890 * 2. apply paravirt patching (generally replacing an indirect
891 * function call with a direct one)
892 * 3. apply alternative patching (e.g. replacing a direct function
893 * call with a custom code sequence)
894 * Doing paravirt patching after alternative patching would clobber
895 * the optimization of the custom code with a function call again.
900 * First patch paravirt functions, such that we overwrite the indirect
901 * call with the direct call.
903 apply_paravirt(__parainstructions, __parainstructions_end);
906 * Rewrite the retpolines, must be done before alternatives since
907 * those can rewrite the retpoline thunks.
909 apply_retpolines(__retpoline_sites, __retpoline_sites_end);
910 apply_returns(__return_sites, __return_sites_end);
913 * Then patch alternatives, such that those paravirt calls that are in
914 * alternatives can be overwritten by their immediate fragments.
916 apply_alternatives(__alt_instructions, __alt_instructions_end);
919 /* Patch to UP if other cpus not imminent. */
920 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
921 uniproc_patched = true;
922 alternatives_smp_module_add(NULL, "core kernel",
923 __smp_locks, __smp_locks_end,
927 if (!uniproc_patched || num_possible_cpus() == 1) {
928 free_init_pages("SMP alternatives",
929 (unsigned long)__smp_locks,
930 (unsigned long)__smp_locks_end);
935 alternatives_patched = 1;
939 * text_poke_early - Update instructions on a live kernel at boot time
940 * @addr: address to modify
941 * @opcode: source of the copy
942 * @len: length to copy
944 * When you use this code to patch more than one byte of an instruction
945 * you need to make sure that other CPUs cannot execute this code in parallel.
946 * Also no thread must be currently preempted in the middle of these
947 * instructions. And on the local CPU you need to be protected against NMI or
948 * MCE handlers seeing an inconsistent instruction while you patch.
950 void __init_or_module text_poke_early(void *addr, const void *opcode,
955 if (boot_cpu_has(X86_FEATURE_NX) &&
956 is_module_text_address((unsigned long)addr)) {
958 * Modules text is marked initially as non-executable, so the
959 * code cannot be running and speculative code-fetches are
960 * prevented. Just change the code.
962 memcpy(addr, opcode, len);
964 local_irq_save(flags);
965 memcpy(addr, opcode, len);
966 local_irq_restore(flags);
970 * Could also do a CLFLUSH here to speed up CPU recovery; but
971 * that causes hangs on some VIA CPUs.
977 struct mm_struct *mm;
981 * Using a temporary mm allows to set temporary mappings that are not accessible
982 * by other CPUs. Such mappings are needed to perform sensitive memory writes
983 * that override the kernel memory protections (e.g., W^X), without exposing the
984 * temporary page-table mappings that are required for these write operations to
985 * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
986 * mapping is torn down.
988 * Context: The temporary mm needs to be used exclusively by a single core. To
989 * harden security IRQs must be disabled while the temporary mm is
990 * loaded, thereby preventing interrupt handler bugs from overriding
991 * the kernel memory protection.
993 static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
995 temp_mm_state_t temp_state;
997 lockdep_assert_irqs_disabled();
1000 * Make sure not to be in TLB lazy mode, as otherwise we'll end up
1001 * with a stale address space WITHOUT being in lazy mode after
1002 * restoring the previous mm.
1004 if (this_cpu_read(cpu_tlbstate_shared.is_lazy))
1005 leave_mm(smp_processor_id());
1007 temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
1008 switch_mm_irqs_off(NULL, mm, current);
1011 * If breakpoints are enabled, disable them while the temporary mm is
1012 * used. Userspace might set up watchpoints on addresses that are used
1013 * in the temporary mm, which would lead to wrong signals being sent or
1016 * Note that breakpoints are not disabled selectively, which also causes
1017 * kernel breakpoints (e.g., perf's) to be disabled. This might be
1018 * undesirable, but still seems reasonable as the code that runs in the
1019 * temporary mm should be short.
1021 if (hw_breakpoint_active())
1022 hw_breakpoint_disable();
1027 static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
1029 lockdep_assert_irqs_disabled();
1030 switch_mm_irqs_off(NULL, prev_state.mm, current);
1033 * Restore the breakpoints if they were disabled before the temporary mm
1036 if (hw_breakpoint_active())
1037 hw_breakpoint_restore();
1040 __ro_after_init struct mm_struct *poking_mm;
1041 __ro_after_init unsigned long poking_addr;
1043 static void *__text_poke(void *addr, const void *opcode, size_t len)
1045 bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
1046 struct page *pages[2] = {NULL};
1047 temp_mm_state_t prev;
1048 unsigned long flags;
1054 * While boot memory allocator is running we cannot use struct pages as
1055 * they are not yet initialized. There is no way to recover.
1057 BUG_ON(!after_bootmem);
1059 if (!core_kernel_text((unsigned long)addr)) {
1060 pages[0] = vmalloc_to_page(addr);
1061 if (cross_page_boundary)
1062 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
1064 pages[0] = virt_to_page(addr);
1065 WARN_ON(!PageReserved(pages[0]));
1066 if (cross_page_boundary)
1067 pages[1] = virt_to_page(addr + PAGE_SIZE);
1070 * If something went wrong, crash and burn since recovery paths are not
1073 BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
1076 * Map the page without the global bit, as TLB flushing is done with
1077 * flush_tlb_mm_range(), which is intended for non-global PTEs.
1079 pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
1082 * The lock is not really needed, but this allows to avoid open-coding.
1084 ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
1087 * This must not fail; preallocated in poking_init().
1091 local_irq_save(flags);
1093 pte = mk_pte(pages[0], pgprot);
1094 set_pte_at(poking_mm, poking_addr, ptep, pte);
1096 if (cross_page_boundary) {
1097 pte = mk_pte(pages[1], pgprot);
1098 set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
1102 * Loading the temporary mm behaves as a compiler barrier, which
1103 * guarantees that the PTE will be set at the time memcpy() is done.
1105 prev = use_temporary_mm(poking_mm);
1107 kasan_disable_current();
1108 memcpy((u8 *)poking_addr + offset_in_page(addr), opcode, len);
1109 kasan_enable_current();
1112 * Ensure that the PTE is only cleared after the instructions of memcpy
1113 * were issued by using a compiler barrier.
1117 pte_clear(poking_mm, poking_addr, ptep);
1118 if (cross_page_boundary)
1119 pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
1122 * Loading the previous page-table hierarchy requires a serializing
1123 * instruction that already allows the core to see the updated version.
1124 * Xen-PV is assumed to serialize execution in a similar manner.
1126 unuse_temporary_mm(prev);
1129 * Flushing the TLB might involve IPIs, which would require enabled
1130 * IRQs, but not if the mm is not used, as it is in this point.
1132 flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
1133 (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
1137 * If the text does not match what we just wrote then something is
1138 * fundamentally screwy; there's nothing we can really do about that.
1140 BUG_ON(memcmp(addr, opcode, len));
1142 local_irq_restore(flags);
1143 pte_unmap_unlock(ptep, ptl);
1148 * text_poke - Update instructions on a live kernel
1149 * @addr: address to modify
1150 * @opcode: source of the copy
1151 * @len: length to copy
1153 * Only atomic text poke/set should be allowed when not doing early patching.
1154 * It means the size must be writable atomically and the address must be aligned
1155 * in a way that permits an atomic write. It also makes sure we fit on a single
1158 * Note that the caller must ensure that if the modified code is part of a
1159 * module, the module would not be removed during poking. This can be achieved
1160 * by registering a module notifier, and ordering module removal and patching
1163 void *text_poke(void *addr, const void *opcode, size_t len)
1165 lockdep_assert_held(&text_mutex);
1167 return __text_poke(addr, opcode, len);
1171 * text_poke_kgdb - Update instructions on a live kernel by kgdb
1172 * @addr: address to modify
1173 * @opcode: source of the copy
1174 * @len: length to copy
1176 * Only atomic text poke/set should be allowed when not doing early patching.
1177 * It means the size must be writable atomically and the address must be aligned
1178 * in a way that permits an atomic write. It also makes sure we fit on a single
1181 * Context: should only be used by kgdb, which ensures no other core is running,
1182 * despite the fact it does not hold the text_mutex.
1184 void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
1186 return __text_poke(addr, opcode, len);
1189 static void do_sync_core(void *info)
1194 void text_poke_sync(void)
1196 on_each_cpu(do_sync_core, NULL, 1);
1199 struct text_poke_loc {
1200 /* addr := _stext + rel_addr */
1205 const u8 text[POKE_MAX_OPCODE_SIZE];
1206 /* see text_poke_bp_batch() */
1210 struct bp_patching_desc {
1211 struct text_poke_loc *vec;
1216 static struct bp_patching_desc bp_desc;
1218 static __always_inline
1219 struct bp_patching_desc *try_get_desc(void)
1221 struct bp_patching_desc *desc = &bp_desc;
1223 if (!arch_atomic_inc_not_zero(&desc->refs))
1229 static __always_inline void put_desc(void)
1231 struct bp_patching_desc *desc = &bp_desc;
1233 smp_mb__before_atomic();
1234 arch_atomic_dec(&desc->refs);
1237 static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
1239 return _stext + tp->rel_addr;
1242 static __always_inline int patch_cmp(const void *key, const void *elt)
1244 struct text_poke_loc *tp = (struct text_poke_loc *) elt;
1246 if (key < text_poke_addr(tp))
1248 if (key > text_poke_addr(tp))
1253 noinstr int poke_int3_handler(struct pt_regs *regs)
1255 struct bp_patching_desc *desc;
1256 struct text_poke_loc *tp;
1260 if (user_mode(regs))
1264 * Having observed our INT3 instruction, we now must observe
1265 * bp_desc with non-zero refcount:
1267 * bp_desc.refs = 1 INT3
1269 * write INT3 if (bp_desc.refs != 0)
1273 desc = try_get_desc();
1278 * Discount the INT3. See text_poke_bp_batch().
1280 ip = (void *) regs->ip - INT3_INSN_SIZE;
1283 * Skip the binary search if there is a single member in the vector.
1285 if (unlikely(desc->nr_entries > 1)) {
1286 tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
1287 sizeof(struct text_poke_loc),
1293 if (text_poke_addr(tp) != ip)
1299 switch (tp->opcode) {
1300 case INT3_INSN_OPCODE:
1302 * Someone poked an explicit INT3, they'll want to handle it,
1307 case RET_INSN_OPCODE:
1308 int3_emulate_ret(regs);
1311 case CALL_INSN_OPCODE:
1312 int3_emulate_call(regs, (long)ip + tp->disp);
1315 case JMP32_INSN_OPCODE:
1316 case JMP8_INSN_OPCODE:
1317 int3_emulate_jmp(regs, (long)ip + tp->disp);
1331 #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
1332 static struct text_poke_loc tp_vec[TP_VEC_MAX];
1333 static int tp_vec_nr;
1336 * text_poke_bp_batch() -- update instructions on live kernel on SMP
1337 * @tp: vector of instructions to patch
1338 * @nr_entries: number of entries in the vector
1340 * Modify multi-byte instruction by using int3 breakpoint on SMP.
1341 * We completely avoid stop_machine() here, and achieve the
1342 * synchronization using int3 breakpoint.
1344 * The way it is done:
1345 * - For each entry in the vector:
1346 * - add a int3 trap to the address that will be patched
1348 * - For each entry in the vector:
1349 * - update all but the first byte of the patched range
1351 * - For each entry in the vector:
1352 * - replace the first byte (int3) by the first byte of
1356 static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
1358 unsigned char int3 = INT3_INSN_OPCODE;
1362 lockdep_assert_held(&text_mutex);
1365 bp_desc.nr_entries = nr_entries;
1368 * Corresponds to the implicit memory barrier in try_get_desc() to
1369 * ensure reading a non-zero refcount provides up to date bp_desc data.
1371 atomic_set_release(&bp_desc.refs, 1);
1374 * Corresponding read barrier in int3 notifier for making sure the
1375 * nr_entries and handler are correctly ordered wrt. patching.
1380 * First step: add a int3 trap to the address that will be patched.
1382 for (i = 0; i < nr_entries; i++) {
1383 tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
1384 text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
1390 * Second step: update all but the first byte of the patched range.
1392 for (do_sync = 0, i = 0; i < nr_entries; i++) {
1393 u8 old[POKE_MAX_OPCODE_SIZE] = { tp[i].old, };
1394 int len = tp[i].len;
1396 if (len - INT3_INSN_SIZE > 0) {
1397 memcpy(old + INT3_INSN_SIZE,
1398 text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1399 len - INT3_INSN_SIZE);
1400 text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1401 (const char *)tp[i].text + INT3_INSN_SIZE,
1402 len - INT3_INSN_SIZE);
1407 * Emit a perf event to record the text poke, primarily to
1408 * support Intel PT decoding which must walk the executable code
1409 * to reconstruct the trace. The flow up to here is:
1412 * - write instruction tail
1413 * At this point the actual control flow will be through the
1414 * INT3 and handler and not hit the old or new instruction.
1415 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
1416 * can still be decoded. Subsequently:
1417 * - emit RECORD_TEXT_POKE with the new instruction
1419 * - write first byte
1421 * So before the text poke event timestamp, the decoder will see
1422 * either the old instruction flow or FUP/TIP of INT3. After the
1423 * text poke event timestamp, the decoder will see either the
1424 * new instruction flow or FUP/TIP of INT3. Thus decoders can
1425 * use the timestamp as the point at which to modify the
1427 * The old instruction is recorded so that the event can be
1428 * processed forwards or backwards.
1430 perf_event_text_poke(text_poke_addr(&tp[i]), old, len,
1436 * According to Intel, this core syncing is very likely
1437 * not necessary and we'd be safe even without it. But
1438 * better safe than sorry (plus there's not only Intel).
1444 * Third step: replace the first byte (int3) by the first byte of
1447 for (do_sync = 0, i = 0; i < nr_entries; i++) {
1448 if (tp[i].text[0] == INT3_INSN_OPCODE)
1451 text_poke(text_poke_addr(&tp[i]), tp[i].text, INT3_INSN_SIZE);
1459 * Remove and wait for refs to be zero.
1461 if (!atomic_dec_and_test(&bp_desc.refs))
1462 atomic_cond_read_acquire(&bp_desc.refs, !VAL);
1465 static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
1466 const void *opcode, size_t len, const void *emulate)
1471 memcpy((void *)tp->text, opcode, len);
1475 ret = insn_decode_kernel(&insn, emulate);
1478 tp->rel_addr = addr - (void *)_stext;
1480 tp->opcode = insn.opcode.bytes[0];
1482 switch (tp->opcode) {
1483 case RET_INSN_OPCODE:
1484 case JMP32_INSN_OPCODE:
1485 case JMP8_INSN_OPCODE:
1487 * Control flow instructions without implied execution of the
1488 * next instruction can be padded with INT3.
1490 for (i = insn.length; i < len; i++)
1491 BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
1495 BUG_ON(len != insn.length);
1499 switch (tp->opcode) {
1500 case INT3_INSN_OPCODE:
1501 case RET_INSN_OPCODE:
1504 case CALL_INSN_OPCODE:
1505 case JMP32_INSN_OPCODE:
1506 case JMP8_INSN_OPCODE:
1507 tp->disp = insn.immediate.value;
1510 default: /* assume NOP */
1512 case 2: /* NOP2 -- emulate as JMP8+0 */
1513 BUG_ON(memcmp(emulate, x86_nops[len], len));
1514 tp->opcode = JMP8_INSN_OPCODE;
1518 case 5: /* NOP5 -- emulate as JMP32+0 */
1519 BUG_ON(memcmp(emulate, x86_nops[len], len));
1520 tp->opcode = JMP32_INSN_OPCODE;
1524 default: /* unknown instruction */
1532 * We hard rely on the tp_vec being ordered; ensure this is so by flushing
1535 static bool tp_order_fail(void *addr)
1537 struct text_poke_loc *tp;
1542 if (!addr) /* force */
1545 tp = &tp_vec[tp_vec_nr - 1];
1546 if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
1552 static void text_poke_flush(void *addr)
1554 if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
1555 text_poke_bp_batch(tp_vec, tp_vec_nr);
1560 void text_poke_finish(void)
1562 text_poke_flush(NULL);
1565 void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
1567 struct text_poke_loc *tp;
1569 if (unlikely(system_state == SYSTEM_BOOTING)) {
1570 text_poke_early(addr, opcode, len);
1574 text_poke_flush(addr);
1576 tp = &tp_vec[tp_vec_nr++];
1577 text_poke_loc_init(tp, addr, opcode, len, emulate);
1581 * text_poke_bp() -- update instructions on live kernel on SMP
1582 * @addr: address to patch
1583 * @opcode: opcode of new instruction
1584 * @len: length to copy
1585 * @emulate: instruction to be emulated
1587 * Update a single instruction with the vector in the stack, avoiding
1588 * dynamically allocated memory. This function should be used when it is
1589 * not possible to allocate memory.
1591 void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
1593 struct text_poke_loc tp;
1595 if (unlikely(system_state == SYSTEM_BOOTING)) {
1596 text_poke_early(addr, opcode, len);
1600 text_poke_loc_init(&tp, addr, opcode, len, emulate);
1601 text_poke_bp_batch(&tp, 1);