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);
273 * The scan order should be from start to end. A later scanned
274 * alternative code can overwrite previously scanned alternative code.
275 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
278 * So be careful if you want to change the scan order to any other
281 for (a = start; a < end; a++) {
282 int insn_buff_sz = 0;
283 /* Mask away "NOT" flag bit for feature to test. */
284 u16 feature = a->cpuid & ~ALTINSTR_FLAG_INV;
286 instr = (u8 *)&a->instr_offset + a->instr_offset;
287 replacement = (u8 *)&a->repl_offset + a->repl_offset;
288 BUG_ON(a->instrlen > sizeof(insn_buff));
289 BUG_ON(feature >= (NCAPINTS + NBUGINTS) * 32);
293 * - feature is present
294 * - feature not present but ALTINSTR_FLAG_INV is set to mean,
295 * patch if feature is *NOT* present.
297 if (!boot_cpu_has(feature) == !(a->cpuid & ALTINSTR_FLAG_INV))
300 DPRINTK("feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)",
301 (a->cpuid & ALTINSTR_FLAG_INV) ? "!" : "",
304 instr, instr, a->instrlen,
305 replacement, a->replacementlen);
307 DUMP_BYTES(instr, a->instrlen, "%px: old_insn: ", instr);
308 DUMP_BYTES(replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
310 memcpy(insn_buff, replacement, a->replacementlen);
311 insn_buff_sz = a->replacementlen;
314 * 0xe8 is a relative jump; fix the offset.
316 * Instruction length is checked before the opcode to avoid
317 * accessing uninitialized bytes for zero-length replacements.
319 if (a->replacementlen == 5 && *insn_buff == 0xe8) {
320 *(s32 *)(insn_buff + 1) += replacement - instr;
321 DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
322 *(s32 *)(insn_buff + 1),
323 (unsigned long)instr + *(s32 *)(insn_buff + 1) + 5);
326 if (a->replacementlen && is_jmp(replacement[0]))
327 recompute_jump(a, instr, replacement, insn_buff);
329 for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
330 insn_buff[insn_buff_sz] = 0x90;
332 DUMP_BYTES(insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
334 text_poke_early(instr, insn_buff, insn_buff_sz);
337 optimize_nops(instr, a->instrlen);
341 #if defined(CONFIG_RETPOLINE) && defined(CONFIG_STACK_VALIDATION)
346 static int emit_indirect(int op, int reg, u8 *bytes)
352 case CALL_INSN_OPCODE:
353 modrm = 0x10; /* Reg = 2; CALL r/m */
356 case JMP32_INSN_OPCODE:
357 modrm = 0x20; /* Reg = 4; JMP r/m */
366 bytes[i++] = 0x41; /* REX.B prefix */
370 modrm |= 0xc0; /* Mod = 3 */
373 bytes[i++] = 0xff; /* opcode */
380 * Rewrite the compiler generated retpoline thunk calls.
382 * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
383 * indirect instructions, avoiding the extra indirection.
385 * For example, convert:
387 * CALL __x86_indirect_thunk_\reg
393 * It also tries to inline spectre_v2=retpoline,amd when size permits.
395 static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
397 retpoline_thunk_t *target;
401 target = addr + insn->length + insn->immediate.value;
402 reg = target - __x86_indirect_thunk_array;
404 if (WARN_ON_ONCE(reg & ~0xf))
407 /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
410 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
411 !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE))
414 op = insn->opcode.bytes[0];
419 * Jcc.d32 __x86_indirect_thunk_\reg
429 /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
430 if (op == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80) {
431 cc = insn->opcode.bytes[1] & 0xf;
432 cc ^= 1; /* invert condition */
434 bytes[i++] = 0x70 + cc; /* Jcc.d8 */
435 bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
437 /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
438 op = JMP32_INSN_OPCODE;
442 * For RETPOLINE_AMD: prepend the indirect CALL/JMP with an LFENCE.
444 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
447 bytes[i++] = 0xe8; /* LFENCE */
450 ret = emit_indirect(op, reg, bytes + i);
455 for (; i < insn->length;)
456 bytes[i++] = BYTES_NOP1;
462 * Generated by 'objtool --retpoline'.
464 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
468 for (s = start; s < end; s++) {
469 void *addr = (void *)s + *s;
475 ret = insn_decode_kernel(&insn, addr);
476 if (WARN_ON_ONCE(ret < 0))
479 op1 = insn.opcode.bytes[0];
480 op2 = insn.opcode.bytes[1];
483 case CALL_INSN_OPCODE:
484 case JMP32_INSN_OPCODE:
487 case 0x0f: /* escape */
488 if (op2 >= 0x80 && op2 <= 0x8f)
496 DPRINTK("retpoline at: %pS (%px) len: %d to: %pS",
497 addr, addr, insn.length,
498 addr + insn.length + insn.immediate.value);
500 len = patch_retpoline(addr, &insn, bytes);
501 if (len == insn.length) {
502 optimize_nops(bytes, len);
503 DUMP_BYTES(((u8*)addr), len, "%px: orig: ", addr);
504 DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
505 text_poke_early(addr, bytes, len);
510 #ifdef CONFIG_RETHUNK
512 * Rewrite the compiler generated return thunk tail-calls.
514 * For example, convert:
516 * JMP __x86_return_thunk
522 static int patch_return(void *addr, struct insn *insn, u8 *bytes)
526 if (cpu_feature_enabled(X86_FEATURE_RETHUNK))
529 bytes[i++] = RET_INSN_OPCODE;
531 for (; i < insn->length;)
532 bytes[i++] = INT3_INSN_OPCODE;
537 void __init_or_module noinline apply_returns(s32 *start, s32 *end)
541 for (s = start; s < end; s++) {
542 void *dest = NULL, *addr = (void *)s + *s;
548 ret = insn_decode_kernel(&insn, addr);
549 if (WARN_ON_ONCE(ret < 0))
552 op = insn.opcode.bytes[0];
553 if (op == JMP32_INSN_OPCODE)
554 dest = addr + insn.length + insn.immediate.value;
556 if (__static_call_fixup(addr, op, dest) ||
557 WARN_ONCE(dest != &__x86_return_thunk,
558 "missing return thunk: %pS-%pS: %*ph",
559 addr, dest, 5, addr))
562 DPRINTK("return thunk at: %pS (%px) len: %d to: %pS",
563 addr, addr, insn.length,
564 addr + insn.length + insn.immediate.value);
566 len = patch_return(addr, &insn, bytes);
567 if (len == insn.length) {
568 DUMP_BYTES(((u8*)addr), len, "%px: orig: ", addr);
569 DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
570 text_poke_early(addr, bytes, len);
575 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
576 #endif /* CONFIG_RETHUNK */
578 #else /* !RETPOLINES || !CONFIG_STACK_VALIDATION */
580 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
581 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
583 #endif /* CONFIG_RETPOLINE && CONFIG_STACK_VALIDATION */
586 static void alternatives_smp_lock(const s32 *start, const s32 *end,
587 u8 *text, u8 *text_end)
591 for (poff = start; poff < end; poff++) {
592 u8 *ptr = (u8 *)poff + *poff;
594 if (!*poff || ptr < text || ptr >= text_end)
596 /* turn DS segment override prefix into lock prefix */
598 text_poke(ptr, ((unsigned char []){0xf0}), 1);
602 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
603 u8 *text, u8 *text_end)
607 for (poff = start; poff < end; poff++) {
608 u8 *ptr = (u8 *)poff + *poff;
610 if (!*poff || ptr < text || ptr >= text_end)
612 /* turn lock prefix into DS segment override prefix */
614 text_poke(ptr, ((unsigned char []){0x3E}), 1);
618 struct smp_alt_module {
619 /* what is this ??? */
623 /* ptrs to lock prefixes */
625 const s32 *locks_end;
627 /* .text segment, needed to avoid patching init code ;) */
631 struct list_head next;
633 static LIST_HEAD(smp_alt_modules);
634 static bool uniproc_patched = false; /* protected by text_mutex */
636 void __init_or_module alternatives_smp_module_add(struct module *mod,
638 void *locks, void *locks_end,
639 void *text, void *text_end)
641 struct smp_alt_module *smp;
643 mutex_lock(&text_mutex);
644 if (!uniproc_patched)
647 if (num_possible_cpus() == 1)
648 /* Don't bother remembering, we'll never have to undo it. */
651 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
653 /* we'll run the (safe but slow) SMP code then ... */
659 smp->locks_end = locks_end;
661 smp->text_end = text_end;
662 DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
663 smp->locks, smp->locks_end,
664 smp->text, smp->text_end, smp->name);
666 list_add_tail(&smp->next, &smp_alt_modules);
668 alternatives_smp_unlock(locks, locks_end, text, text_end);
670 mutex_unlock(&text_mutex);
673 void __init_or_module alternatives_smp_module_del(struct module *mod)
675 struct smp_alt_module *item;
677 mutex_lock(&text_mutex);
678 list_for_each_entry(item, &smp_alt_modules, next) {
679 if (mod != item->mod)
681 list_del(&item->next);
685 mutex_unlock(&text_mutex);
688 void alternatives_enable_smp(void)
690 struct smp_alt_module *mod;
692 /* Why bother if there are no other CPUs? */
693 BUG_ON(num_possible_cpus() == 1);
695 mutex_lock(&text_mutex);
697 if (uniproc_patched) {
698 pr_info("switching to SMP code\n");
699 BUG_ON(num_online_cpus() != 1);
700 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
701 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
702 list_for_each_entry(mod, &smp_alt_modules, next)
703 alternatives_smp_lock(mod->locks, mod->locks_end,
704 mod->text, mod->text_end);
705 uniproc_patched = false;
707 mutex_unlock(&text_mutex);
711 * Return 1 if the address range is reserved for SMP-alternatives.
712 * Must hold text_mutex.
714 int alternatives_text_reserved(void *start, void *end)
716 struct smp_alt_module *mod;
718 u8 *text_start = start;
721 lockdep_assert_held(&text_mutex);
723 list_for_each_entry(mod, &smp_alt_modules, next) {
724 if (mod->text > text_end || mod->text_end < text_start)
726 for (poff = mod->locks; poff < mod->locks_end; poff++) {
727 const u8 *ptr = (const u8 *)poff + *poff;
729 if (text_start <= ptr && text_end > ptr)
736 #endif /* CONFIG_SMP */
738 #ifdef CONFIG_PARAVIRT
739 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
740 struct paravirt_patch_site *end)
742 struct paravirt_patch_site *p;
743 char insn_buff[MAX_PATCH_LEN];
745 for (p = start; p < end; p++) {
748 BUG_ON(p->len > MAX_PATCH_LEN);
749 /* prep the buffer with the original instructions */
750 memcpy(insn_buff, p->instr, p->len);
751 used = paravirt_patch(p->type, insn_buff, (unsigned long)p->instr, p->len);
753 BUG_ON(used > p->len);
755 /* Pad the rest with nops */
756 add_nops(insn_buff + used, p->len - used);
757 text_poke_early(p->instr, insn_buff, p->len);
760 extern struct paravirt_patch_site __start_parainstructions[],
761 __stop_parainstructions[];
762 #endif /* CONFIG_PARAVIRT */
765 * Self-test for the INT3 based CALL emulation code.
767 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
768 * properly and that there is a stack gap between the INT3 frame and the
769 * previous context. Without this gap doing a virtual PUSH on the interrupted
770 * stack would corrupt the INT3 IRET frame.
772 * See entry_{32,64}.S for more details.
776 * We define the int3_magic() function in assembly to control the calling
777 * convention such that we can 'call' it from assembly.
780 extern void int3_magic(unsigned int *ptr); /* defined in asm */
783 " .pushsection .init.text, \"ax\", @progbits\n"
784 " .type int3_magic, @function\n"
786 " movl $1, (%" _ASM_ARG1 ")\n"
788 " .size int3_magic, .-int3_magic\n"
792 extern __initdata unsigned long int3_selftest_ip; /* defined in asm below */
795 int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
797 struct die_args *args = data;
798 struct pt_regs *regs = args->regs;
800 if (!regs || user_mode(regs))
806 if (regs->ip - INT3_INSN_SIZE != int3_selftest_ip)
809 int3_emulate_call(regs, (unsigned long)&int3_magic);
813 static void __init int3_selftest(void)
815 static __initdata struct notifier_block int3_exception_nb = {
816 .notifier_call = int3_exception_notify,
817 .priority = INT_MAX-1, /* last */
819 unsigned int val = 0;
821 BUG_ON(register_die_notifier(&int3_exception_nb));
824 * Basically: int3_magic(&val); but really complicated :-)
826 * Stick the address of the INT3 instruction into int3_selftest_ip,
827 * then trigger the INT3, padded with NOPs to match a CALL instruction
830 asm volatile ("1: int3; nop; nop; nop; nop\n\t"
831 ".pushsection .init.data,\"aw\"\n\t"
832 ".align " __ASM_SEL(4, 8) "\n\t"
833 ".type int3_selftest_ip, @object\n\t"
834 ".size int3_selftest_ip, " __ASM_SEL(4, 8) "\n\t"
835 "int3_selftest_ip:\n\t"
836 __ASM_SEL(.long, .quad) " 1b\n\t"
838 : ASM_CALL_CONSTRAINT
839 : __ASM_SEL_RAW(a, D) (&val)
844 unregister_die_notifier(&int3_exception_nb);
847 void __init alternative_instructions(void)
852 * The patching is not fully atomic, so try to avoid local
853 * interruptions that might execute the to be patched code.
854 * Other CPUs are not running.
859 * Don't stop machine check exceptions while patching.
860 * MCEs only happen when something got corrupted and in this
861 * case we must do something about the corruption.
862 * Ignoring it is worse than an unlikely patching race.
863 * Also machine checks tend to be broadcast and if one CPU
864 * goes into machine check the others follow quickly, so we don't
865 * expect a machine check to cause undue problems during to code
870 * Paravirt patching and alternative patching can be combined to
871 * replace a function call with a short direct code sequence (e.g.
872 * by setting a constant return value instead of doing that in an
873 * external function).
874 * In order to make this work the following sequence is required:
875 * 1. set (artificial) features depending on used paravirt
876 * functions which can later influence alternative patching
877 * 2. apply paravirt patching (generally replacing an indirect
878 * function call with a direct one)
879 * 3. apply alternative patching (e.g. replacing a direct function
880 * call with a custom code sequence)
881 * Doing paravirt patching after alternative patching would clobber
882 * the optimization of the custom code with a function call again.
887 * First patch paravirt functions, such that we overwrite the indirect
888 * call with the direct call.
890 apply_paravirt(__parainstructions, __parainstructions_end);
893 * Rewrite the retpolines, must be done before alternatives since
894 * those can rewrite the retpoline thunks.
896 apply_retpolines(__retpoline_sites, __retpoline_sites_end);
897 apply_returns(__return_sites, __return_sites_end);
900 * Then patch alternatives, such that those paravirt calls that are in
901 * alternatives can be overwritten by their immediate fragments.
903 apply_alternatives(__alt_instructions, __alt_instructions_end);
906 /* Patch to UP if other cpus not imminent. */
907 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
908 uniproc_patched = true;
909 alternatives_smp_module_add(NULL, "core kernel",
910 __smp_locks, __smp_locks_end,
914 if (!uniproc_patched || num_possible_cpus() == 1) {
915 free_init_pages("SMP alternatives",
916 (unsigned long)__smp_locks,
917 (unsigned long)__smp_locks_end);
922 alternatives_patched = 1;
926 * text_poke_early - Update instructions on a live kernel at boot time
927 * @addr: address to modify
928 * @opcode: source of the copy
929 * @len: length to copy
931 * When you use this code to patch more than one byte of an instruction
932 * you need to make sure that other CPUs cannot execute this code in parallel.
933 * Also no thread must be currently preempted in the middle of these
934 * instructions. And on the local CPU you need to be protected against NMI or
935 * MCE handlers seeing an inconsistent instruction while you patch.
937 void __init_or_module text_poke_early(void *addr, const void *opcode,
942 if (boot_cpu_has(X86_FEATURE_NX) &&
943 is_module_text_address((unsigned long)addr)) {
945 * Modules text is marked initially as non-executable, so the
946 * code cannot be running and speculative code-fetches are
947 * prevented. Just change the code.
949 memcpy(addr, opcode, len);
951 local_irq_save(flags);
952 memcpy(addr, opcode, len);
953 local_irq_restore(flags);
957 * Could also do a CLFLUSH here to speed up CPU recovery; but
958 * that causes hangs on some VIA CPUs.
964 struct mm_struct *mm;
968 * Using a temporary mm allows to set temporary mappings that are not accessible
969 * by other CPUs. Such mappings are needed to perform sensitive memory writes
970 * that override the kernel memory protections (e.g., W^X), without exposing the
971 * temporary page-table mappings that are required for these write operations to
972 * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
973 * mapping is torn down.
975 * Context: The temporary mm needs to be used exclusively by a single core. To
976 * harden security IRQs must be disabled while the temporary mm is
977 * loaded, thereby preventing interrupt handler bugs from overriding
978 * the kernel memory protection.
980 static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
982 temp_mm_state_t temp_state;
984 lockdep_assert_irqs_disabled();
987 * Make sure not to be in TLB lazy mode, as otherwise we'll end up
988 * with a stale address space WITHOUT being in lazy mode after
989 * restoring the previous mm.
991 if (this_cpu_read(cpu_tlbstate_shared.is_lazy))
992 leave_mm(smp_processor_id());
994 temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
995 switch_mm_irqs_off(NULL, mm, current);
998 * If breakpoints are enabled, disable them while the temporary mm is
999 * used. Userspace might set up watchpoints on addresses that are used
1000 * in the temporary mm, which would lead to wrong signals being sent or
1003 * Note that breakpoints are not disabled selectively, which also causes
1004 * kernel breakpoints (e.g., perf's) to be disabled. This might be
1005 * undesirable, but still seems reasonable as the code that runs in the
1006 * temporary mm should be short.
1008 if (hw_breakpoint_active())
1009 hw_breakpoint_disable();
1014 static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
1016 lockdep_assert_irqs_disabled();
1017 switch_mm_irqs_off(NULL, prev_state.mm, current);
1020 * Restore the breakpoints if they were disabled before the temporary mm
1023 if (hw_breakpoint_active())
1024 hw_breakpoint_restore();
1027 __ro_after_init struct mm_struct *poking_mm;
1028 __ro_after_init unsigned long poking_addr;
1030 static void *__text_poke(void *addr, const void *opcode, size_t len)
1032 bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
1033 struct page *pages[2] = {NULL};
1034 temp_mm_state_t prev;
1035 unsigned long flags;
1041 * While boot memory allocator is running we cannot use struct pages as
1042 * they are not yet initialized. There is no way to recover.
1044 BUG_ON(!after_bootmem);
1046 if (!core_kernel_text((unsigned long)addr)) {
1047 pages[0] = vmalloc_to_page(addr);
1048 if (cross_page_boundary)
1049 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
1051 pages[0] = virt_to_page(addr);
1052 WARN_ON(!PageReserved(pages[0]));
1053 if (cross_page_boundary)
1054 pages[1] = virt_to_page(addr + PAGE_SIZE);
1057 * If something went wrong, crash and burn since recovery paths are not
1060 BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
1063 * Map the page without the global bit, as TLB flushing is done with
1064 * flush_tlb_mm_range(), which is intended for non-global PTEs.
1066 pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
1069 * The lock is not really needed, but this allows to avoid open-coding.
1071 ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
1074 * This must not fail; preallocated in poking_init().
1078 local_irq_save(flags);
1080 pte = mk_pte(pages[0], pgprot);
1081 set_pte_at(poking_mm, poking_addr, ptep, pte);
1083 if (cross_page_boundary) {
1084 pte = mk_pte(pages[1], pgprot);
1085 set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
1089 * Loading the temporary mm behaves as a compiler barrier, which
1090 * guarantees that the PTE will be set at the time memcpy() is done.
1092 prev = use_temporary_mm(poking_mm);
1094 kasan_disable_current();
1095 memcpy((u8 *)poking_addr + offset_in_page(addr), opcode, len);
1096 kasan_enable_current();
1099 * Ensure that the PTE is only cleared after the instructions of memcpy
1100 * were issued by using a compiler barrier.
1104 pte_clear(poking_mm, poking_addr, ptep);
1105 if (cross_page_boundary)
1106 pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
1109 * Loading the previous page-table hierarchy requires a serializing
1110 * instruction that already allows the core to see the updated version.
1111 * Xen-PV is assumed to serialize execution in a similar manner.
1113 unuse_temporary_mm(prev);
1116 * Flushing the TLB might involve IPIs, which would require enabled
1117 * IRQs, but not if the mm is not used, as it is in this point.
1119 flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
1120 (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
1124 * If the text does not match what we just wrote then something is
1125 * fundamentally screwy; there's nothing we can really do about that.
1127 BUG_ON(memcmp(addr, opcode, len));
1129 local_irq_restore(flags);
1130 pte_unmap_unlock(ptep, ptl);
1135 * text_poke - Update instructions on a live kernel
1136 * @addr: address to modify
1137 * @opcode: source of the copy
1138 * @len: length to copy
1140 * Only atomic text poke/set should be allowed when not doing early patching.
1141 * It means the size must be writable atomically and the address must be aligned
1142 * in a way that permits an atomic write. It also makes sure we fit on a single
1145 * Note that the caller must ensure that if the modified code is part of a
1146 * module, the module would not be removed during poking. This can be achieved
1147 * by registering a module notifier, and ordering module removal and patching
1150 void *text_poke(void *addr, const void *opcode, size_t len)
1152 lockdep_assert_held(&text_mutex);
1154 return __text_poke(addr, opcode, len);
1158 * text_poke_kgdb - Update instructions on a live kernel by kgdb
1159 * @addr: address to modify
1160 * @opcode: source of the copy
1161 * @len: length to copy
1163 * Only atomic text poke/set should be allowed when not doing early patching.
1164 * It means the size must be writable atomically and the address must be aligned
1165 * in a way that permits an atomic write. It also makes sure we fit on a single
1168 * Context: should only be used by kgdb, which ensures no other core is running,
1169 * despite the fact it does not hold the text_mutex.
1171 void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
1173 return __text_poke(addr, opcode, len);
1176 static void do_sync_core(void *info)
1181 void text_poke_sync(void)
1183 on_each_cpu(do_sync_core, NULL, 1);
1186 struct text_poke_loc {
1187 /* addr := _stext + rel_addr */
1192 const u8 text[POKE_MAX_OPCODE_SIZE];
1193 /* see text_poke_bp_batch() */
1197 struct bp_patching_desc {
1198 struct text_poke_loc *vec;
1203 static struct bp_patching_desc *bp_desc;
1205 static __always_inline
1206 struct bp_patching_desc *try_get_desc(struct bp_patching_desc **descp)
1208 /* rcu_dereference */
1209 struct bp_patching_desc *desc = __READ_ONCE(*descp);
1211 if (!desc || !arch_atomic_inc_not_zero(&desc->refs))
1217 static __always_inline void put_desc(struct bp_patching_desc *desc)
1219 smp_mb__before_atomic();
1220 arch_atomic_dec(&desc->refs);
1223 static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
1225 return _stext + tp->rel_addr;
1228 static __always_inline int patch_cmp(const void *key, const void *elt)
1230 struct text_poke_loc *tp = (struct text_poke_loc *) elt;
1232 if (key < text_poke_addr(tp))
1234 if (key > text_poke_addr(tp))
1239 noinstr int poke_int3_handler(struct pt_regs *regs)
1241 struct bp_patching_desc *desc;
1242 struct text_poke_loc *tp;
1246 if (user_mode(regs))
1250 * Having observed our INT3 instruction, we now must observe
1253 * bp_desc = desc INT3
1255 * write INT3 if (desc)
1259 desc = try_get_desc(&bp_desc);
1264 * Discount the INT3. See text_poke_bp_batch().
1266 ip = (void *) regs->ip - INT3_INSN_SIZE;
1269 * Skip the binary search if there is a single member in the vector.
1271 if (unlikely(desc->nr_entries > 1)) {
1272 tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
1273 sizeof(struct text_poke_loc),
1279 if (text_poke_addr(tp) != ip)
1285 switch (tp->opcode) {
1286 case INT3_INSN_OPCODE:
1288 * Someone poked an explicit INT3, they'll want to handle it,
1293 case RET_INSN_OPCODE:
1294 int3_emulate_ret(regs);
1297 case CALL_INSN_OPCODE:
1298 int3_emulate_call(regs, (long)ip + tp->disp);
1301 case JMP32_INSN_OPCODE:
1302 case JMP8_INSN_OPCODE:
1303 int3_emulate_jmp(regs, (long)ip + tp->disp);
1317 #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
1318 static struct text_poke_loc tp_vec[TP_VEC_MAX];
1319 static int tp_vec_nr;
1322 * text_poke_bp_batch() -- update instructions on live kernel on SMP
1323 * @tp: vector of instructions to patch
1324 * @nr_entries: number of entries in the vector
1326 * Modify multi-byte instruction by using int3 breakpoint on SMP.
1327 * We completely avoid stop_machine() here, and achieve the
1328 * synchronization using int3 breakpoint.
1330 * The way it is done:
1331 * - For each entry in the vector:
1332 * - add a int3 trap to the address that will be patched
1334 * - For each entry in the vector:
1335 * - update all but the first byte of the patched range
1337 * - For each entry in the vector:
1338 * - replace the first byte (int3) by the first byte of
1342 static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
1344 struct bp_patching_desc desc = {
1346 .nr_entries = nr_entries,
1347 .refs = ATOMIC_INIT(1),
1349 unsigned char int3 = INT3_INSN_OPCODE;
1353 lockdep_assert_held(&text_mutex);
1355 smp_store_release(&bp_desc, &desc); /* rcu_assign_pointer */
1358 * Corresponding read barrier in int3 notifier for making sure the
1359 * nr_entries and handler are correctly ordered wrt. patching.
1364 * First step: add a int3 trap to the address that will be patched.
1366 for (i = 0; i < nr_entries; i++) {
1367 tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
1368 text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
1374 * Second step: update all but the first byte of the patched range.
1376 for (do_sync = 0, i = 0; i < nr_entries; i++) {
1377 u8 old[POKE_MAX_OPCODE_SIZE] = { tp[i].old, };
1378 int len = tp[i].len;
1380 if (len - INT3_INSN_SIZE > 0) {
1381 memcpy(old + INT3_INSN_SIZE,
1382 text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1383 len - INT3_INSN_SIZE);
1384 text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1385 (const char *)tp[i].text + INT3_INSN_SIZE,
1386 len - INT3_INSN_SIZE);
1391 * Emit a perf event to record the text poke, primarily to
1392 * support Intel PT decoding which must walk the executable code
1393 * to reconstruct the trace. The flow up to here is:
1396 * - write instruction tail
1397 * At this point the actual control flow will be through the
1398 * INT3 and handler and not hit the old or new instruction.
1399 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
1400 * can still be decoded. Subsequently:
1401 * - emit RECORD_TEXT_POKE with the new instruction
1403 * - write first byte
1405 * So before the text poke event timestamp, the decoder will see
1406 * either the old instruction flow or FUP/TIP of INT3. After the
1407 * text poke event timestamp, the decoder will see either the
1408 * new instruction flow or FUP/TIP of INT3. Thus decoders can
1409 * use the timestamp as the point at which to modify the
1411 * The old instruction is recorded so that the event can be
1412 * processed forwards or backwards.
1414 perf_event_text_poke(text_poke_addr(&tp[i]), old, len,
1420 * According to Intel, this core syncing is very likely
1421 * not necessary and we'd be safe even without it. But
1422 * better safe than sorry (plus there's not only Intel).
1428 * Third step: replace the first byte (int3) by the first byte of
1431 for (do_sync = 0, i = 0; i < nr_entries; i++) {
1432 if (tp[i].text[0] == INT3_INSN_OPCODE)
1435 text_poke(text_poke_addr(&tp[i]), tp[i].text, INT3_INSN_SIZE);
1443 * Remove and synchronize_rcu(), except we have a very primitive
1444 * refcount based completion.
1446 WRITE_ONCE(bp_desc, NULL); /* RCU_INIT_POINTER */
1447 if (!atomic_dec_and_test(&desc.refs))
1448 atomic_cond_read_acquire(&desc.refs, !VAL);
1451 static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
1452 const void *opcode, size_t len, const void *emulate)
1457 memcpy((void *)tp->text, opcode, len);
1461 ret = insn_decode_kernel(&insn, emulate);
1464 tp->rel_addr = addr - (void *)_stext;
1466 tp->opcode = insn.opcode.bytes[0];
1468 switch (tp->opcode) {
1469 case RET_INSN_OPCODE:
1470 case JMP32_INSN_OPCODE:
1471 case JMP8_INSN_OPCODE:
1473 * Control flow instructions without implied execution of the
1474 * next instruction can be padded with INT3.
1476 for (i = insn.length; i < len; i++)
1477 BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
1481 BUG_ON(len != insn.length);
1485 switch (tp->opcode) {
1486 case INT3_INSN_OPCODE:
1487 case RET_INSN_OPCODE:
1490 case CALL_INSN_OPCODE:
1491 case JMP32_INSN_OPCODE:
1492 case JMP8_INSN_OPCODE:
1493 tp->disp = insn.immediate.value;
1496 default: /* assume NOP */
1498 case 2: /* NOP2 -- emulate as JMP8+0 */
1499 BUG_ON(memcmp(emulate, x86_nops[len], len));
1500 tp->opcode = JMP8_INSN_OPCODE;
1504 case 5: /* NOP5 -- emulate as JMP32+0 */
1505 BUG_ON(memcmp(emulate, x86_nops[len], len));
1506 tp->opcode = JMP32_INSN_OPCODE;
1510 default: /* unknown instruction */
1518 * We hard rely on the tp_vec being ordered; ensure this is so by flushing
1521 static bool tp_order_fail(void *addr)
1523 struct text_poke_loc *tp;
1528 if (!addr) /* force */
1531 tp = &tp_vec[tp_vec_nr - 1];
1532 if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
1538 static void text_poke_flush(void *addr)
1540 if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
1541 text_poke_bp_batch(tp_vec, tp_vec_nr);
1546 void text_poke_finish(void)
1548 text_poke_flush(NULL);
1551 void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
1553 struct text_poke_loc *tp;
1555 if (unlikely(system_state == SYSTEM_BOOTING)) {
1556 text_poke_early(addr, opcode, len);
1560 text_poke_flush(addr);
1562 tp = &tp_vec[tp_vec_nr++];
1563 text_poke_loc_init(tp, addr, opcode, len, emulate);
1567 * text_poke_bp() -- update instructions on live kernel on SMP
1568 * @addr: address to patch
1569 * @opcode: opcode of new instruction
1570 * @len: length to copy
1571 * @emulate: instruction to be emulated
1573 * Update a single instruction with the vector in the stack, avoiding
1574 * dynamically allocated memory. This function should be used when it is
1575 * not possible to allocate memory.
1577 void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
1579 struct text_poke_loc tp;
1581 if (unlikely(system_state == SYSTEM_BOOTING)) {
1582 text_poke_early(addr, opcode, len);
1586 text_poke_loc_init(&tp, addr, opcode, len, emulate);
1587 text_poke_bp_batch(&tp, 1);