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/asm-prototypes.h>
33 int __read_mostly alternatives_patched;
35 EXPORT_SYMBOL_GPL(alternatives_patched);
37 #define MAX_PATCH_LEN (255-1)
39 static int __initdata_or_module debug_alternative;
41 static int __init debug_alt(char *str)
43 debug_alternative = 1;
46 __setup("debug-alternative", debug_alt);
48 static int noreplace_smp;
50 static int __init setup_noreplace_smp(char *str)
55 __setup("noreplace-smp", setup_noreplace_smp);
57 #define DPRINTK(fmt, args...) \
59 if (debug_alternative) \
60 printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \
63 #define DUMP_BYTES(buf, len, fmt, args...) \
65 if (unlikely(debug_alternative)) { \
71 printk(KERN_DEBUG pr_fmt(fmt), ##args); \
72 for (j = 0; j < (len) - 1; j++) \
73 printk(KERN_CONT "%02hhx ", buf[j]); \
74 printk(KERN_CONT "%02hhx\n", buf[j]); \
79 * Each GENERIC_NOPX is of X bytes, and defined as an array of bytes
80 * that correspond to that nop. Getting from one nop to the next, we
81 * add to the array the offset that is equal to the sum of all sizes of
82 * nops preceding the one we are after.
84 * Note: The GENERIC_NOP5_ATOMIC is at the end, as it breaks the
85 * nice symmetry of sizes of the previous nops.
87 #if defined(GENERIC_NOP1) && !defined(CONFIG_X86_64)
88 static const unsigned char intelnops[] =
100 static const unsigned char * const intel_nops[ASM_NOP_MAX+2] =
106 intelnops + 1 + 2 + 3,
107 intelnops + 1 + 2 + 3 + 4,
108 intelnops + 1 + 2 + 3 + 4 + 5,
109 intelnops + 1 + 2 + 3 + 4 + 5 + 6,
110 intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
111 intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
116 static const unsigned char k8nops[] =
128 static const unsigned char * const k8_nops[ASM_NOP_MAX+2] =
135 k8nops + 1 + 2 + 3 + 4,
136 k8nops + 1 + 2 + 3 + 4 + 5,
137 k8nops + 1 + 2 + 3 + 4 + 5 + 6,
138 k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
139 k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
143 #if defined(K7_NOP1) && !defined(CONFIG_X86_64)
144 static const unsigned char k7nops[] =
156 static const unsigned char * const k7_nops[ASM_NOP_MAX+2] =
163 k7nops + 1 + 2 + 3 + 4,
164 k7nops + 1 + 2 + 3 + 4 + 5,
165 k7nops + 1 + 2 + 3 + 4 + 5 + 6,
166 k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
167 k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
172 static const unsigned char p6nops[] =
184 static const unsigned char * const p6_nops[ASM_NOP_MAX+2] =
191 p6nops + 1 + 2 + 3 + 4,
192 p6nops + 1 + 2 + 3 + 4 + 5,
193 p6nops + 1 + 2 + 3 + 4 + 5 + 6,
194 p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
195 p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
199 /* Initialize these to a safe default */
201 const unsigned char * const *ideal_nops = p6_nops;
203 const unsigned char * const *ideal_nops = intel_nops;
206 void __init arch_init_ideal_nops(void)
208 switch (boot_cpu_data.x86_vendor) {
209 case X86_VENDOR_INTEL:
211 * Due to a decoder implementation quirk, some
212 * specific Intel CPUs actually perform better with
213 * the "k8_nops" than with the SDM-recommended NOPs.
215 if (boot_cpu_data.x86 == 6 &&
216 boot_cpu_data.x86_model >= 0x0f &&
217 boot_cpu_data.x86_model != 0x1c &&
218 boot_cpu_data.x86_model != 0x26 &&
219 boot_cpu_data.x86_model != 0x27 &&
220 boot_cpu_data.x86_model < 0x30) {
221 ideal_nops = k8_nops;
222 } else if (boot_cpu_has(X86_FEATURE_NOPL)) {
223 ideal_nops = p6_nops;
226 ideal_nops = k8_nops;
228 ideal_nops = intel_nops;
233 case X86_VENDOR_HYGON:
234 ideal_nops = p6_nops;
238 if (boot_cpu_data.x86 > 0xf) {
239 ideal_nops = p6_nops;
247 ideal_nops = k8_nops;
249 if (boot_cpu_has(X86_FEATURE_K8))
250 ideal_nops = k8_nops;
251 else if (boot_cpu_has(X86_FEATURE_K7))
252 ideal_nops = k7_nops;
254 ideal_nops = intel_nops;
259 /* Use this to add nops to a buffer, then text_poke the whole buffer. */
260 static void __init_or_module add_nops(void *insns, unsigned int len)
263 unsigned int noplen = len;
264 if (noplen > ASM_NOP_MAX)
265 noplen = ASM_NOP_MAX;
266 memcpy(insns, ideal_nops[noplen], noplen);
272 extern s32 __retpoline_sites[], __retpoline_sites_end[];
273 extern s32 __return_sites[], __return_sites_end[];
274 extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
275 extern s32 __smp_locks[], __smp_locks_end[];
276 void text_poke_early(void *addr, const void *opcode, size_t len);
279 * Are we looking at a near JMP with a 1 or 4-byte displacement.
281 static inline bool is_jmp(const u8 opcode)
283 return opcode == 0xeb || opcode == 0xe9;
286 static void __init_or_module
287 recompute_jump(struct alt_instr *a, u8 *orig_insn, u8 *repl_insn, u8 *insn_buff)
289 u8 *next_rip, *tgt_rip;
293 if (a->replacementlen != 5)
296 o_dspl = *(s32 *)(insn_buff + 1);
298 /* next_rip of the replacement JMP */
299 next_rip = repl_insn + a->replacementlen;
300 /* target rip of the replacement JMP */
301 tgt_rip = next_rip + o_dspl;
302 n_dspl = tgt_rip - orig_insn;
304 DPRINTK("target RIP: %px, new_displ: 0x%x", tgt_rip, n_dspl);
306 if (tgt_rip - orig_insn >= 0) {
307 if (n_dspl - 2 <= 127)
311 /* negative offset */
313 if (((n_dspl - 2) & 0xff) == (n_dspl - 2))
323 insn_buff[1] = (s8)n_dspl;
324 add_nops(insn_buff + 2, 3);
333 *(s32 *)&insn_buff[1] = n_dspl;
339 DPRINTK("final displ: 0x%08x, JMP 0x%lx",
340 n_dspl, (unsigned long)orig_insn + n_dspl + repl_len);
344 * optimize_nops_range() - Optimize a sequence of single byte NOPs (0x90)
346 * @instr: instruction byte stream
347 * @instrlen: length of the above
348 * @off: offset within @instr where the first NOP has been detected
350 * Return: number of NOPs found (and replaced).
352 static __always_inline int optimize_nops_range(u8 *instr, u8 instrlen, int off)
357 while (i < instrlen) {
358 if (instr[i] != 0x90)
369 local_irq_save(flags);
370 add_nops(instr + off, nnops);
371 local_irq_restore(flags);
373 DUMP_BYTES(instr, instrlen, "%px: [%d:%d) optimized NOPs: ", instr, off, i);
379 * "noinline" to cause control flow change and thus invalidate I$ and
380 * cause refetch after modification.
382 static void __init_or_module noinline optimize_nops(u8 *instr, size_t len)
388 * Jump over the non-NOP insns and optimize single-byte NOPs into bigger
392 if (insn_decode_kernel(&insn, &instr[i]))
396 * See if this and any potentially following NOPs can be
399 if (insn.length == 1 && insn.opcode.bytes[0] == 0x90)
400 i += optimize_nops_range(instr, len, i);
410 * Replace instructions with better alternatives for this CPU type. This runs
411 * before SMP is initialized to avoid SMP problems with self modifying code.
412 * This implies that asymmetric systems where APs have less capabilities than
413 * the boot processor are not handled. Tough. Make sure you disable such
416 * Marked "noinline" to cause control flow change and thus insn cache
417 * to refetch changed I$ lines.
419 void __init_or_module noinline apply_alternatives(struct alt_instr *start,
420 struct alt_instr *end)
423 u8 *instr, *replacement;
424 u8 insn_buff[MAX_PATCH_LEN];
426 DPRINTK("alt table %px, -> %px", start, end);
429 * In the case CONFIG_X86_5LEVEL=y, KASAN_SHADOW_START is defined using
430 * cpu_feature_enabled(X86_FEATURE_LA57) and is therefore patched here.
431 * During the process, KASAN becomes confused seeing partial LA57
432 * conversion and triggers a false-positive out-of-bound report.
434 * Disable KASAN until the patching is complete.
436 kasan_disable_current();
439 * The scan order should be from start to end. A later scanned
440 * alternative code can overwrite previously scanned alternative code.
441 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
444 * So be careful if you want to change the scan order to any other
447 for (a = start; a < end; a++) {
448 int insn_buff_sz = 0;
449 /* Mask away "NOT" flag bit for feature to test. */
450 u16 feature = a->cpuid & ~ALTINSTR_FLAG_INV;
452 instr = (u8 *)&a->instr_offset + a->instr_offset;
453 replacement = (u8 *)&a->repl_offset + a->repl_offset;
454 BUG_ON(a->instrlen > sizeof(insn_buff));
455 BUG_ON(feature >= (NCAPINTS + NBUGINTS) * 32);
459 * - feature is present
460 * - feature not present but ALTINSTR_FLAG_INV is set to mean,
461 * patch if feature is *NOT* present.
463 if (!boot_cpu_has(feature) == !(a->cpuid & ALTINSTR_FLAG_INV))
466 DPRINTK("feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)",
467 (a->cpuid & ALTINSTR_FLAG_INV) ? "!" : "",
470 instr, instr, a->instrlen,
471 replacement, a->replacementlen);
473 DUMP_BYTES(instr, a->instrlen, "%px: old_insn: ", instr);
474 DUMP_BYTES(replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
476 memcpy(insn_buff, replacement, a->replacementlen);
477 insn_buff_sz = a->replacementlen;
480 * 0xe8 is a relative jump; fix the offset.
482 * Instruction length is checked before the opcode to avoid
483 * accessing uninitialized bytes for zero-length replacements.
485 if (a->replacementlen == 5 && *insn_buff == 0xe8) {
486 *(s32 *)(insn_buff + 1) += replacement - instr;
487 DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
488 *(s32 *)(insn_buff + 1),
489 (unsigned long)instr + *(s32 *)(insn_buff + 1) + 5);
492 if (a->replacementlen && is_jmp(replacement[0]))
493 recompute_jump(a, instr, replacement, insn_buff);
495 for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
496 insn_buff[insn_buff_sz] = 0x90;
498 DUMP_BYTES(insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
500 text_poke_early(instr, insn_buff, insn_buff_sz);
503 optimize_nops(instr, a->instrlen);
506 kasan_enable_current();
509 #if defined(CONFIG_RETPOLINE) && defined(CONFIG_STACK_VALIDATION)
514 static int emit_indirect(int op, int reg, u8 *bytes)
520 case CALL_INSN_OPCODE:
521 modrm = 0x10; /* Reg = 2; CALL r/m */
524 case JMP32_INSN_OPCODE:
525 modrm = 0x20; /* Reg = 4; JMP r/m */
534 bytes[i++] = 0x41; /* REX.B prefix */
538 modrm |= 0xc0; /* Mod = 3 */
541 bytes[i++] = 0xff; /* opcode */
548 * Rewrite the compiler generated retpoline thunk calls.
550 * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
551 * indirect instructions, avoiding the extra indirection.
553 * For example, convert:
555 * CALL __x86_indirect_thunk_\reg
561 * It also tries to inline spectre_v2=retpoline,amd when size permits.
563 static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
565 retpoline_thunk_t *target;
569 target = addr + insn->length + insn->immediate.value;
570 reg = target - __x86_indirect_thunk_array;
572 if (WARN_ON_ONCE(reg & ~0xf))
575 /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
578 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
579 !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE))
582 op = insn->opcode.bytes[0];
587 * Jcc.d32 __x86_indirect_thunk_\reg
597 /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
598 if (op == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80) {
599 cc = insn->opcode.bytes[1] & 0xf;
600 cc ^= 1; /* invert condition */
602 bytes[i++] = 0x70 + cc; /* Jcc.d8 */
603 bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
605 /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
606 op = JMP32_INSN_OPCODE;
610 * For RETPOLINE_AMD: prepend the indirect CALL/JMP with an LFENCE.
612 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
615 bytes[i++] = 0xe8; /* LFENCE */
618 ret = emit_indirect(op, reg, bytes + i);
623 for (; i < insn->length;)
630 * Generated by 'objtool --retpoline'.
632 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
636 for (s = start; s < end; s++) {
637 void *addr = (void *)s + *s;
643 ret = insn_decode_kernel(&insn, addr);
644 if (WARN_ON_ONCE(ret < 0))
647 op1 = insn.opcode.bytes[0];
648 op2 = insn.opcode.bytes[1];
651 case CALL_INSN_OPCODE:
652 case JMP32_INSN_OPCODE:
655 case 0x0f: /* escape */
656 if (op2 >= 0x80 && op2 <= 0x8f)
664 DPRINTK("retpoline at: %pS (%px) len: %d to: %pS",
665 addr, addr, insn.length,
666 addr + insn.length + insn.immediate.value);
668 len = patch_retpoline(addr, &insn, bytes);
669 if (len == insn.length) {
670 optimize_nops(bytes, len);
671 DUMP_BYTES(((u8*)addr), len, "%px: orig: ", addr);
672 DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
673 text_poke_early(addr, bytes, len);
678 #ifdef CONFIG_RETHUNK
681 * Rewrite the compiler generated return thunk tail-calls.
683 * For example, convert:
685 * JMP __x86_return_thunk
691 static int patch_return(void *addr, struct insn *insn, u8 *bytes)
695 if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) {
696 if (x86_return_thunk == __x86_return_thunk)
700 __text_gen_insn(bytes, JMP32_INSN_OPCODE, addr, x86_return_thunk, i);
702 bytes[i++] = RET_INSN_OPCODE;
705 for (; i < insn->length;)
706 bytes[i++] = INT3_INSN_OPCODE;
710 void __init_or_module noinline apply_returns(s32 *start, s32 *end)
714 for (s = start; s < end; s++) {
715 void *dest = NULL, *addr = (void *)s + *s;
721 ret = insn_decode_kernel(&insn, addr);
722 if (WARN_ON_ONCE(ret < 0))
725 op = insn.opcode.bytes[0];
726 if (op == JMP32_INSN_OPCODE)
727 dest = addr + insn.length + insn.immediate.value;
729 if (__static_call_fixup(addr, op, dest) ||
730 WARN_ONCE(dest != &__x86_return_thunk,
731 "missing return thunk: %pS-%pS: %*ph",
732 addr, dest, 5, addr))
735 DPRINTK("return thunk at: %pS (%px) len: %d to: %pS",
736 addr, addr, insn.length,
737 addr + insn.length + insn.immediate.value);
739 len = patch_return(addr, &insn, bytes);
740 if (len == insn.length) {
741 DUMP_BYTES(((u8*)addr), len, "%px: orig: ", addr);
742 DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
743 text_poke_early(addr, bytes, len);
748 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
749 #endif /* CONFIG_RETHUNK */
751 #else /* !RETPOLINES || !CONFIG_STACK_VALIDATION */
753 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
754 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
756 #endif /* CONFIG_RETPOLINE && CONFIG_STACK_VALIDATION */
759 static void alternatives_smp_lock(const s32 *start, const s32 *end,
760 u8 *text, u8 *text_end)
764 for (poff = start; poff < end; poff++) {
765 u8 *ptr = (u8 *)poff + *poff;
767 if (!*poff || ptr < text || ptr >= text_end)
769 /* turn DS segment override prefix into lock prefix */
771 text_poke(ptr, ((unsigned char []){0xf0}), 1);
775 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
776 u8 *text, u8 *text_end)
780 for (poff = start; poff < end; poff++) {
781 u8 *ptr = (u8 *)poff + *poff;
783 if (!*poff || ptr < text || ptr >= text_end)
785 /* turn lock prefix into DS segment override prefix */
787 text_poke(ptr, ((unsigned char []){0x3E}), 1);
791 struct smp_alt_module {
792 /* what is this ??? */
796 /* ptrs to lock prefixes */
798 const s32 *locks_end;
800 /* .text segment, needed to avoid patching init code ;) */
804 struct list_head next;
806 static LIST_HEAD(smp_alt_modules);
807 static bool uniproc_patched = false; /* protected by text_mutex */
809 void __init_or_module alternatives_smp_module_add(struct module *mod,
811 void *locks, void *locks_end,
812 void *text, void *text_end)
814 struct smp_alt_module *smp;
816 mutex_lock(&text_mutex);
817 if (!uniproc_patched)
820 if (num_possible_cpus() == 1)
821 /* Don't bother remembering, we'll never have to undo it. */
824 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
826 /* we'll run the (safe but slow) SMP code then ... */
832 smp->locks_end = locks_end;
834 smp->text_end = text_end;
835 DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
836 smp->locks, smp->locks_end,
837 smp->text, smp->text_end, smp->name);
839 list_add_tail(&smp->next, &smp_alt_modules);
841 alternatives_smp_unlock(locks, locks_end, text, text_end);
843 mutex_unlock(&text_mutex);
846 void __init_or_module alternatives_smp_module_del(struct module *mod)
848 struct smp_alt_module *item;
850 mutex_lock(&text_mutex);
851 list_for_each_entry(item, &smp_alt_modules, next) {
852 if (mod != item->mod)
854 list_del(&item->next);
858 mutex_unlock(&text_mutex);
861 void alternatives_enable_smp(void)
863 struct smp_alt_module *mod;
865 /* Why bother if there are no other CPUs? */
866 BUG_ON(num_possible_cpus() == 1);
868 mutex_lock(&text_mutex);
870 if (uniproc_patched) {
871 pr_info("switching to SMP code\n");
872 BUG_ON(num_online_cpus() != 1);
873 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
874 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
875 list_for_each_entry(mod, &smp_alt_modules, next)
876 alternatives_smp_lock(mod->locks, mod->locks_end,
877 mod->text, mod->text_end);
878 uniproc_patched = false;
880 mutex_unlock(&text_mutex);
884 * Return 1 if the address range is reserved for SMP-alternatives.
885 * Must hold text_mutex.
887 int alternatives_text_reserved(void *start, void *end)
889 struct smp_alt_module *mod;
891 u8 *text_start = start;
894 lockdep_assert_held(&text_mutex);
896 list_for_each_entry(mod, &smp_alt_modules, next) {
897 if (mod->text > text_end || mod->text_end < text_start)
899 for (poff = mod->locks; poff < mod->locks_end; poff++) {
900 const u8 *ptr = (const u8 *)poff + *poff;
902 if (text_start <= ptr && text_end > ptr)
909 #endif /* CONFIG_SMP */
911 #ifdef CONFIG_PARAVIRT
912 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
913 struct paravirt_patch_site *end)
915 struct paravirt_patch_site *p;
916 char insn_buff[MAX_PATCH_LEN];
918 for (p = start; p < end; p++) {
921 BUG_ON(p->len > MAX_PATCH_LEN);
922 /* prep the buffer with the original instructions */
923 memcpy(insn_buff, p->instr, p->len);
924 used = pv_ops.init.patch(p->type, insn_buff, (unsigned long)p->instr, p->len);
926 BUG_ON(used > p->len);
928 /* Pad the rest with nops */
929 add_nops(insn_buff + used, p->len - used);
930 text_poke_early(p->instr, insn_buff, p->len);
933 extern struct paravirt_patch_site __start_parainstructions[],
934 __stop_parainstructions[];
935 #endif /* CONFIG_PARAVIRT */
938 * Self-test for the INT3 based CALL emulation code.
940 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
941 * properly and that there is a stack gap between the INT3 frame and the
942 * previous context. Without this gap doing a virtual PUSH on the interrupted
943 * stack would corrupt the INT3 IRET frame.
945 * See entry_{32,64}.S for more details.
949 * We define the int3_magic() function in assembly to control the calling
950 * convention such that we can 'call' it from assembly.
953 extern void int3_magic(unsigned int *ptr); /* defined in asm */
956 " .pushsection .init.text, \"ax\", @progbits\n"
957 " .type int3_magic, @function\n"
959 " movl $1, (%" _ASM_ARG1 ")\n"
961 " .size int3_magic, .-int3_magic\n"
965 extern __initdata unsigned long int3_selftest_ip; /* defined in asm below */
968 int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
970 struct die_args *args = data;
971 struct pt_regs *regs = args->regs;
973 if (!regs || user_mode(regs))
979 if (regs->ip - INT3_INSN_SIZE != int3_selftest_ip)
982 int3_emulate_call(regs, (unsigned long)&int3_magic);
986 static void __init int3_selftest(void)
988 static __initdata struct notifier_block int3_exception_nb = {
989 .notifier_call = int3_exception_notify,
990 .priority = INT_MAX-1, /* last */
992 unsigned int val = 0;
994 BUG_ON(register_die_notifier(&int3_exception_nb));
997 * Basically: int3_magic(&val); but really complicated :-)
999 * Stick the address of the INT3 instruction into int3_selftest_ip,
1000 * then trigger the INT3, padded with NOPs to match a CALL instruction
1003 asm volatile ("1: int3; nop; nop; nop; nop\n\t"
1004 ".pushsection .init.data,\"aw\"\n\t"
1005 ".align " __ASM_SEL(4, 8) "\n\t"
1006 ".type int3_selftest_ip, @object\n\t"
1007 ".size int3_selftest_ip, " __ASM_SEL(4, 8) "\n\t"
1008 "int3_selftest_ip:\n\t"
1009 __ASM_SEL(.long, .quad) " 1b\n\t"
1011 : ASM_CALL_CONSTRAINT
1012 : __ASM_SEL_RAW(a, D) (&val)
1017 unregister_die_notifier(&int3_exception_nb);
1020 void __init alternative_instructions(void)
1025 * The patching is not fully atomic, so try to avoid local
1026 * interruptions that might execute the to be patched code.
1027 * Other CPUs are not running.
1032 * Don't stop machine check exceptions while patching.
1033 * MCEs only happen when something got corrupted and in this
1034 * case we must do something about the corruption.
1035 * Ignoring it is worse than an unlikely patching race.
1036 * Also machine checks tend to be broadcast and if one CPU
1037 * goes into machine check the others follow quickly, so we don't
1038 * expect a machine check to cause undue problems during to code
1043 * Rewrite the retpolines, must be done before alternatives since
1044 * those can rewrite the retpoline thunks.
1046 apply_retpolines(__retpoline_sites, __retpoline_sites_end);
1047 apply_returns(__return_sites, __return_sites_end);
1049 apply_alternatives(__alt_instructions, __alt_instructions_end);
1052 /* Patch to UP if other cpus not imminent. */
1053 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
1054 uniproc_patched = true;
1055 alternatives_smp_module_add(NULL, "core kernel",
1056 __smp_locks, __smp_locks_end,
1060 if (!uniproc_patched || num_possible_cpus() == 1) {
1061 free_init_pages("SMP alternatives",
1062 (unsigned long)__smp_locks,
1063 (unsigned long)__smp_locks_end);
1067 apply_paravirt(__parainstructions, __parainstructions_end);
1070 alternatives_patched = 1;
1074 * text_poke_early - Update instructions on a live kernel at boot time
1075 * @addr: address to modify
1076 * @opcode: source of the copy
1077 * @len: length to copy
1079 * When you use this code to patch more than one byte of an instruction
1080 * you need to make sure that other CPUs cannot execute this code in parallel.
1081 * Also no thread must be currently preempted in the middle of these
1082 * instructions. And on the local CPU you need to be protected against NMI or
1083 * MCE handlers seeing an inconsistent instruction while you patch.
1085 void __init_or_module text_poke_early(void *addr, const void *opcode,
1088 unsigned long flags;
1090 if (boot_cpu_has(X86_FEATURE_NX) &&
1091 is_module_text_address((unsigned long)addr)) {
1093 * Modules text is marked initially as non-executable, so the
1094 * code cannot be running and speculative code-fetches are
1095 * prevented. Just change the code.
1097 memcpy(addr, opcode, len);
1099 local_irq_save(flags);
1100 memcpy(addr, opcode, len);
1102 local_irq_restore(flags);
1105 * Could also do a CLFLUSH here to speed up CPU recovery; but
1106 * that causes hangs on some VIA CPUs.
1112 struct mm_struct *mm;
1116 * Using a temporary mm allows to set temporary mappings that are not accessible
1117 * by other CPUs. Such mappings are needed to perform sensitive memory writes
1118 * that override the kernel memory protections (e.g., W^X), without exposing the
1119 * temporary page-table mappings that are required for these write operations to
1120 * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
1121 * mapping is torn down.
1123 * Context: The temporary mm needs to be used exclusively by a single core. To
1124 * harden security IRQs must be disabled while the temporary mm is
1125 * loaded, thereby preventing interrupt handler bugs from overriding
1126 * the kernel memory protection.
1128 static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
1130 temp_mm_state_t temp_state;
1132 lockdep_assert_irqs_disabled();
1135 * Make sure not to be in TLB lazy mode, as otherwise we'll end up
1136 * with a stale address space WITHOUT being in lazy mode after
1137 * restoring the previous mm.
1139 if (this_cpu_read(cpu_tlbstate.is_lazy))
1140 leave_mm(smp_processor_id());
1142 temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
1143 switch_mm_irqs_off(NULL, mm, current);
1146 * If breakpoints are enabled, disable them while the temporary mm is
1147 * used. Userspace might set up watchpoints on addresses that are used
1148 * in the temporary mm, which would lead to wrong signals being sent or
1151 * Note that breakpoints are not disabled selectively, which also causes
1152 * kernel breakpoints (e.g., perf's) to be disabled. This might be
1153 * undesirable, but still seems reasonable as the code that runs in the
1154 * temporary mm should be short.
1156 if (hw_breakpoint_active())
1157 hw_breakpoint_disable();
1162 static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
1164 lockdep_assert_irqs_disabled();
1165 switch_mm_irqs_off(NULL, prev_state.mm, current);
1168 * Restore the breakpoints if they were disabled before the temporary mm
1171 if (hw_breakpoint_active())
1172 hw_breakpoint_restore();
1175 __ro_after_init struct mm_struct *poking_mm;
1176 __ro_after_init unsigned long poking_addr;
1178 static void *__text_poke(void *addr, const void *opcode, size_t len)
1180 bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
1181 struct page *pages[2] = {NULL};
1182 temp_mm_state_t prev;
1183 unsigned long flags;
1189 * While boot memory allocator is running we cannot use struct pages as
1190 * they are not yet initialized. There is no way to recover.
1192 BUG_ON(!after_bootmem);
1194 if (!core_kernel_text((unsigned long)addr)) {
1195 pages[0] = vmalloc_to_page(addr);
1196 if (cross_page_boundary)
1197 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
1199 pages[0] = virt_to_page(addr);
1200 WARN_ON(!PageReserved(pages[0]));
1201 if (cross_page_boundary)
1202 pages[1] = virt_to_page(addr + PAGE_SIZE);
1205 * If something went wrong, crash and burn since recovery paths are not
1208 BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
1211 * Map the page without the global bit, as TLB flushing is done with
1212 * flush_tlb_mm_range(), which is intended for non-global PTEs.
1214 pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
1217 * The lock is not really needed, but this allows to avoid open-coding.
1219 ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
1222 * This must not fail; preallocated in poking_init().
1226 local_irq_save(flags);
1228 pte = mk_pte(pages[0], pgprot);
1229 set_pte_at(poking_mm, poking_addr, ptep, pte);
1231 if (cross_page_boundary) {
1232 pte = mk_pte(pages[1], pgprot);
1233 set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
1237 * Loading the temporary mm behaves as a compiler barrier, which
1238 * guarantees that the PTE will be set at the time memcpy() is done.
1240 prev = use_temporary_mm(poking_mm);
1242 kasan_disable_current();
1243 memcpy((u8 *)poking_addr + offset_in_page(addr), opcode, len);
1244 kasan_enable_current();
1247 * Ensure that the PTE is only cleared after the instructions of memcpy
1248 * were issued by using a compiler barrier.
1252 pte_clear(poking_mm, poking_addr, ptep);
1253 if (cross_page_boundary)
1254 pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
1257 * Loading the previous page-table hierarchy requires a serializing
1258 * instruction that already allows the core to see the updated version.
1259 * Xen-PV is assumed to serialize execution in a similar manner.
1261 unuse_temporary_mm(prev);
1264 * Flushing the TLB might involve IPIs, which would require enabled
1265 * IRQs, but not if the mm is not used, as it is in this point.
1267 flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
1268 (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
1272 * If the text does not match what we just wrote then something is
1273 * fundamentally screwy; there's nothing we can really do about that.
1275 BUG_ON(memcmp(addr, opcode, len));
1277 local_irq_restore(flags);
1278 pte_unmap_unlock(ptep, ptl);
1283 * text_poke - Update instructions on a live kernel
1284 * @addr: address to modify
1285 * @opcode: source of the copy
1286 * @len: length to copy
1288 * Only atomic text poke/set should be allowed when not doing early patching.
1289 * It means the size must be writable atomically and the address must be aligned
1290 * in a way that permits an atomic write. It also makes sure we fit on a single
1293 * Note that the caller must ensure that if the modified code is part of a
1294 * module, the module would not be removed during poking. This can be achieved
1295 * by registering a module notifier, and ordering module removal and patching
1298 void *text_poke(void *addr, const void *opcode, size_t len)
1300 lockdep_assert_held(&text_mutex);
1302 return __text_poke(addr, opcode, len);
1306 * text_poke_kgdb - Update instructions on a live kernel by kgdb
1307 * @addr: address to modify
1308 * @opcode: source of the copy
1309 * @len: length to copy
1311 * Only atomic text poke/set should be allowed when not doing early patching.
1312 * It means the size must be writable atomically and the address must be aligned
1313 * in a way that permits an atomic write. It also makes sure we fit on a single
1316 * Context: should only be used by kgdb, which ensures no other core is running,
1317 * despite the fact it does not hold the text_mutex.
1319 void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
1321 return __text_poke(addr, opcode, len);
1324 static void do_sync_core(void *info)
1329 void text_poke_sync(void)
1331 on_each_cpu(do_sync_core, NULL, 1);
1334 struct text_poke_loc {
1335 /* addr := _stext + rel_addr */
1340 const u8 text[POKE_MAX_OPCODE_SIZE];
1341 /* see text_poke_bp_batch() */
1345 struct bp_patching_desc {
1346 struct text_poke_loc *vec;
1351 static struct bp_patching_desc bp_desc;
1353 static __always_inline
1354 struct bp_patching_desc *try_get_desc(void)
1356 struct bp_patching_desc *desc = &bp_desc;
1358 if (!arch_atomic_inc_not_zero(&desc->refs))
1364 static __always_inline void put_desc(void)
1366 struct bp_patching_desc *desc = &bp_desc;
1368 smp_mb__before_atomic();
1369 arch_atomic_dec(&desc->refs);
1372 static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
1374 return _stext + tp->rel_addr;
1377 static __always_inline int patch_cmp(const void *key, const void *elt)
1379 struct text_poke_loc *tp = (struct text_poke_loc *) elt;
1381 if (key < text_poke_addr(tp))
1383 if (key > text_poke_addr(tp))
1388 noinstr int poke_int3_handler(struct pt_regs *regs)
1390 struct bp_patching_desc *desc;
1391 struct text_poke_loc *tp;
1395 if (user_mode(regs))
1399 * Having observed our INT3 instruction, we now must observe
1400 * bp_desc with non-zero refcount:
1402 * bp_desc.refs = 1 INT3
1404 * write INT3 if (bp_desc.refs != 0)
1408 desc = try_get_desc();
1413 * Discount the INT3. See text_poke_bp_batch().
1415 ip = (void *) regs->ip - INT3_INSN_SIZE;
1418 * Skip the binary search if there is a single member in the vector.
1420 if (unlikely(desc->nr_entries > 1)) {
1421 tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
1422 sizeof(struct text_poke_loc),
1428 if (text_poke_addr(tp) != ip)
1434 switch (tp->opcode) {
1435 case INT3_INSN_OPCODE:
1437 * Someone poked an explicit INT3, they'll want to handle it,
1442 case RET_INSN_OPCODE:
1443 int3_emulate_ret(regs);
1446 case CALL_INSN_OPCODE:
1447 int3_emulate_call(regs, (long)ip + tp->disp);
1450 case JMP32_INSN_OPCODE:
1451 case JMP8_INSN_OPCODE:
1452 int3_emulate_jmp(regs, (long)ip + tp->disp);
1466 #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
1467 static struct text_poke_loc tp_vec[TP_VEC_MAX];
1468 static int tp_vec_nr;
1471 * text_poke_bp_batch() -- update instructions on live kernel on SMP
1472 * @tp: vector of instructions to patch
1473 * @nr_entries: number of entries in the vector
1475 * Modify multi-byte instruction by using int3 breakpoint on SMP.
1476 * We completely avoid stop_machine() here, and achieve the
1477 * synchronization using int3 breakpoint.
1479 * The way it is done:
1480 * - For each entry in the vector:
1481 * - add a int3 trap to the address that will be patched
1483 * - For each entry in the vector:
1484 * - update all but the first byte of the patched range
1486 * - For each entry in the vector:
1487 * - replace the first byte (int3) by the first byte of
1491 static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
1493 unsigned char int3 = INT3_INSN_OPCODE;
1497 lockdep_assert_held(&text_mutex);
1500 bp_desc.nr_entries = nr_entries;
1503 * Corresponds to the implicit memory barrier in try_get_desc() to
1504 * ensure reading a non-zero refcount provides up to date bp_desc data.
1506 atomic_set_release(&bp_desc.refs, 1);
1509 * Corresponding read barrier in int3 notifier for making sure the
1510 * nr_entries and handler are correctly ordered wrt. patching.
1515 * First step: add a int3 trap to the address that will be patched.
1517 for (i = 0; i < nr_entries; i++) {
1518 tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
1519 text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
1525 * Second step: update all but the first byte of the patched range.
1527 for (do_sync = 0, i = 0; i < nr_entries; i++) {
1528 u8 old[POKE_MAX_OPCODE_SIZE] = { tp[i].old, };
1529 int len = tp[i].len;
1531 if (len - INT3_INSN_SIZE > 0) {
1532 memcpy(old + INT3_INSN_SIZE,
1533 text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1534 len - INT3_INSN_SIZE);
1535 text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1536 (const char *)tp[i].text + INT3_INSN_SIZE,
1537 len - INT3_INSN_SIZE);
1542 * Emit a perf event to record the text poke, primarily to
1543 * support Intel PT decoding which must walk the executable code
1544 * to reconstruct the trace. The flow up to here is:
1547 * - write instruction tail
1548 * At this point the actual control flow will be through the
1549 * INT3 and handler and not hit the old or new instruction.
1550 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
1551 * can still be decoded. Subsequently:
1552 * - emit RECORD_TEXT_POKE with the new instruction
1554 * - write first byte
1556 * So before the text poke event timestamp, the decoder will see
1557 * either the old instruction flow or FUP/TIP of INT3. After the
1558 * text poke event timestamp, the decoder will see either the
1559 * new instruction flow or FUP/TIP of INT3. Thus decoders can
1560 * use the timestamp as the point at which to modify the
1562 * The old instruction is recorded so that the event can be
1563 * processed forwards or backwards.
1565 perf_event_text_poke(text_poke_addr(&tp[i]), old, len,
1571 * According to Intel, this core syncing is very likely
1572 * not necessary and we'd be safe even without it. But
1573 * better safe than sorry (plus there's not only Intel).
1579 * Third step: replace the first byte (int3) by the first byte of
1582 for (do_sync = 0, i = 0; i < nr_entries; i++) {
1583 if (tp[i].text[0] == INT3_INSN_OPCODE)
1586 text_poke(text_poke_addr(&tp[i]), tp[i].text, INT3_INSN_SIZE);
1594 * Remove and wait for refs to be zero.
1596 if (!atomic_dec_and_test(&bp_desc.refs))
1597 atomic_cond_read_acquire(&bp_desc.refs, !VAL);
1600 static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
1601 const void *opcode, size_t len, const void *emulate)
1606 memcpy((void *)tp->text, opcode, len);
1610 ret = insn_decode_kernel(&insn, emulate);
1613 tp->rel_addr = addr - (void *)_stext;
1615 tp->opcode = insn.opcode.bytes[0];
1617 switch (tp->opcode) {
1618 case RET_INSN_OPCODE:
1619 case JMP32_INSN_OPCODE:
1620 case JMP8_INSN_OPCODE:
1622 * Control flow instructions without implied execution of the
1623 * next instruction can be padded with INT3.
1625 for (i = insn.length; i < len; i++)
1626 BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
1630 BUG_ON(len != insn.length);
1634 switch (tp->opcode) {
1635 case INT3_INSN_OPCODE:
1636 case RET_INSN_OPCODE:
1639 case CALL_INSN_OPCODE:
1640 case JMP32_INSN_OPCODE:
1641 case JMP8_INSN_OPCODE:
1642 tp->disp = insn.immediate.value;
1645 default: /* assume NOP */
1647 case 2: /* NOP2 -- emulate as JMP8+0 */
1648 BUG_ON(memcmp(emulate, ideal_nops[len], len));
1649 tp->opcode = JMP8_INSN_OPCODE;
1653 case 5: /* NOP5 -- emulate as JMP32+0 */
1654 BUG_ON(memcmp(emulate, ideal_nops[NOP_ATOMIC5], len));
1655 tp->opcode = JMP32_INSN_OPCODE;
1659 default: /* unknown instruction */
1667 * We hard rely on the tp_vec being ordered; ensure this is so by flushing
1670 static bool tp_order_fail(void *addr)
1672 struct text_poke_loc *tp;
1677 if (!addr) /* force */
1680 tp = &tp_vec[tp_vec_nr - 1];
1681 if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
1687 static void text_poke_flush(void *addr)
1689 if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
1690 text_poke_bp_batch(tp_vec, tp_vec_nr);
1695 void text_poke_finish(void)
1697 text_poke_flush(NULL);
1700 void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
1702 struct text_poke_loc *tp;
1704 if (unlikely(system_state == SYSTEM_BOOTING)) {
1705 text_poke_early(addr, opcode, len);
1709 text_poke_flush(addr);
1711 tp = &tp_vec[tp_vec_nr++];
1712 text_poke_loc_init(tp, addr, opcode, len, emulate);
1716 * text_poke_bp() -- update instructions on live kernel on SMP
1717 * @addr: address to patch
1718 * @opcode: opcode of new instruction
1719 * @len: length to copy
1720 * @handler: address to jump to when the temporary breakpoint is hit
1722 * Update a single instruction with the vector in the stack, avoiding
1723 * dynamically allocated memory. This function should be used when it is
1724 * not possible to allocate memory.
1726 void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
1728 struct text_poke_loc tp;
1730 if (unlikely(system_state == SYSTEM_BOOTING)) {
1731 text_poke_early(addr, opcode, len);
1735 text_poke_loc_init(&tp, addr, opcode, len, emulate);
1736 text_poke_bp_batch(&tp, 1);