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 struct alt_instr __alt_instructions[], __alt_instructions_end[];
119 extern s32 __smp_locks[], __smp_locks_end[];
120 void text_poke_early(void *addr, const void *opcode, size_t len);
123 * Are we looking at a near JMP with a 1 or 4-byte displacement.
125 static inline bool is_jmp(const u8 opcode)
127 return opcode == 0xeb || opcode == 0xe9;
130 static void __init_or_module
131 recompute_jump(struct alt_instr *a, u8 *orig_insn, u8 *repl_insn, u8 *insn_buff)
133 u8 *next_rip, *tgt_rip;
137 if (a->replacementlen != 5)
140 o_dspl = *(s32 *)(insn_buff + 1);
142 /* next_rip of the replacement JMP */
143 next_rip = repl_insn + a->replacementlen;
144 /* target rip of the replacement JMP */
145 tgt_rip = next_rip + o_dspl;
146 n_dspl = tgt_rip - orig_insn;
148 DPRINTK("target RIP: %px, new_displ: 0x%x", tgt_rip, n_dspl);
150 if (tgt_rip - orig_insn >= 0) {
151 if (n_dspl - 2 <= 127)
155 /* negative offset */
157 if (((n_dspl - 2) & 0xff) == (n_dspl - 2))
167 insn_buff[1] = (s8)n_dspl;
168 add_nops(insn_buff + 2, 3);
177 *(s32 *)&insn_buff[1] = n_dspl;
183 DPRINTK("final displ: 0x%08x, JMP 0x%lx",
184 n_dspl, (unsigned long)orig_insn + n_dspl + repl_len);
188 * optimize_nops_range() - Optimize a sequence of single byte NOPs (0x90)
190 * @instr: instruction byte stream
191 * @instrlen: length of the above
192 * @off: offset within @instr where the first NOP has been detected
194 * Return: number of NOPs found (and replaced).
196 static __always_inline int optimize_nops_range(u8 *instr, u8 instrlen, int off)
201 while (i < instrlen) {
202 if (instr[i] != 0x90)
213 local_irq_save(flags);
214 add_nops(instr + off, nnops);
215 local_irq_restore(flags);
217 DUMP_BYTES(instr, instrlen, "%px: [%d:%d) optimized NOPs: ", instr, off, i);
223 * "noinline" to cause control flow change and thus invalidate I$ and
224 * cause refetch after modification.
226 static void __init_or_module noinline optimize_nops(u8 *instr, size_t len)
232 * Jump over the non-NOP insns and optimize single-byte NOPs into bigger
236 if (insn_decode_kernel(&insn, &instr[i]))
240 * See if this and any potentially following NOPs can be
243 if (insn.length == 1 && insn.opcode.bytes[0] == 0x90)
244 i += optimize_nops_range(instr, len, i);
254 * Replace instructions with better alternatives for this CPU type. This runs
255 * before SMP is initialized to avoid SMP problems with self modifying code.
256 * This implies that asymmetric systems where APs have less capabilities than
257 * the boot processor are not handled. Tough. Make sure you disable such
260 * Marked "noinline" to cause control flow change and thus insn cache
261 * to refetch changed I$ lines.
263 void __init_or_module noinline apply_alternatives(struct alt_instr *start,
264 struct alt_instr *end)
267 u8 *instr, *replacement;
268 u8 insn_buff[MAX_PATCH_LEN];
270 DPRINTK("alt table %px, -> %px", start, end);
272 * The scan order should be from start to end. A later scanned
273 * alternative code can overwrite previously scanned alternative code.
274 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
277 * So be careful if you want to change the scan order to any other
280 for (a = start; a < end; a++) {
281 int insn_buff_sz = 0;
282 /* Mask away "NOT" flag bit for feature to test. */
283 u16 feature = a->cpuid & ~ALTINSTR_FLAG_INV;
285 instr = (u8 *)&a->instr_offset + a->instr_offset;
286 replacement = (u8 *)&a->repl_offset + a->repl_offset;
287 BUG_ON(a->instrlen > sizeof(insn_buff));
288 BUG_ON(feature >= (NCAPINTS + NBUGINTS) * 32);
292 * - feature is present
293 * - feature not present but ALTINSTR_FLAG_INV is set to mean,
294 * patch if feature is *NOT* present.
296 if (!boot_cpu_has(feature) == !(a->cpuid & ALTINSTR_FLAG_INV))
299 DPRINTK("feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)",
300 (a->cpuid & ALTINSTR_FLAG_INV) ? "!" : "",
303 instr, instr, a->instrlen,
304 replacement, a->replacementlen);
306 DUMP_BYTES(instr, a->instrlen, "%px: old_insn: ", instr);
307 DUMP_BYTES(replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
309 memcpy(insn_buff, replacement, a->replacementlen);
310 insn_buff_sz = a->replacementlen;
313 * 0xe8 is a relative jump; fix the offset.
315 * Instruction length is checked before the opcode to avoid
316 * accessing uninitialized bytes for zero-length replacements.
318 if (a->replacementlen == 5 && *insn_buff == 0xe8) {
319 *(s32 *)(insn_buff + 1) += replacement - instr;
320 DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
321 *(s32 *)(insn_buff + 1),
322 (unsigned long)instr + *(s32 *)(insn_buff + 1) + 5);
325 if (a->replacementlen && is_jmp(replacement[0]))
326 recompute_jump(a, instr, replacement, insn_buff);
328 for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
329 insn_buff[insn_buff_sz] = 0x90;
331 DUMP_BYTES(insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
333 text_poke_early(instr, insn_buff, insn_buff_sz);
336 optimize_nops(instr, a->instrlen);
340 #if defined(CONFIG_RETPOLINE) && defined(CONFIG_STACK_VALIDATION)
345 static int emit_indirect(int op, int reg, u8 *bytes)
351 case CALL_INSN_OPCODE:
352 modrm = 0x10; /* Reg = 2; CALL r/m */
355 case JMP32_INSN_OPCODE:
356 modrm = 0x20; /* Reg = 4; JMP r/m */
365 bytes[i++] = 0x41; /* REX.B prefix */
369 modrm |= 0xc0; /* Mod = 3 */
372 bytes[i++] = 0xff; /* opcode */
379 * Rewrite the compiler generated retpoline thunk calls.
381 * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
382 * indirect instructions, avoiding the extra indirection.
384 * For example, convert:
386 * CALL __x86_indirect_thunk_\reg
392 * It also tries to inline spectre_v2=retpoline,amd when size permits.
394 static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
396 retpoline_thunk_t *target;
400 target = addr + insn->length + insn->immediate.value;
401 reg = target - __x86_indirect_thunk_array;
403 if (WARN_ON_ONCE(reg & ~0xf))
406 /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
409 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
410 !cpu_feature_enabled(X86_FEATURE_RETPOLINE_AMD))
413 op = insn->opcode.bytes[0];
418 * Jcc.d32 __x86_indirect_thunk_\reg
428 /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
429 if (op == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80) {
430 cc = insn->opcode.bytes[1] & 0xf;
431 cc ^= 1; /* invert condition */
433 bytes[i++] = 0x70 + cc; /* Jcc.d8 */
434 bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
436 /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
437 op = JMP32_INSN_OPCODE;
441 * For RETPOLINE_AMD: prepend the indirect CALL/JMP with an LFENCE.
443 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_AMD)) {
446 bytes[i++] = 0xe8; /* LFENCE */
449 ret = emit_indirect(op, reg, bytes + i);
454 for (; i < insn->length;)
455 bytes[i++] = BYTES_NOP1;
461 * Generated by 'objtool --retpoline'.
463 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
467 for (s = start; s < end; s++) {
468 void *addr = (void *)s + *s;
474 ret = insn_decode_kernel(&insn, addr);
475 if (WARN_ON_ONCE(ret < 0))
478 op1 = insn.opcode.bytes[0];
479 op2 = insn.opcode.bytes[1];
482 case CALL_INSN_OPCODE:
483 case JMP32_INSN_OPCODE:
486 case 0x0f: /* escape */
487 if (op2 >= 0x80 && op2 <= 0x8f)
495 DPRINTK("retpoline at: %pS (%px) len: %d to: %pS",
496 addr, addr, insn.length,
497 addr + insn.length + insn.immediate.value);
499 len = patch_retpoline(addr, &insn, bytes);
500 if (len == insn.length) {
501 optimize_nops(bytes, len);
502 DUMP_BYTES(((u8*)addr), len, "%px: orig: ", addr);
503 DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
504 text_poke_early(addr, bytes, len);
509 #else /* !RETPOLINES || !CONFIG_STACK_VALIDATION */
511 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
513 #endif /* CONFIG_RETPOLINE && CONFIG_STACK_VALIDATION */
516 static void alternatives_smp_lock(const s32 *start, const s32 *end,
517 u8 *text, u8 *text_end)
521 for (poff = start; poff < end; poff++) {
522 u8 *ptr = (u8 *)poff + *poff;
524 if (!*poff || ptr < text || ptr >= text_end)
526 /* turn DS segment override prefix into lock prefix */
528 text_poke(ptr, ((unsigned char []){0xf0}), 1);
532 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
533 u8 *text, u8 *text_end)
537 for (poff = start; poff < end; poff++) {
538 u8 *ptr = (u8 *)poff + *poff;
540 if (!*poff || ptr < text || ptr >= text_end)
542 /* turn lock prefix into DS segment override prefix */
544 text_poke(ptr, ((unsigned char []){0x3E}), 1);
548 struct smp_alt_module {
549 /* what is this ??? */
553 /* ptrs to lock prefixes */
555 const s32 *locks_end;
557 /* .text segment, needed to avoid patching init code ;) */
561 struct list_head next;
563 static LIST_HEAD(smp_alt_modules);
564 static bool uniproc_patched = false; /* protected by text_mutex */
566 void __init_or_module alternatives_smp_module_add(struct module *mod,
568 void *locks, void *locks_end,
569 void *text, void *text_end)
571 struct smp_alt_module *smp;
573 mutex_lock(&text_mutex);
574 if (!uniproc_patched)
577 if (num_possible_cpus() == 1)
578 /* Don't bother remembering, we'll never have to undo it. */
581 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
583 /* we'll run the (safe but slow) SMP code then ... */
589 smp->locks_end = locks_end;
591 smp->text_end = text_end;
592 DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
593 smp->locks, smp->locks_end,
594 smp->text, smp->text_end, smp->name);
596 list_add_tail(&smp->next, &smp_alt_modules);
598 alternatives_smp_unlock(locks, locks_end, text, text_end);
600 mutex_unlock(&text_mutex);
603 void __init_or_module alternatives_smp_module_del(struct module *mod)
605 struct smp_alt_module *item;
607 mutex_lock(&text_mutex);
608 list_for_each_entry(item, &smp_alt_modules, next) {
609 if (mod != item->mod)
611 list_del(&item->next);
615 mutex_unlock(&text_mutex);
618 void alternatives_enable_smp(void)
620 struct smp_alt_module *mod;
622 /* Why bother if there are no other CPUs? */
623 BUG_ON(num_possible_cpus() == 1);
625 mutex_lock(&text_mutex);
627 if (uniproc_patched) {
628 pr_info("switching to SMP code\n");
629 BUG_ON(num_online_cpus() != 1);
630 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
631 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
632 list_for_each_entry(mod, &smp_alt_modules, next)
633 alternatives_smp_lock(mod->locks, mod->locks_end,
634 mod->text, mod->text_end);
635 uniproc_patched = false;
637 mutex_unlock(&text_mutex);
641 * Return 1 if the address range is reserved for SMP-alternatives.
642 * Must hold text_mutex.
644 int alternatives_text_reserved(void *start, void *end)
646 struct smp_alt_module *mod;
648 u8 *text_start = start;
651 lockdep_assert_held(&text_mutex);
653 list_for_each_entry(mod, &smp_alt_modules, next) {
654 if (mod->text > text_end || mod->text_end < text_start)
656 for (poff = mod->locks; poff < mod->locks_end; poff++) {
657 const u8 *ptr = (const u8 *)poff + *poff;
659 if (text_start <= ptr && text_end > ptr)
666 #endif /* CONFIG_SMP */
668 #ifdef CONFIG_PARAVIRT
669 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
670 struct paravirt_patch_site *end)
672 struct paravirt_patch_site *p;
673 char insn_buff[MAX_PATCH_LEN];
675 for (p = start; p < end; p++) {
678 BUG_ON(p->len > MAX_PATCH_LEN);
679 /* prep the buffer with the original instructions */
680 memcpy(insn_buff, p->instr, p->len);
681 used = paravirt_patch(p->type, insn_buff, (unsigned long)p->instr, p->len);
683 BUG_ON(used > p->len);
685 /* Pad the rest with nops */
686 add_nops(insn_buff + used, p->len - used);
687 text_poke_early(p->instr, insn_buff, p->len);
690 extern struct paravirt_patch_site __start_parainstructions[],
691 __stop_parainstructions[];
692 #endif /* CONFIG_PARAVIRT */
695 * Self-test for the INT3 based CALL emulation code.
697 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
698 * properly and that there is a stack gap between the INT3 frame and the
699 * previous context. Without this gap doing a virtual PUSH on the interrupted
700 * stack would corrupt the INT3 IRET frame.
702 * See entry_{32,64}.S for more details.
706 * We define the int3_magic() function in assembly to control the calling
707 * convention such that we can 'call' it from assembly.
710 extern void int3_magic(unsigned int *ptr); /* defined in asm */
713 " .pushsection .init.text, \"ax\", @progbits\n"
714 " .type int3_magic, @function\n"
716 " movl $1, (%" _ASM_ARG1 ")\n"
718 " .size int3_magic, .-int3_magic\n"
722 extern __initdata unsigned long int3_selftest_ip; /* defined in asm below */
725 int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
727 struct die_args *args = data;
728 struct pt_regs *regs = args->regs;
730 if (!regs || user_mode(regs))
736 if (regs->ip - INT3_INSN_SIZE != int3_selftest_ip)
739 int3_emulate_call(regs, (unsigned long)&int3_magic);
743 static void __init int3_selftest(void)
745 static __initdata struct notifier_block int3_exception_nb = {
746 .notifier_call = int3_exception_notify,
747 .priority = INT_MAX-1, /* last */
749 unsigned int val = 0;
751 BUG_ON(register_die_notifier(&int3_exception_nb));
754 * Basically: int3_magic(&val); but really complicated :-)
756 * Stick the address of the INT3 instruction into int3_selftest_ip,
757 * then trigger the INT3, padded with NOPs to match a CALL instruction
760 asm volatile ("1: int3; nop; nop; nop; nop\n\t"
761 ".pushsection .init.data,\"aw\"\n\t"
762 ".align " __ASM_SEL(4, 8) "\n\t"
763 ".type int3_selftest_ip, @object\n\t"
764 ".size int3_selftest_ip, " __ASM_SEL(4, 8) "\n\t"
765 "int3_selftest_ip:\n\t"
766 __ASM_SEL(.long, .quad) " 1b\n\t"
768 : ASM_CALL_CONSTRAINT
769 : __ASM_SEL_RAW(a, D) (&val)
774 unregister_die_notifier(&int3_exception_nb);
777 void __init alternative_instructions(void)
782 * The patching is not fully atomic, so try to avoid local
783 * interruptions that might execute the to be patched code.
784 * Other CPUs are not running.
789 * Don't stop machine check exceptions while patching.
790 * MCEs only happen when something got corrupted and in this
791 * case we must do something about the corruption.
792 * Ignoring it is worse than an unlikely patching race.
793 * Also machine checks tend to be broadcast and if one CPU
794 * goes into machine check the others follow quickly, so we don't
795 * expect a machine check to cause undue problems during to code
800 * Paravirt patching and alternative patching can be combined to
801 * replace a function call with a short direct code sequence (e.g.
802 * by setting a constant return value instead of doing that in an
803 * external function).
804 * In order to make this work the following sequence is required:
805 * 1. set (artificial) features depending on used paravirt
806 * functions which can later influence alternative patching
807 * 2. apply paravirt patching (generally replacing an indirect
808 * function call with a direct one)
809 * 3. apply alternative patching (e.g. replacing a direct function
810 * call with a custom code sequence)
811 * Doing paravirt patching after alternative patching would clobber
812 * the optimization of the custom code with a function call again.
817 * First patch paravirt functions, such that we overwrite the indirect
818 * call with the direct call.
820 apply_paravirt(__parainstructions, __parainstructions_end);
823 * Rewrite the retpolines, must be done before alternatives since
824 * those can rewrite the retpoline thunks.
826 apply_retpolines(__retpoline_sites, __retpoline_sites_end);
829 * Then patch alternatives, such that those paravirt calls that are in
830 * alternatives can be overwritten by their immediate fragments.
832 apply_alternatives(__alt_instructions, __alt_instructions_end);
835 /* Patch to UP if other cpus not imminent. */
836 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
837 uniproc_patched = true;
838 alternatives_smp_module_add(NULL, "core kernel",
839 __smp_locks, __smp_locks_end,
843 if (!uniproc_patched || num_possible_cpus() == 1) {
844 free_init_pages("SMP alternatives",
845 (unsigned long)__smp_locks,
846 (unsigned long)__smp_locks_end);
851 alternatives_patched = 1;
855 * text_poke_early - Update instructions on a live kernel at boot time
856 * @addr: address to modify
857 * @opcode: source of the copy
858 * @len: length to copy
860 * When you use this code to patch more than one byte of an instruction
861 * you need to make sure that other CPUs cannot execute this code in parallel.
862 * Also no thread must be currently preempted in the middle of these
863 * instructions. And on the local CPU you need to be protected against NMI or
864 * MCE handlers seeing an inconsistent instruction while you patch.
866 void __init_or_module text_poke_early(void *addr, const void *opcode,
871 if (boot_cpu_has(X86_FEATURE_NX) &&
872 is_module_text_address((unsigned long)addr)) {
874 * Modules text is marked initially as non-executable, so the
875 * code cannot be running and speculative code-fetches are
876 * prevented. Just change the code.
878 memcpy(addr, opcode, len);
880 local_irq_save(flags);
881 memcpy(addr, opcode, len);
882 local_irq_restore(flags);
886 * Could also do a CLFLUSH here to speed up CPU recovery; but
887 * that causes hangs on some VIA CPUs.
893 struct mm_struct *mm;
897 * Using a temporary mm allows to set temporary mappings that are not accessible
898 * by other CPUs. Such mappings are needed to perform sensitive memory writes
899 * that override the kernel memory protections (e.g., W^X), without exposing the
900 * temporary page-table mappings that are required for these write operations to
901 * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
902 * mapping is torn down.
904 * Context: The temporary mm needs to be used exclusively by a single core. To
905 * harden security IRQs must be disabled while the temporary mm is
906 * loaded, thereby preventing interrupt handler bugs from overriding
907 * the kernel memory protection.
909 static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
911 temp_mm_state_t temp_state;
913 lockdep_assert_irqs_disabled();
916 * Make sure not to be in TLB lazy mode, as otherwise we'll end up
917 * with a stale address space WITHOUT being in lazy mode after
918 * restoring the previous mm.
920 if (this_cpu_read(cpu_tlbstate_shared.is_lazy))
921 leave_mm(smp_processor_id());
923 temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
924 switch_mm_irqs_off(NULL, mm, current);
927 * If breakpoints are enabled, disable them while the temporary mm is
928 * used. Userspace might set up watchpoints on addresses that are used
929 * in the temporary mm, which would lead to wrong signals being sent or
932 * Note that breakpoints are not disabled selectively, which also causes
933 * kernel breakpoints (e.g., perf's) to be disabled. This might be
934 * undesirable, but still seems reasonable as the code that runs in the
935 * temporary mm should be short.
937 if (hw_breakpoint_active())
938 hw_breakpoint_disable();
943 static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
945 lockdep_assert_irqs_disabled();
946 switch_mm_irqs_off(NULL, prev_state.mm, current);
949 * Restore the breakpoints if they were disabled before the temporary mm
952 if (hw_breakpoint_active())
953 hw_breakpoint_restore();
956 __ro_after_init struct mm_struct *poking_mm;
957 __ro_after_init unsigned long poking_addr;
959 static void *__text_poke(void *addr, const void *opcode, size_t len)
961 bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
962 struct page *pages[2] = {NULL};
963 temp_mm_state_t prev;
970 * While boot memory allocator is running we cannot use struct pages as
971 * they are not yet initialized. There is no way to recover.
973 BUG_ON(!after_bootmem);
975 if (!core_kernel_text((unsigned long)addr)) {
976 pages[0] = vmalloc_to_page(addr);
977 if (cross_page_boundary)
978 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
980 pages[0] = virt_to_page(addr);
981 WARN_ON(!PageReserved(pages[0]));
982 if (cross_page_boundary)
983 pages[1] = virt_to_page(addr + PAGE_SIZE);
986 * If something went wrong, crash and burn since recovery paths are not
989 BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
992 * Map the page without the global bit, as TLB flushing is done with
993 * flush_tlb_mm_range(), which is intended for non-global PTEs.
995 pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
998 * The lock is not really needed, but this allows to avoid open-coding.
1000 ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
1003 * This must not fail; preallocated in poking_init().
1007 local_irq_save(flags);
1009 pte = mk_pte(pages[0], pgprot);
1010 set_pte_at(poking_mm, poking_addr, ptep, pte);
1012 if (cross_page_boundary) {
1013 pte = mk_pte(pages[1], pgprot);
1014 set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
1018 * Loading the temporary mm behaves as a compiler barrier, which
1019 * guarantees that the PTE will be set at the time memcpy() is done.
1021 prev = use_temporary_mm(poking_mm);
1023 kasan_disable_current();
1024 memcpy((u8 *)poking_addr + offset_in_page(addr), opcode, len);
1025 kasan_enable_current();
1028 * Ensure that the PTE is only cleared after the instructions of memcpy
1029 * were issued by using a compiler barrier.
1033 pte_clear(poking_mm, poking_addr, ptep);
1034 if (cross_page_boundary)
1035 pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
1038 * Loading the previous page-table hierarchy requires a serializing
1039 * instruction that already allows the core to see the updated version.
1040 * Xen-PV is assumed to serialize execution in a similar manner.
1042 unuse_temporary_mm(prev);
1045 * Flushing the TLB might involve IPIs, which would require enabled
1046 * IRQs, but not if the mm is not used, as it is in this point.
1048 flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
1049 (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
1053 * If the text does not match what we just wrote then something is
1054 * fundamentally screwy; there's nothing we can really do about that.
1056 BUG_ON(memcmp(addr, opcode, len));
1058 local_irq_restore(flags);
1059 pte_unmap_unlock(ptep, ptl);
1064 * text_poke - Update instructions on a live kernel
1065 * @addr: address to modify
1066 * @opcode: source of the copy
1067 * @len: length to copy
1069 * Only atomic text poke/set should be allowed when not doing early patching.
1070 * It means the size must be writable atomically and the address must be aligned
1071 * in a way that permits an atomic write. It also makes sure we fit on a single
1074 * Note that the caller must ensure that if the modified code is part of a
1075 * module, the module would not be removed during poking. This can be achieved
1076 * by registering a module notifier, and ordering module removal and patching
1079 void *text_poke(void *addr, const void *opcode, size_t len)
1081 lockdep_assert_held(&text_mutex);
1083 return __text_poke(addr, opcode, len);
1087 * text_poke_kgdb - Update instructions on a live kernel by kgdb
1088 * @addr: address to modify
1089 * @opcode: source of the copy
1090 * @len: length to copy
1092 * Only atomic text poke/set should be allowed when not doing early patching.
1093 * It means the size must be writable atomically and the address must be aligned
1094 * in a way that permits an atomic write. It also makes sure we fit on a single
1097 * Context: should only be used by kgdb, which ensures no other core is running,
1098 * despite the fact it does not hold the text_mutex.
1100 void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
1102 return __text_poke(addr, opcode, len);
1105 static void do_sync_core(void *info)
1110 void text_poke_sync(void)
1112 on_each_cpu(do_sync_core, NULL, 1);
1115 struct text_poke_loc {
1116 /* addr := _stext + rel_addr */
1121 const u8 text[POKE_MAX_OPCODE_SIZE];
1122 /* see text_poke_bp_batch() */
1126 struct bp_patching_desc {
1127 struct text_poke_loc *vec;
1132 static struct bp_patching_desc *bp_desc;
1134 static __always_inline
1135 struct bp_patching_desc *try_get_desc(struct bp_patching_desc **descp)
1137 /* rcu_dereference */
1138 struct bp_patching_desc *desc = __READ_ONCE(*descp);
1140 if (!desc || !arch_atomic_inc_not_zero(&desc->refs))
1146 static __always_inline void put_desc(struct bp_patching_desc *desc)
1148 smp_mb__before_atomic();
1149 arch_atomic_dec(&desc->refs);
1152 static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
1154 return _stext + tp->rel_addr;
1157 static __always_inline int patch_cmp(const void *key, const void *elt)
1159 struct text_poke_loc *tp = (struct text_poke_loc *) elt;
1161 if (key < text_poke_addr(tp))
1163 if (key > text_poke_addr(tp))
1168 noinstr int poke_int3_handler(struct pt_regs *regs)
1170 struct bp_patching_desc *desc;
1171 struct text_poke_loc *tp;
1175 if (user_mode(regs))
1179 * Having observed our INT3 instruction, we now must observe
1182 * bp_desc = desc INT3
1184 * write INT3 if (desc)
1188 desc = try_get_desc(&bp_desc);
1193 * Discount the INT3. See text_poke_bp_batch().
1195 ip = (void *) regs->ip - INT3_INSN_SIZE;
1198 * Skip the binary search if there is a single member in the vector.
1200 if (unlikely(desc->nr_entries > 1)) {
1201 tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
1202 sizeof(struct text_poke_loc),
1208 if (text_poke_addr(tp) != ip)
1214 switch (tp->opcode) {
1215 case INT3_INSN_OPCODE:
1217 * Someone poked an explicit INT3, they'll want to handle it,
1222 case RET_INSN_OPCODE:
1223 int3_emulate_ret(regs);
1226 case CALL_INSN_OPCODE:
1227 int3_emulate_call(regs, (long)ip + tp->disp);
1230 case JMP32_INSN_OPCODE:
1231 case JMP8_INSN_OPCODE:
1232 int3_emulate_jmp(regs, (long)ip + tp->disp);
1246 #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
1247 static struct text_poke_loc tp_vec[TP_VEC_MAX];
1248 static int tp_vec_nr;
1251 * text_poke_bp_batch() -- update instructions on live kernel on SMP
1252 * @tp: vector of instructions to patch
1253 * @nr_entries: number of entries in the vector
1255 * Modify multi-byte instruction by using int3 breakpoint on SMP.
1256 * We completely avoid stop_machine() here, and achieve the
1257 * synchronization using int3 breakpoint.
1259 * The way it is done:
1260 * - For each entry in the vector:
1261 * - add a int3 trap to the address that will be patched
1263 * - For each entry in the vector:
1264 * - update all but the first byte of the patched range
1266 * - For each entry in the vector:
1267 * - replace the first byte (int3) by the first byte of
1271 static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
1273 struct bp_patching_desc desc = {
1275 .nr_entries = nr_entries,
1276 .refs = ATOMIC_INIT(1),
1278 unsigned char int3 = INT3_INSN_OPCODE;
1282 lockdep_assert_held(&text_mutex);
1284 smp_store_release(&bp_desc, &desc); /* rcu_assign_pointer */
1287 * Corresponding read barrier in int3 notifier for making sure the
1288 * nr_entries and handler are correctly ordered wrt. patching.
1293 * First step: add a int3 trap to the address that will be patched.
1295 for (i = 0; i < nr_entries; i++) {
1296 tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
1297 text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
1303 * Second step: update all but the first byte of the patched range.
1305 for (do_sync = 0, i = 0; i < nr_entries; i++) {
1306 u8 old[POKE_MAX_OPCODE_SIZE] = { tp[i].old, };
1307 int len = tp[i].len;
1309 if (len - INT3_INSN_SIZE > 0) {
1310 memcpy(old + INT3_INSN_SIZE,
1311 text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1312 len - INT3_INSN_SIZE);
1313 text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1314 (const char *)tp[i].text + INT3_INSN_SIZE,
1315 len - INT3_INSN_SIZE);
1320 * Emit a perf event to record the text poke, primarily to
1321 * support Intel PT decoding which must walk the executable code
1322 * to reconstruct the trace. The flow up to here is:
1325 * - write instruction tail
1326 * At this point the actual control flow will be through the
1327 * INT3 and handler and not hit the old or new instruction.
1328 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
1329 * can still be decoded. Subsequently:
1330 * - emit RECORD_TEXT_POKE with the new instruction
1332 * - write first byte
1334 * So before the text poke event timestamp, the decoder will see
1335 * either the old instruction flow or FUP/TIP of INT3. After the
1336 * text poke event timestamp, the decoder will see either the
1337 * new instruction flow or FUP/TIP of INT3. Thus decoders can
1338 * use the timestamp as the point at which to modify the
1340 * The old instruction is recorded so that the event can be
1341 * processed forwards or backwards.
1343 perf_event_text_poke(text_poke_addr(&tp[i]), old, len,
1349 * According to Intel, this core syncing is very likely
1350 * not necessary and we'd be safe even without it. But
1351 * better safe than sorry (plus there's not only Intel).
1357 * Third step: replace the first byte (int3) by the first byte of
1360 for (do_sync = 0, i = 0; i < nr_entries; i++) {
1361 if (tp[i].text[0] == INT3_INSN_OPCODE)
1364 text_poke(text_poke_addr(&tp[i]), tp[i].text, INT3_INSN_SIZE);
1372 * Remove and synchronize_rcu(), except we have a very primitive
1373 * refcount based completion.
1375 WRITE_ONCE(bp_desc, NULL); /* RCU_INIT_POINTER */
1376 if (!atomic_dec_and_test(&desc.refs))
1377 atomic_cond_read_acquire(&desc.refs, !VAL);
1380 static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
1381 const void *opcode, size_t len, const void *emulate)
1386 memcpy((void *)tp->text, opcode, len);
1390 ret = insn_decode_kernel(&insn, emulate);
1393 tp->rel_addr = addr - (void *)_stext;
1395 tp->opcode = insn.opcode.bytes[0];
1397 switch (tp->opcode) {
1398 case RET_INSN_OPCODE:
1399 case JMP32_INSN_OPCODE:
1400 case JMP8_INSN_OPCODE:
1402 * Control flow instructions without implied execution of the
1403 * next instruction can be padded with INT3.
1405 for (i = insn.length; i < len; i++)
1406 BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
1410 BUG_ON(len != insn.length);
1414 switch (tp->opcode) {
1415 case INT3_INSN_OPCODE:
1416 case RET_INSN_OPCODE:
1419 case CALL_INSN_OPCODE:
1420 case JMP32_INSN_OPCODE:
1421 case JMP8_INSN_OPCODE:
1422 tp->disp = insn.immediate.value;
1425 default: /* assume NOP */
1427 case 2: /* NOP2 -- emulate as JMP8+0 */
1428 BUG_ON(memcmp(emulate, x86_nops[len], len));
1429 tp->opcode = JMP8_INSN_OPCODE;
1433 case 5: /* NOP5 -- emulate as JMP32+0 */
1434 BUG_ON(memcmp(emulate, x86_nops[len], len));
1435 tp->opcode = JMP32_INSN_OPCODE;
1439 default: /* unknown instruction */
1447 * We hard rely on the tp_vec being ordered; ensure this is so by flushing
1450 static bool tp_order_fail(void *addr)
1452 struct text_poke_loc *tp;
1457 if (!addr) /* force */
1460 tp = &tp_vec[tp_vec_nr - 1];
1461 if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
1467 static void text_poke_flush(void *addr)
1469 if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
1470 text_poke_bp_batch(tp_vec, tp_vec_nr);
1475 void text_poke_finish(void)
1477 text_poke_flush(NULL);
1480 void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
1482 struct text_poke_loc *tp;
1484 if (unlikely(system_state == SYSTEM_BOOTING)) {
1485 text_poke_early(addr, opcode, len);
1489 text_poke_flush(addr);
1491 tp = &tp_vec[tp_vec_nr++];
1492 text_poke_loc_init(tp, addr, opcode, len, emulate);
1496 * text_poke_bp() -- update instructions on live kernel on SMP
1497 * @addr: address to patch
1498 * @opcode: opcode of new instruction
1499 * @len: length to copy
1500 * @emulate: instruction to be emulated
1502 * Update a single instruction with the vector in the stack, avoiding
1503 * dynamically allocated memory. This function should be used when it is
1504 * not possible to allocate memory.
1506 void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
1508 struct text_poke_loc tp;
1510 if (unlikely(system_state == SYSTEM_BOOTING)) {
1511 text_poke_early(addr, opcode, len);
1515 text_poke_loc_init(&tp, addr, opcode, len, emulate);
1516 text_poke_bp_batch(&tp, 1);