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)
43 #define DA_RETPOLINE 0x04
47 static unsigned int __initdata_or_module debug_alternative;
49 static int __init debug_alt(char *str)
51 if (str && *str == '=')
54 if (!str || kstrtouint(str, 0, &debug_alternative))
55 debug_alternative = DA_ALL;
59 __setup("debug-alternative", debug_alt);
61 static int noreplace_smp;
63 static int __init setup_noreplace_smp(char *str)
68 __setup("noreplace-smp", setup_noreplace_smp);
70 #define DPRINTK(type, fmt, args...) \
72 if (debug_alternative & DA_##type) \
73 printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \
76 #define DUMP_BYTES(type, buf, len, fmt, args...) \
78 if (unlikely(debug_alternative & DA_##type)) { \
84 printk(KERN_DEBUG pr_fmt(fmt), ##args); \
85 for (j = 0; j < (len) - 1; j++) \
86 printk(KERN_CONT "%02hhx ", buf[j]); \
87 printk(KERN_CONT "%02hhx\n", buf[j]); \
91 static const unsigned char x86nops[] =
108 const unsigned char * const x86_nops[ASM_NOP_MAX+1] =
115 x86nops + 1 + 2 + 3 + 4,
116 x86nops + 1 + 2 + 3 + 4 + 5,
117 x86nops + 1 + 2 + 3 + 4 + 5 + 6,
118 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
120 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
121 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
122 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
127 * Fill the buffer with a single effective instruction of size @len.
129 * In order not to issue an ORC stack depth tracking CFI entry (Call Frame Info)
130 * for every single-byte NOP, try to generate the maximally available NOP of
131 * size <= ASM_NOP_MAX such that only a single CFI entry is generated (vs one for
132 * each single-byte NOPs). If @len to fill out is > ASM_NOP_MAX, pad with INT3 and
133 * *jump* over instead of executing long and daft NOPs.
135 static void __init_or_module add_nop(u8 *instr, unsigned int len)
137 u8 *target = instr + len;
142 if (len <= ASM_NOP_MAX) {
143 memcpy(instr, x86_nops[len], len);
148 __text_gen_insn(instr, JMP8_INSN_OPCODE, instr, target, JMP8_INSN_SIZE);
149 instr += JMP8_INSN_SIZE;
151 __text_gen_insn(instr, JMP32_INSN_OPCODE, instr, target, JMP32_INSN_SIZE);
152 instr += JMP32_INSN_SIZE;
155 for (;instr < target; instr++)
156 *instr = INT3_INSN_OPCODE;
159 extern s32 __retpoline_sites[], __retpoline_sites_end[];
160 extern s32 __return_sites[], __return_sites_end[];
161 extern s32 __cfi_sites[], __cfi_sites_end[];
162 extern s32 __ibt_endbr_seal[], __ibt_endbr_seal_end[];
163 extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
164 extern s32 __smp_locks[], __smp_locks_end[];
165 void text_poke_early(void *addr, const void *opcode, size_t len);
168 * Matches NOP and NOPL, not any of the other possible NOPs.
170 static bool insn_is_nop(struct insn *insn)
172 /* Anything NOP, but no REP NOP */
173 if (insn->opcode.bytes[0] == 0x90 &&
174 (!insn->prefixes.nbytes || insn->prefixes.bytes[0] != 0xF3))
178 if (insn->opcode.bytes[0] == 0x0F && insn->opcode.bytes[1] == 0x1F)
181 /* TODO: more nops */
187 * Find the offset of the first non-NOP instruction starting at @offset
188 * but no further than @len.
190 static int skip_nops(u8 *instr, int offset, int len)
194 for (; offset < len; offset += insn.length) {
195 if (insn_decode_kernel(&insn, &instr[offset]))
198 if (!insn_is_nop(&insn))
206 * Optimize a sequence of NOPs, possibly preceded by an unconditional jump
207 * to the end of the NOP sequence into a single NOP.
209 static bool __init_or_module
210 __optimize_nops(u8 *instr, size_t len, struct insn *insn, int *next, int *prev, int *target)
212 int i = *next - insn->length;
214 switch (insn->opcode.bytes[0]) {
215 case JMP8_INSN_OPCODE:
216 case JMP32_INSN_OPCODE:
218 *target = *next + insn->immediate.value;
222 if (insn_is_nop(insn)) {
225 *next = skip_nops(instr, *next, len);
226 if (*target && *next == *target)
229 add_nop(instr + nop, *next - nop);
230 DUMP_BYTES(ALT, instr, len, "%px: [%d:%d) optimized NOPs: ", instr, nop, *next);
239 * "noinline" to cause control flow change and thus invalidate I$ and
240 * cause refetch after modification.
242 static void __init_or_module noinline optimize_nops(u8 *instr, size_t len)
244 int prev, target = 0;
246 for (int next, i = 0; i < len; i = next) {
249 if (insn_decode_kernel(&insn, &instr[i]))
252 next = i + insn.length;
254 __optimize_nops(instr, len, &insn, &next, &prev, &target);
259 * In this context, "source" is where the instructions are placed in the
260 * section .altinstr_replacement, for example during kernel build by the
262 * "Destination" is where the instructions are being patched in by this
265 * The source offset is:
267 * src_imm = target - src_next_ip (1)
269 * and the target offset is:
271 * dst_imm = target - dst_next_ip (2)
273 * so rework (1) as an expression for target like:
275 * target = src_imm + src_next_ip (1a)
277 * and substitute in (2) to get:
279 * dst_imm = (src_imm + src_next_ip) - dst_next_ip (3)
281 * Now, since the instruction stream is 'identical' at src and dst (it
282 * is being copied after all) it can be stated that:
284 * src_next_ip = src + ip_offset
285 * dst_next_ip = dst + ip_offset (4)
287 * Substitute (4) in (3) and observe ip_offset being cancelled out to
290 * dst_imm = src_imm + (src + ip_offset) - (dst + ip_offset)
291 * = src_imm + src - dst + ip_offset - ip_offset
292 * = src_imm + src - dst (5)
294 * IOW, only the relative displacement of the code block matters.
297 #define apply_reloc_n(n_, p_, d_) \
299 s32 v = *(s##n_ *)(p_); \
301 BUG_ON((v >> 31) != (v >> (n_-1))); \
302 *(s##n_ *)(p_) = (s##n_)v; \
306 static __always_inline
307 void apply_reloc(int n, void *ptr, uintptr_t diff)
310 case 1: apply_reloc_n(8, ptr, diff); break;
311 case 2: apply_reloc_n(16, ptr, diff); break;
312 case 4: apply_reloc_n(32, ptr, diff); break;
317 static __always_inline
318 bool need_reloc(unsigned long offset, u8 *src, size_t src_len)
320 u8 *target = src + offset;
322 * If the target is inside the patched block, it's relative to the
323 * block itself and does not need relocation.
325 return (target < src || target > src + src_len);
328 static void __init_or_module noinline
329 apply_relocation(u8 *buf, size_t len, u8 *dest, u8 *src, size_t src_len)
331 int prev, target = 0;
333 for (int next, i = 0; i < len; i = next) {
336 if (WARN_ON_ONCE(insn_decode_kernel(&insn, &buf[i])))
339 next = i + insn.length;
341 if (__optimize_nops(buf, len, &insn, &next, &prev, &target))
344 switch (insn.opcode.bytes[0]) {
346 if (insn.opcode.bytes[1] < 0x80 ||
347 insn.opcode.bytes[1] > 0x8f)
350 fallthrough; /* Jcc.d32 */
351 case 0x70 ... 0x7f: /* Jcc.d8 */
352 case JMP8_INSN_OPCODE:
353 case JMP32_INSN_OPCODE:
354 case CALL_INSN_OPCODE:
355 if (need_reloc(next + insn.immediate.value, src, src_len)) {
356 apply_reloc(insn.immediate.nbytes,
357 buf + i + insn_offset_immediate(&insn),
362 * Where possible, convert JMP.d32 into JMP.d8.
364 if (insn.opcode.bytes[0] == JMP32_INSN_OPCODE) {
365 s32 imm = insn.immediate.value;
367 imm += JMP32_INSN_SIZE - JMP8_INSN_SIZE;
368 if ((imm >> 31) == (imm >> 7)) {
369 buf[i+0] = JMP8_INSN_OPCODE;
372 memset(&buf[i+2], INT3_INSN_OPCODE, insn.length - 2);
378 if (insn_rip_relative(&insn)) {
379 if (need_reloc(next + insn.displacement.value, src, src_len)) {
380 apply_reloc(insn.displacement.nbytes,
381 buf + i + insn_offset_displacement(&insn),
389 * Replace instructions with better alternatives for this CPU type. This runs
390 * before SMP is initialized to avoid SMP problems with self modifying code.
391 * This implies that asymmetric systems where APs have less capabilities than
392 * the boot processor are not handled. Tough. Make sure you disable such
395 * Marked "noinline" to cause control flow change and thus insn cache
396 * to refetch changed I$ lines.
398 void __init_or_module noinline apply_alternatives(struct alt_instr *start,
399 struct alt_instr *end)
402 u8 *instr, *replacement;
403 u8 insn_buff[MAX_PATCH_LEN];
405 DPRINTK(ALT, "alt table %px, -> %px", start, end);
407 * The scan order should be from start to end. A later scanned
408 * alternative code can overwrite previously scanned alternative code.
409 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
412 * So be careful if you want to change the scan order to any other
415 for (a = start; a < end; a++) {
416 int insn_buff_sz = 0;
418 instr = (u8 *)&a->instr_offset + a->instr_offset;
419 replacement = (u8 *)&a->repl_offset + a->repl_offset;
420 BUG_ON(a->instrlen > sizeof(insn_buff));
421 BUG_ON(a->cpuid >= (NCAPINTS + NBUGINTS) * 32);
425 * - feature is present
426 * - feature not present but ALT_FLAG_NOT is set to mean,
427 * patch if feature is *NOT* present.
429 if (!boot_cpu_has(a->cpuid) == !(a->flags & ALT_FLAG_NOT)) {
430 optimize_nops(instr, a->instrlen);
434 DPRINTK(ALT, "feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)",
435 (a->flags & ALT_FLAG_NOT) ? "!" : "",
438 instr, instr, a->instrlen,
439 replacement, a->replacementlen);
441 memcpy(insn_buff, replacement, a->replacementlen);
442 insn_buff_sz = a->replacementlen;
444 for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
445 insn_buff[insn_buff_sz] = 0x90;
447 apply_relocation(insn_buff, a->instrlen, instr, replacement, a->replacementlen);
449 DUMP_BYTES(ALT, instr, a->instrlen, "%px: old_insn: ", instr);
450 DUMP_BYTES(ALT, replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
451 DUMP_BYTES(ALT, insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
453 text_poke_early(instr, insn_buff, insn_buff_sz);
457 static inline bool is_jcc32(struct insn *insn)
459 /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
460 return insn->opcode.bytes[0] == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80;
463 #if defined(CONFIG_RETPOLINE) && defined(CONFIG_OBJTOOL)
468 static int emit_indirect(int op, int reg, u8 *bytes)
474 case CALL_INSN_OPCODE:
475 modrm = 0x10; /* Reg = 2; CALL r/m */
478 case JMP32_INSN_OPCODE:
479 modrm = 0x20; /* Reg = 4; JMP r/m */
488 bytes[i++] = 0x41; /* REX.B prefix */
492 modrm |= 0xc0; /* Mod = 3 */
495 bytes[i++] = 0xff; /* opcode */
501 static int emit_call_track_retpoline(void *addr, struct insn *insn, int reg, u8 *bytes)
503 u8 op = insn->opcode.bytes[0];
507 * Clang does 'weird' Jcc __x86_indirect_thunk_r11 conditional
508 * tail-calls. Deal with them.
510 if (is_jcc32(insn)) {
512 op = insn->opcode.bytes[1];
516 if (insn->length == 6)
517 bytes[i++] = 0x2e; /* CS-prefix */
520 case CALL_INSN_OPCODE:
521 __text_gen_insn(bytes+i, op, addr+i,
522 __x86_indirect_call_thunk_array[reg],
527 case JMP32_INSN_OPCODE:
529 __text_gen_insn(bytes+i, op, addr+i,
530 __x86_indirect_jump_thunk_array[reg],
532 i += JMP32_INSN_SIZE;
536 WARN(1, "%pS %px %*ph\n", addr, addr, 6, addr);
540 WARN_ON_ONCE(i != insn->length);
546 * Rewrite the compiler generated retpoline thunk calls.
548 * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
549 * indirect instructions, avoiding the extra indirection.
551 * For example, convert:
553 * CALL __x86_indirect_thunk_\reg
559 * It also tries to inline spectre_v2=retpoline,lfence when size permits.
561 static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
563 retpoline_thunk_t *target;
567 target = addr + insn->length + insn->immediate.value;
568 reg = target - __x86_indirect_thunk_array;
570 if (WARN_ON_ONCE(reg & ~0xf))
573 /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
576 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
577 !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
578 if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
579 return emit_call_track_retpoline(addr, insn, reg, bytes);
584 op = insn->opcode.bytes[0];
589 * Jcc.d32 __x86_indirect_thunk_\reg
599 if (is_jcc32(insn)) {
600 cc = insn->opcode.bytes[1] & 0xf;
601 cc ^= 1; /* invert condition */
603 bytes[i++] = 0x70 + cc; /* Jcc.d8 */
604 bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
606 /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
607 op = JMP32_INSN_OPCODE;
611 * For RETPOLINE_LFENCE: prepend the indirect CALL/JMP with an LFENCE.
613 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
616 bytes[i++] = 0xe8; /* LFENCE */
619 ret = emit_indirect(op, reg, bytes + i);
625 * The compiler is supposed to EMIT an INT3 after every unconditional
626 * JMP instruction due to AMD BTC. However, if the compiler is too old
627 * or SLS isn't enabled, we still need an INT3 after indirect JMPs
630 if (op == JMP32_INSN_OPCODE && i < insn->length)
631 bytes[i++] = INT3_INSN_OPCODE;
633 for (; i < insn->length;)
634 bytes[i++] = BYTES_NOP1;
640 * Generated by 'objtool --retpoline'.
642 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
646 for (s = start; s < end; s++) {
647 void *addr = (void *)s + *s;
653 ret = insn_decode_kernel(&insn, addr);
654 if (WARN_ON_ONCE(ret < 0))
657 op1 = insn.opcode.bytes[0];
658 op2 = insn.opcode.bytes[1];
661 case CALL_INSN_OPCODE:
662 case JMP32_INSN_OPCODE:
665 case 0x0f: /* escape */
666 if (op2 >= 0x80 && op2 <= 0x8f)
674 DPRINTK(RETPOLINE, "retpoline at: %pS (%px) len: %d to: %pS",
675 addr, addr, insn.length,
676 addr + insn.length + insn.immediate.value);
678 len = patch_retpoline(addr, &insn, bytes);
679 if (len == insn.length) {
680 optimize_nops(bytes, len);
681 DUMP_BYTES(RETPOLINE, ((u8*)addr), len, "%px: orig: ", addr);
682 DUMP_BYTES(RETPOLINE, ((u8*)bytes), len, "%px: repl: ", addr);
683 text_poke_early(addr, bytes, len);
688 #ifdef CONFIG_RETHUNK
690 #ifdef CONFIG_CALL_THUNKS
691 void (*x86_return_thunk)(void) __ro_after_init = &__x86_return_thunk;
695 * Rewrite the compiler generated return thunk tail-calls.
697 * For example, convert:
699 * JMP __x86_return_thunk
705 static int patch_return(void *addr, struct insn *insn, u8 *bytes)
709 /* Patch the custom return thunks... */
710 if (cpu_feature_enabled(X86_FEATURE_RETHUNK)) {
712 __text_gen_insn(bytes, JMP32_INSN_OPCODE, addr, x86_return_thunk, i);
714 /* ... or patch them out if not needed. */
715 bytes[i++] = RET_INSN_OPCODE;
718 for (; i < insn->length;)
719 bytes[i++] = INT3_INSN_OPCODE;
723 void __init_or_module noinline apply_returns(s32 *start, s32 *end)
728 * Do not patch out the default return thunks if those needed are the
729 * ones generated by the compiler.
731 if (cpu_feature_enabled(X86_FEATURE_RETHUNK) &&
732 (x86_return_thunk == __x86_return_thunk))
735 for (s = start; s < end; s++) {
736 void *dest = NULL, *addr = (void *)s + *s;
742 ret = insn_decode_kernel(&insn, addr);
743 if (WARN_ON_ONCE(ret < 0))
746 op = insn.opcode.bytes[0];
747 if (op == JMP32_INSN_OPCODE)
748 dest = addr + insn.length + insn.immediate.value;
750 if (__static_call_fixup(addr, op, dest) ||
751 WARN_ONCE(dest != &__x86_return_thunk,
752 "missing return thunk: %pS-%pS: %*ph",
753 addr, dest, 5, addr))
756 DPRINTK(RET, "return thunk at: %pS (%px) len: %d to: %pS",
757 addr, addr, insn.length,
758 addr + insn.length + insn.immediate.value);
760 len = patch_return(addr, &insn, bytes);
761 if (len == insn.length) {
762 DUMP_BYTES(RET, ((u8*)addr), len, "%px: orig: ", addr);
763 DUMP_BYTES(RET, ((u8*)bytes), len, "%px: repl: ", addr);
764 text_poke_early(addr, bytes, len);
769 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
770 #endif /* CONFIG_RETHUNK */
772 #else /* !CONFIG_RETPOLINE || !CONFIG_OBJTOOL */
774 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
775 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
777 #endif /* CONFIG_RETPOLINE && CONFIG_OBJTOOL */
779 #ifdef CONFIG_X86_KERNEL_IBT
781 static void __init_or_module poison_endbr(void *addr, bool warn)
783 u32 endbr, poison = gen_endbr_poison();
785 if (WARN_ON_ONCE(get_kernel_nofault(endbr, addr)))
788 if (!is_endbr(endbr)) {
793 DPRINTK(ENDBR, "ENDBR at: %pS (%px)", addr, addr);
796 * When we have IBT, the lack of ENDBR will trigger #CP
798 DUMP_BYTES(ENDBR, ((u8*)addr), 4, "%px: orig: ", addr);
799 DUMP_BYTES(ENDBR, ((u8*)&poison), 4, "%px: repl: ", addr);
800 text_poke_early(addr, &poison, 4);
804 * Generated by: objtool --ibt
806 void __init_or_module noinline apply_ibt_endbr(s32 *start, s32 *end)
810 for (s = start; s < end; s++) {
811 void *addr = (void *)s + *s;
813 poison_endbr(addr, true);
814 if (IS_ENABLED(CONFIG_FINEIBT))
815 poison_endbr(addr - 16, false);
821 void __init_or_module apply_ibt_endbr(s32 *start, s32 *end) { }
823 #endif /* CONFIG_X86_KERNEL_IBT */
825 #ifdef CONFIG_FINEIBT
834 static enum cfi_mode cfi_mode __ro_after_init = CFI_DEFAULT;
835 static bool cfi_rand __ro_after_init = true;
836 static u32 cfi_seed __ro_after_init;
839 * Re-hash the CFI hash with a boot-time seed while making sure the result is
840 * not a valid ENDBR instruction.
842 static u32 cfi_rehash(u32 hash)
845 while (unlikely(is_endbr(hash) || is_endbr(-hash))) {
854 static __init int cfi_parse_cmdline(char *str)
860 char *next = strchr(str, ',');
866 if (!strcmp(str, "auto")) {
867 cfi_mode = CFI_DEFAULT;
868 } else if (!strcmp(str, "off")) {
871 } else if (!strcmp(str, "kcfi")) {
873 } else if (!strcmp(str, "fineibt")) {
874 cfi_mode = CFI_FINEIBT;
875 } else if (!strcmp(str, "norand")) {
878 pr_err("Ignoring unknown cfi option (%s).", str);
886 early_param("cfi", cfi_parse_cmdline);
891 * __cfi_\func: __cfi_\func:
892 * movl $0x12345678,%eax // 5 endbr64 // 4
893 * nop subl $0x12345678,%r10d // 7
907 * movl $(-0x12345678),%r10d // 6 movl $0x12345678,%r10d // 6
908 * addl $-15(%r11),%r10d // 4 sub $16,%r11 // 4
909 * je 1f // 2 nop4 // 4
911 * 1: call __x86_indirect_thunk_r11 // 5 call *%r11; nop2; // 5
915 asm( ".pushsection .rodata \n"
916 "fineibt_preamble_start: \n"
918 " subl $0x12345678, %r10d \n"
919 " je fineibt_preamble_end \n"
922 "fineibt_preamble_end: \n"
926 extern u8 fineibt_preamble_start[];
927 extern u8 fineibt_preamble_end[];
929 #define fineibt_preamble_size (fineibt_preamble_end - fineibt_preamble_start)
930 #define fineibt_preamble_hash 7
932 asm( ".pushsection .rodata \n"
933 "fineibt_caller_start: \n"
934 " movl $0x12345678, %r10d \n"
937 "fineibt_caller_end: \n"
941 extern u8 fineibt_caller_start[];
942 extern u8 fineibt_caller_end[];
944 #define fineibt_caller_size (fineibt_caller_end - fineibt_caller_start)
945 #define fineibt_caller_hash 2
947 #define fineibt_caller_jmp (fineibt_caller_size - 2)
949 static u32 decode_preamble_hash(void *addr)
953 /* b8 78 56 34 12 mov $0x12345678,%eax */
955 return *(u32 *)(addr + 1);
957 return 0; /* invalid hash value */
960 static u32 decode_caller_hash(void *addr)
964 /* 41 ba 78 56 34 12 mov $0x12345678,%r10d */
965 if (p[0] == 0x41 && p[1] == 0xba)
966 return -*(u32 *)(addr + 2);
968 /* e8 0c 78 56 34 12 jmp.d8 +12 */
969 if (p[0] == JMP8_INSN_OPCODE && p[1] == fineibt_caller_jmp)
970 return -*(u32 *)(addr + 2);
972 return 0; /* invalid hash value */
975 /* .retpoline_sites */
976 static int cfi_disable_callers(s32 *start, s32 *end)
979 * Disable kCFI by patching in a JMP.d8, this leaves the hash immediate
980 * in tact for later usage. Also see decode_caller_hash() and
981 * cfi_rewrite_callers().
983 const u8 jmp[] = { JMP8_INSN_OPCODE, fineibt_caller_jmp };
986 for (s = start; s < end; s++) {
987 void *addr = (void *)s + *s;
990 addr -= fineibt_caller_size;
991 hash = decode_caller_hash(addr);
992 if (!hash) /* nocfi callers */
995 text_poke_early(addr, jmp, 2);
1001 static int cfi_enable_callers(s32 *start, s32 *end)
1004 * Re-enable kCFI, undo what cfi_disable_callers() did.
1006 const u8 mov[] = { 0x41, 0xba };
1009 for (s = start; s < end; s++) {
1010 void *addr = (void *)s + *s;
1013 addr -= fineibt_caller_size;
1014 hash = decode_caller_hash(addr);
1015 if (!hash) /* nocfi callers */
1018 text_poke_early(addr, mov, 2);
1025 static int cfi_rand_preamble(s32 *start, s32 *end)
1029 for (s = start; s < end; s++) {
1030 void *addr = (void *)s + *s;
1033 hash = decode_preamble_hash(addr);
1034 if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1035 addr, addr, 5, addr))
1038 hash = cfi_rehash(hash);
1039 text_poke_early(addr + 1, &hash, 4);
1045 static int cfi_rewrite_preamble(s32 *start, s32 *end)
1049 for (s = start; s < end; s++) {
1050 void *addr = (void *)s + *s;
1053 hash = decode_preamble_hash(addr);
1054 if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1055 addr, addr, 5, addr))
1058 text_poke_early(addr, fineibt_preamble_start, fineibt_preamble_size);
1059 WARN_ON(*(u32 *)(addr + fineibt_preamble_hash) != 0x12345678);
1060 text_poke_early(addr + fineibt_preamble_hash, &hash, 4);
1066 /* .retpoline_sites */
1067 static int cfi_rand_callers(s32 *start, s32 *end)
1071 for (s = start; s < end; s++) {
1072 void *addr = (void *)s + *s;
1075 addr -= fineibt_caller_size;
1076 hash = decode_caller_hash(addr);
1078 hash = -cfi_rehash(hash);
1079 text_poke_early(addr + 2, &hash, 4);
1086 static int cfi_rewrite_callers(s32 *start, s32 *end)
1090 for (s = start; s < end; s++) {
1091 void *addr = (void *)s + *s;
1094 addr -= fineibt_caller_size;
1095 hash = decode_caller_hash(addr);
1097 text_poke_early(addr, fineibt_caller_start, fineibt_caller_size);
1098 WARN_ON(*(u32 *)(addr + fineibt_caller_hash) != 0x12345678);
1099 text_poke_early(addr + fineibt_caller_hash, &hash, 4);
1101 /* rely on apply_retpolines() */
1107 static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1108 s32 *start_cfi, s32 *end_cfi, bool builtin)
1112 if (WARN_ONCE(fineibt_preamble_size != 16,
1113 "FineIBT preamble wrong size: %ld", fineibt_preamble_size))
1116 if (cfi_mode == CFI_DEFAULT) {
1117 cfi_mode = CFI_KCFI;
1118 if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT))
1119 cfi_mode = CFI_FINEIBT;
1123 * Rewrite the callers to not use the __cfi_ stubs, such that we might
1124 * rewrite them. This disables all CFI. If this succeeds but any of the
1125 * later stages fails, we're without CFI.
1127 ret = cfi_disable_callers(start_retpoline, end_retpoline);
1133 cfi_seed = get_random_u32();
1135 ret = cfi_rand_preamble(start_cfi, end_cfi);
1139 ret = cfi_rand_callers(start_retpoline, end_retpoline);
1147 pr_info("Disabling CFI\n");
1151 ret = cfi_enable_callers(start_retpoline, end_retpoline);
1156 pr_info("Using kCFI\n");
1160 ret = cfi_rewrite_preamble(start_cfi, end_cfi);
1164 ret = cfi_rewrite_callers(start_retpoline, end_retpoline);
1169 pr_info("Using FineIBT CFI\n");
1177 pr_err("Something went horribly wrong trying to rewrite the CFI implementation.\n");
1182 static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1183 s32 *start_cfi, s32 *end_cfi, bool builtin)
1189 void apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1190 s32 *start_cfi, s32 *end_cfi)
1192 return __apply_fineibt(start_retpoline, end_retpoline,
1194 /* .builtin = */ false);
1198 static void alternatives_smp_lock(const s32 *start, const s32 *end,
1199 u8 *text, u8 *text_end)
1203 for (poff = start; poff < end; poff++) {
1204 u8 *ptr = (u8 *)poff + *poff;
1206 if (!*poff || ptr < text || ptr >= text_end)
1208 /* turn DS segment override prefix into lock prefix */
1210 text_poke(ptr, ((unsigned char []){0xf0}), 1);
1214 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
1215 u8 *text, u8 *text_end)
1219 for (poff = start; poff < end; poff++) {
1220 u8 *ptr = (u8 *)poff + *poff;
1222 if (!*poff || ptr < text || ptr >= text_end)
1224 /* turn lock prefix into DS segment override prefix */
1226 text_poke(ptr, ((unsigned char []){0x3E}), 1);
1230 struct smp_alt_module {
1231 /* what is this ??? */
1235 /* ptrs to lock prefixes */
1237 const s32 *locks_end;
1239 /* .text segment, needed to avoid patching init code ;) */
1243 struct list_head next;
1245 static LIST_HEAD(smp_alt_modules);
1246 static bool uniproc_patched = false; /* protected by text_mutex */
1248 void __init_or_module alternatives_smp_module_add(struct module *mod,
1250 void *locks, void *locks_end,
1251 void *text, void *text_end)
1253 struct smp_alt_module *smp;
1255 mutex_lock(&text_mutex);
1256 if (!uniproc_patched)
1259 if (num_possible_cpus() == 1)
1260 /* Don't bother remembering, we'll never have to undo it. */
1263 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
1265 /* we'll run the (safe but slow) SMP code then ... */
1271 smp->locks_end = locks_end;
1273 smp->text_end = text_end;
1274 DPRINTK(SMP, "locks %p -> %p, text %p -> %p, name %s\n",
1275 smp->locks, smp->locks_end,
1276 smp->text, smp->text_end, smp->name);
1278 list_add_tail(&smp->next, &smp_alt_modules);
1280 alternatives_smp_unlock(locks, locks_end, text, text_end);
1282 mutex_unlock(&text_mutex);
1285 void __init_or_module alternatives_smp_module_del(struct module *mod)
1287 struct smp_alt_module *item;
1289 mutex_lock(&text_mutex);
1290 list_for_each_entry(item, &smp_alt_modules, next) {
1291 if (mod != item->mod)
1293 list_del(&item->next);
1297 mutex_unlock(&text_mutex);
1300 void alternatives_enable_smp(void)
1302 struct smp_alt_module *mod;
1304 /* Why bother if there are no other CPUs? */
1305 BUG_ON(num_possible_cpus() == 1);
1307 mutex_lock(&text_mutex);
1309 if (uniproc_patched) {
1310 pr_info("switching to SMP code\n");
1311 BUG_ON(num_online_cpus() != 1);
1312 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
1313 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
1314 list_for_each_entry(mod, &smp_alt_modules, next)
1315 alternatives_smp_lock(mod->locks, mod->locks_end,
1316 mod->text, mod->text_end);
1317 uniproc_patched = false;
1319 mutex_unlock(&text_mutex);
1323 * Return 1 if the address range is reserved for SMP-alternatives.
1324 * Must hold text_mutex.
1326 int alternatives_text_reserved(void *start, void *end)
1328 struct smp_alt_module *mod;
1330 u8 *text_start = start;
1333 lockdep_assert_held(&text_mutex);
1335 list_for_each_entry(mod, &smp_alt_modules, next) {
1336 if (mod->text > text_end || mod->text_end < text_start)
1338 for (poff = mod->locks; poff < mod->locks_end; poff++) {
1339 const u8 *ptr = (const u8 *)poff + *poff;
1341 if (text_start <= ptr && text_end > ptr)
1348 #endif /* CONFIG_SMP */
1350 #ifdef CONFIG_PARAVIRT
1352 /* Use this to add nops to a buffer, then text_poke the whole buffer. */
1353 static void __init_or_module add_nops(void *insns, unsigned int len)
1356 unsigned int noplen = len;
1357 if (noplen > ASM_NOP_MAX)
1358 noplen = ASM_NOP_MAX;
1359 memcpy(insns, x86_nops[noplen], noplen);
1365 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
1366 struct paravirt_patch_site *end)
1368 struct paravirt_patch_site *p;
1369 char insn_buff[MAX_PATCH_LEN];
1371 for (p = start; p < end; p++) {
1374 BUG_ON(p->len > MAX_PATCH_LEN);
1375 /* prep the buffer with the original instructions */
1376 memcpy(insn_buff, p->instr, p->len);
1377 used = paravirt_patch(p->type, insn_buff, (unsigned long)p->instr, p->len);
1379 BUG_ON(used > p->len);
1381 /* Pad the rest with nops */
1382 add_nops(insn_buff + used, p->len - used);
1383 text_poke_early(p->instr, insn_buff, p->len);
1386 extern struct paravirt_patch_site __start_parainstructions[],
1387 __stop_parainstructions[];
1388 #endif /* CONFIG_PARAVIRT */
1391 * Self-test for the INT3 based CALL emulation code.
1393 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
1394 * properly and that there is a stack gap between the INT3 frame and the
1395 * previous context. Without this gap doing a virtual PUSH on the interrupted
1396 * stack would corrupt the INT3 IRET frame.
1398 * See entry_{32,64}.S for more details.
1402 * We define the int3_magic() function in assembly to control the calling
1403 * convention such that we can 'call' it from assembly.
1406 extern void int3_magic(unsigned int *ptr); /* defined in asm */
1409 " .pushsection .init.text, \"ax\", @progbits\n"
1410 " .type int3_magic, @function\n"
1413 " movl $1, (%" _ASM_ARG1 ")\n"
1415 " .size int3_magic, .-int3_magic\n"
1419 extern void int3_selftest_ip(void); /* defined in asm below */
1422 int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
1424 unsigned long selftest = (unsigned long)&int3_selftest_ip;
1425 struct die_args *args = data;
1426 struct pt_regs *regs = args->regs;
1428 OPTIMIZER_HIDE_VAR(selftest);
1430 if (!regs || user_mode(regs))
1433 if (val != DIE_INT3)
1436 if (regs->ip - INT3_INSN_SIZE != selftest)
1439 int3_emulate_call(regs, (unsigned long)&int3_magic);
1443 /* Must be noinline to ensure uniqueness of int3_selftest_ip. */
1444 static noinline void __init int3_selftest(void)
1446 static __initdata struct notifier_block int3_exception_nb = {
1447 .notifier_call = int3_exception_notify,
1448 .priority = INT_MAX-1, /* last */
1450 unsigned int val = 0;
1452 BUG_ON(register_die_notifier(&int3_exception_nb));
1455 * Basically: int3_magic(&val); but really complicated :-)
1457 * INT3 padded with NOP to CALL_INSN_SIZE. The int3_exception_nb
1458 * notifier above will emulate CALL for us.
1460 asm volatile ("int3_selftest_ip:\n\t"
1462 " int3; nop; nop; nop; nop\n\t"
1463 : ASM_CALL_CONSTRAINT
1464 : __ASM_SEL_RAW(a, D) (&val)
1469 unregister_die_notifier(&int3_exception_nb);
1472 static __initdata int __alt_reloc_selftest_addr;
1474 __visible noinline void __init __alt_reloc_selftest(void *arg)
1476 WARN_ON(arg != &__alt_reloc_selftest_addr);
1479 static noinline void __init alt_reloc_selftest(void)
1482 * Tests apply_relocation().
1484 * This has a relative immediate (CALL) in a place other than the first
1485 * instruction and additionally on x86_64 we get a RIP-relative LEA:
1487 * lea 0x0(%rip),%rdi # 5d0: R_X86_64_PC32 .init.data+0x5566c
1488 * call +0 # 5d5: R_X86_64_PLT32 __alt_reloc_selftest-0x4
1490 * Getting this wrong will either crash and burn or tickle the WARN
1493 asm_inline volatile (
1494 ALTERNATIVE("", "lea %[mem], %%" _ASM_ARG1 "; call __alt_reloc_selftest;", X86_FEATURE_ALWAYS)
1496 : [mem] "m" (__alt_reloc_selftest_addr)
1501 void __init alternative_instructions(void)
1506 * The patching is not fully atomic, so try to avoid local
1507 * interruptions that might execute the to be patched code.
1508 * Other CPUs are not running.
1513 * Don't stop machine check exceptions while patching.
1514 * MCEs only happen when something got corrupted and in this
1515 * case we must do something about the corruption.
1516 * Ignoring it is worse than an unlikely patching race.
1517 * Also machine checks tend to be broadcast and if one CPU
1518 * goes into machine check the others follow quickly, so we don't
1519 * expect a machine check to cause undue problems during to code
1524 * Paravirt patching and alternative patching can be combined to
1525 * replace a function call with a short direct code sequence (e.g.
1526 * by setting a constant return value instead of doing that in an
1527 * external function).
1528 * In order to make this work the following sequence is required:
1529 * 1. set (artificial) features depending on used paravirt
1530 * functions which can later influence alternative patching
1531 * 2. apply paravirt patching (generally replacing an indirect
1532 * function call with a direct one)
1533 * 3. apply alternative patching (e.g. replacing a direct function
1534 * call with a custom code sequence)
1535 * Doing paravirt patching after alternative patching would clobber
1536 * the optimization of the custom code with a function call again.
1541 * First patch paravirt functions, such that we overwrite the indirect
1542 * call with the direct call.
1544 apply_paravirt(__parainstructions, __parainstructions_end);
1546 __apply_fineibt(__retpoline_sites, __retpoline_sites_end,
1547 __cfi_sites, __cfi_sites_end, true);
1550 * Rewrite the retpolines, must be done before alternatives since
1551 * those can rewrite the retpoline thunks.
1553 apply_retpolines(__retpoline_sites, __retpoline_sites_end);
1554 apply_returns(__return_sites, __return_sites_end);
1557 * Then patch alternatives, such that those paravirt calls that are in
1558 * alternatives can be overwritten by their immediate fragments.
1560 apply_alternatives(__alt_instructions, __alt_instructions_end);
1563 * Now all calls are established. Apply the call thunks if
1566 callthunks_patch_builtin_calls();
1568 apply_ibt_endbr(__ibt_endbr_seal, __ibt_endbr_seal_end);
1571 /* Patch to UP if other cpus not imminent. */
1572 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
1573 uniproc_patched = true;
1574 alternatives_smp_module_add(NULL, "core kernel",
1575 __smp_locks, __smp_locks_end,
1579 if (!uniproc_patched || num_possible_cpus() == 1) {
1580 free_init_pages("SMP alternatives",
1581 (unsigned long)__smp_locks,
1582 (unsigned long)__smp_locks_end);
1587 alternatives_patched = 1;
1589 alt_reloc_selftest();
1593 * text_poke_early - Update instructions on a live kernel at boot time
1594 * @addr: address to modify
1595 * @opcode: source of the copy
1596 * @len: length to copy
1598 * When you use this code to patch more than one byte of an instruction
1599 * you need to make sure that other CPUs cannot execute this code in parallel.
1600 * Also no thread must be currently preempted in the middle of these
1601 * instructions. And on the local CPU you need to be protected against NMI or
1602 * MCE handlers seeing an inconsistent instruction while you patch.
1604 void __init_or_module text_poke_early(void *addr, const void *opcode,
1607 unsigned long flags;
1609 if (boot_cpu_has(X86_FEATURE_NX) &&
1610 is_module_text_address((unsigned long)addr)) {
1612 * Modules text is marked initially as non-executable, so the
1613 * code cannot be running and speculative code-fetches are
1614 * prevented. Just change the code.
1616 memcpy(addr, opcode, len);
1618 local_irq_save(flags);
1619 memcpy(addr, opcode, len);
1620 local_irq_restore(flags);
1624 * Could also do a CLFLUSH here to speed up CPU recovery; but
1625 * that causes hangs on some VIA CPUs.
1631 struct mm_struct *mm;
1635 * Using a temporary mm allows to set temporary mappings that are not accessible
1636 * by other CPUs. Such mappings are needed to perform sensitive memory writes
1637 * that override the kernel memory protections (e.g., W^X), without exposing the
1638 * temporary page-table mappings that are required for these write operations to
1639 * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
1640 * mapping is torn down.
1642 * Context: The temporary mm needs to be used exclusively by a single core. To
1643 * harden security IRQs must be disabled while the temporary mm is
1644 * loaded, thereby preventing interrupt handler bugs from overriding
1645 * the kernel memory protection.
1647 static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
1649 temp_mm_state_t temp_state;
1651 lockdep_assert_irqs_disabled();
1654 * Make sure not to be in TLB lazy mode, as otherwise we'll end up
1655 * with a stale address space WITHOUT being in lazy mode after
1656 * restoring the previous mm.
1658 if (this_cpu_read(cpu_tlbstate_shared.is_lazy))
1659 leave_mm(smp_processor_id());
1661 temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
1662 switch_mm_irqs_off(NULL, mm, current);
1665 * If breakpoints are enabled, disable them while the temporary mm is
1666 * used. Userspace might set up watchpoints on addresses that are used
1667 * in the temporary mm, which would lead to wrong signals being sent or
1670 * Note that breakpoints are not disabled selectively, which also causes
1671 * kernel breakpoints (e.g., perf's) to be disabled. This might be
1672 * undesirable, but still seems reasonable as the code that runs in the
1673 * temporary mm should be short.
1675 if (hw_breakpoint_active())
1676 hw_breakpoint_disable();
1681 static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
1683 lockdep_assert_irqs_disabled();
1684 switch_mm_irqs_off(NULL, prev_state.mm, current);
1687 * Restore the breakpoints if they were disabled before the temporary mm
1690 if (hw_breakpoint_active())
1691 hw_breakpoint_restore();
1694 __ro_after_init struct mm_struct *poking_mm;
1695 __ro_after_init unsigned long poking_addr;
1697 static void text_poke_memcpy(void *dst, const void *src, size_t len)
1699 memcpy(dst, src, len);
1702 static void text_poke_memset(void *dst, const void *src, size_t len)
1704 int c = *(const int *)src;
1706 memset(dst, c, len);
1709 typedef void text_poke_f(void *dst, const void *src, size_t len);
1711 static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t len)
1713 bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
1714 struct page *pages[2] = {NULL};
1715 temp_mm_state_t prev;
1716 unsigned long flags;
1722 * While boot memory allocator is running we cannot use struct pages as
1723 * they are not yet initialized. There is no way to recover.
1725 BUG_ON(!after_bootmem);
1727 if (!core_kernel_text((unsigned long)addr)) {
1728 pages[0] = vmalloc_to_page(addr);
1729 if (cross_page_boundary)
1730 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
1732 pages[0] = virt_to_page(addr);
1733 WARN_ON(!PageReserved(pages[0]));
1734 if (cross_page_boundary)
1735 pages[1] = virt_to_page(addr + PAGE_SIZE);
1738 * If something went wrong, crash and burn since recovery paths are not
1741 BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
1744 * Map the page without the global bit, as TLB flushing is done with
1745 * flush_tlb_mm_range(), which is intended for non-global PTEs.
1747 pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
1750 * The lock is not really needed, but this allows to avoid open-coding.
1752 ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
1755 * This must not fail; preallocated in poking_init().
1759 local_irq_save(flags);
1761 pte = mk_pte(pages[0], pgprot);
1762 set_pte_at(poking_mm, poking_addr, ptep, pte);
1764 if (cross_page_boundary) {
1765 pte = mk_pte(pages[1], pgprot);
1766 set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
1770 * Loading the temporary mm behaves as a compiler barrier, which
1771 * guarantees that the PTE will be set at the time memcpy() is done.
1773 prev = use_temporary_mm(poking_mm);
1775 kasan_disable_current();
1776 func((u8 *)poking_addr + offset_in_page(addr), src, len);
1777 kasan_enable_current();
1780 * Ensure that the PTE is only cleared after the instructions of memcpy
1781 * were issued by using a compiler barrier.
1785 pte_clear(poking_mm, poking_addr, ptep);
1786 if (cross_page_boundary)
1787 pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
1790 * Loading the previous page-table hierarchy requires a serializing
1791 * instruction that already allows the core to see the updated version.
1792 * Xen-PV is assumed to serialize execution in a similar manner.
1794 unuse_temporary_mm(prev);
1797 * Flushing the TLB might involve IPIs, which would require enabled
1798 * IRQs, but not if the mm is not used, as it is in this point.
1800 flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
1801 (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
1804 if (func == text_poke_memcpy) {
1806 * If the text does not match what we just wrote then something is
1807 * fundamentally screwy; there's nothing we can really do about that.
1809 BUG_ON(memcmp(addr, src, len));
1812 local_irq_restore(flags);
1813 pte_unmap_unlock(ptep, ptl);
1818 * text_poke - Update instructions on a live kernel
1819 * @addr: address to modify
1820 * @opcode: source of the copy
1821 * @len: length to copy
1823 * Only atomic text poke/set should be allowed when not doing early patching.
1824 * It means the size must be writable atomically and the address must be aligned
1825 * in a way that permits an atomic write. It also makes sure we fit on a single
1828 * Note that the caller must ensure that if the modified code is part of a
1829 * module, the module would not be removed during poking. This can be achieved
1830 * by registering a module notifier, and ordering module removal and patching
1833 void *text_poke(void *addr, const void *opcode, size_t len)
1835 lockdep_assert_held(&text_mutex);
1837 return __text_poke(text_poke_memcpy, addr, opcode, len);
1841 * text_poke_kgdb - Update instructions on a live kernel by kgdb
1842 * @addr: address to modify
1843 * @opcode: source of the copy
1844 * @len: length to copy
1846 * Only atomic text poke/set should be allowed when not doing early patching.
1847 * It means the size must be writable atomically and the address must be aligned
1848 * in a way that permits an atomic write. It also makes sure we fit on a single
1851 * Context: should only be used by kgdb, which ensures no other core is running,
1852 * despite the fact it does not hold the text_mutex.
1854 void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
1856 return __text_poke(text_poke_memcpy, addr, opcode, len);
1859 void *text_poke_copy_locked(void *addr, const void *opcode, size_t len,
1862 unsigned long start = (unsigned long)addr;
1865 if (WARN_ON_ONCE(!core_ok && core_kernel_text(start)))
1868 while (patched < len) {
1869 unsigned long ptr = start + patched;
1872 s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
1874 __text_poke(text_poke_memcpy, (void *)ptr, opcode + patched, s);
1881 * text_poke_copy - Copy instructions into (an unused part of) RX memory
1882 * @addr: address to modify
1883 * @opcode: source of the copy
1884 * @len: length to copy, could be more than 2x PAGE_SIZE
1886 * Not safe against concurrent execution; useful for JITs to dump
1887 * new code blocks into unused regions of RX memory. Can be used in
1888 * conjunction with synchronize_rcu_tasks() to wait for existing
1889 * execution to quiesce after having made sure no existing functions
1890 * pointers are live.
1892 void *text_poke_copy(void *addr, const void *opcode, size_t len)
1894 mutex_lock(&text_mutex);
1895 addr = text_poke_copy_locked(addr, opcode, len, false);
1896 mutex_unlock(&text_mutex);
1901 * text_poke_set - memset into (an unused part of) RX memory
1902 * @addr: address to modify
1903 * @c: the byte to fill the area with
1904 * @len: length to copy, could be more than 2x PAGE_SIZE
1906 * This is useful to overwrite unused regions of RX memory with illegal
1909 void *text_poke_set(void *addr, int c, size_t len)
1911 unsigned long start = (unsigned long)addr;
1914 if (WARN_ON_ONCE(core_kernel_text(start)))
1917 mutex_lock(&text_mutex);
1918 while (patched < len) {
1919 unsigned long ptr = start + patched;
1922 s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
1924 __text_poke(text_poke_memset, (void *)ptr, (void *)&c, s);
1927 mutex_unlock(&text_mutex);
1931 static void do_sync_core(void *info)
1936 void text_poke_sync(void)
1938 on_each_cpu(do_sync_core, NULL, 1);
1942 * NOTE: crazy scheme to allow patching Jcc.d32 but not increase the size of
1943 * this thing. When len == 6 everything is prefixed with 0x0f and we map
1944 * opcode to Jcc.d8, using len to distinguish.
1946 struct text_poke_loc {
1947 /* addr := _stext + rel_addr */
1952 const u8 text[POKE_MAX_OPCODE_SIZE];
1953 /* see text_poke_bp_batch() */
1957 struct bp_patching_desc {
1958 struct text_poke_loc *vec;
1963 static struct bp_patching_desc bp_desc;
1965 static __always_inline
1966 struct bp_patching_desc *try_get_desc(void)
1968 struct bp_patching_desc *desc = &bp_desc;
1970 if (!raw_atomic_inc_not_zero(&desc->refs))
1976 static __always_inline void put_desc(void)
1978 struct bp_patching_desc *desc = &bp_desc;
1980 smp_mb__before_atomic();
1981 raw_atomic_dec(&desc->refs);
1984 static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
1986 return _stext + tp->rel_addr;
1989 static __always_inline int patch_cmp(const void *key, const void *elt)
1991 struct text_poke_loc *tp = (struct text_poke_loc *) elt;
1993 if (key < text_poke_addr(tp))
1995 if (key > text_poke_addr(tp))
2000 noinstr int poke_int3_handler(struct pt_regs *regs)
2002 struct bp_patching_desc *desc;
2003 struct text_poke_loc *tp;
2007 if (user_mode(regs))
2011 * Having observed our INT3 instruction, we now must observe
2012 * bp_desc with non-zero refcount:
2014 * bp_desc.refs = 1 INT3
2016 * write INT3 if (bp_desc.refs != 0)
2020 desc = try_get_desc();
2025 * Discount the INT3. See text_poke_bp_batch().
2027 ip = (void *) regs->ip - INT3_INSN_SIZE;
2030 * Skip the binary search if there is a single member in the vector.
2032 if (unlikely(desc->nr_entries > 1)) {
2033 tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
2034 sizeof(struct text_poke_loc),
2040 if (text_poke_addr(tp) != ip)
2046 switch (tp->opcode) {
2047 case INT3_INSN_OPCODE:
2049 * Someone poked an explicit INT3, they'll want to handle it,
2054 case RET_INSN_OPCODE:
2055 int3_emulate_ret(regs);
2058 case CALL_INSN_OPCODE:
2059 int3_emulate_call(regs, (long)ip + tp->disp);
2062 case JMP32_INSN_OPCODE:
2063 case JMP8_INSN_OPCODE:
2064 int3_emulate_jmp(regs, (long)ip + tp->disp);
2067 case 0x70 ... 0x7f: /* Jcc */
2068 int3_emulate_jcc(regs, tp->opcode & 0xf, (long)ip, tp->disp);
2082 #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
2083 static struct text_poke_loc tp_vec[TP_VEC_MAX];
2084 static int tp_vec_nr;
2087 * text_poke_bp_batch() -- update instructions on live kernel on SMP
2088 * @tp: vector of instructions to patch
2089 * @nr_entries: number of entries in the vector
2091 * Modify multi-byte instruction by using int3 breakpoint on SMP.
2092 * We completely avoid stop_machine() here, and achieve the
2093 * synchronization using int3 breakpoint.
2095 * The way it is done:
2096 * - For each entry in the vector:
2097 * - add a int3 trap to the address that will be patched
2099 * - For each entry in the vector:
2100 * - update all but the first byte of the patched range
2102 * - For each entry in the vector:
2103 * - replace the first byte (int3) by the first byte of
2107 static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
2109 unsigned char int3 = INT3_INSN_OPCODE;
2113 lockdep_assert_held(&text_mutex);
2116 bp_desc.nr_entries = nr_entries;
2119 * Corresponds to the implicit memory barrier in try_get_desc() to
2120 * ensure reading a non-zero refcount provides up to date bp_desc data.
2122 atomic_set_release(&bp_desc.refs, 1);
2125 * Function tracing can enable thousands of places that need to be
2126 * updated. This can take quite some time, and with full kernel debugging
2127 * enabled, this could cause the softlockup watchdog to trigger.
2128 * This function gets called every 256 entries added to be patched.
2129 * Call cond_resched() here to make sure that other tasks can get scheduled
2130 * while processing all the functions being patched.
2135 * Corresponding read barrier in int3 notifier for making sure the
2136 * nr_entries and handler are correctly ordered wrt. patching.
2141 * First step: add a int3 trap to the address that will be patched.
2143 for (i = 0; i < nr_entries; i++) {
2144 tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
2145 text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
2151 * Second step: update all but the first byte of the patched range.
2153 for (do_sync = 0, i = 0; i < nr_entries; i++) {
2154 u8 old[POKE_MAX_OPCODE_SIZE+1] = { tp[i].old, };
2155 u8 _new[POKE_MAX_OPCODE_SIZE+1];
2156 const u8 *new = tp[i].text;
2157 int len = tp[i].len;
2159 if (len - INT3_INSN_SIZE > 0) {
2160 memcpy(old + INT3_INSN_SIZE,
2161 text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
2162 len - INT3_INSN_SIZE);
2166 memcpy(_new + 1, new, 5);
2170 text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
2171 new + INT3_INSN_SIZE,
2172 len - INT3_INSN_SIZE);
2178 * Emit a perf event to record the text poke, primarily to
2179 * support Intel PT decoding which must walk the executable code
2180 * to reconstruct the trace. The flow up to here is:
2183 * - write instruction tail
2184 * At this point the actual control flow will be through the
2185 * INT3 and handler and not hit the old or new instruction.
2186 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
2187 * can still be decoded. Subsequently:
2188 * - emit RECORD_TEXT_POKE with the new instruction
2190 * - write first byte
2192 * So before the text poke event timestamp, the decoder will see
2193 * either the old instruction flow or FUP/TIP of INT3. After the
2194 * text poke event timestamp, the decoder will see either the
2195 * new instruction flow or FUP/TIP of INT3. Thus decoders can
2196 * use the timestamp as the point at which to modify the
2198 * The old instruction is recorded so that the event can be
2199 * processed forwards or backwards.
2201 perf_event_text_poke(text_poke_addr(&tp[i]), old, len, new, len);
2206 * According to Intel, this core syncing is very likely
2207 * not necessary and we'd be safe even without it. But
2208 * better safe than sorry (plus there's not only Intel).
2214 * Third step: replace the first byte (int3) by the first byte of
2217 for (do_sync = 0, i = 0; i < nr_entries; i++) {
2218 u8 byte = tp[i].text[0];
2223 if (byte == INT3_INSN_OPCODE)
2226 text_poke(text_poke_addr(&tp[i]), &byte, INT3_INSN_SIZE);
2234 * Remove and wait for refs to be zero.
2236 if (!atomic_dec_and_test(&bp_desc.refs))
2237 atomic_cond_read_acquire(&bp_desc.refs, !VAL);
2240 static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
2241 const void *opcode, size_t len, const void *emulate)
2248 memcpy((void *)tp->text, opcode+i, len-i);
2252 ret = insn_decode_kernel(&insn, emulate);
2255 tp->rel_addr = addr - (void *)_stext;
2257 tp->opcode = insn.opcode.bytes[0];
2259 if (is_jcc32(&insn)) {
2261 * Map Jcc.d32 onto Jcc.d8 and use len to distinguish.
2263 tp->opcode = insn.opcode.bytes[1] - 0x10;
2266 switch (tp->opcode) {
2267 case RET_INSN_OPCODE:
2268 case JMP32_INSN_OPCODE:
2269 case JMP8_INSN_OPCODE:
2271 * Control flow instructions without implied execution of the
2272 * next instruction can be padded with INT3.
2274 for (i = insn.length; i < len; i++)
2275 BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
2279 BUG_ON(len != insn.length);
2282 switch (tp->opcode) {
2283 case INT3_INSN_OPCODE:
2284 case RET_INSN_OPCODE:
2287 case CALL_INSN_OPCODE:
2288 case JMP32_INSN_OPCODE:
2289 case JMP8_INSN_OPCODE:
2290 case 0x70 ... 0x7f: /* Jcc */
2291 tp->disp = insn.immediate.value;
2294 default: /* assume NOP */
2296 case 2: /* NOP2 -- emulate as JMP8+0 */
2297 BUG_ON(memcmp(emulate, x86_nops[len], len));
2298 tp->opcode = JMP8_INSN_OPCODE;
2302 case 5: /* NOP5 -- emulate as JMP32+0 */
2303 BUG_ON(memcmp(emulate, x86_nops[len], len));
2304 tp->opcode = JMP32_INSN_OPCODE;
2308 default: /* unknown instruction */
2316 * We hard rely on the tp_vec being ordered; ensure this is so by flushing
2319 static bool tp_order_fail(void *addr)
2321 struct text_poke_loc *tp;
2326 if (!addr) /* force */
2329 tp = &tp_vec[tp_vec_nr - 1];
2330 if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
2336 static void text_poke_flush(void *addr)
2338 if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
2339 text_poke_bp_batch(tp_vec, tp_vec_nr);
2344 void text_poke_finish(void)
2346 text_poke_flush(NULL);
2349 void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
2351 struct text_poke_loc *tp;
2353 text_poke_flush(addr);
2355 tp = &tp_vec[tp_vec_nr++];
2356 text_poke_loc_init(tp, addr, opcode, len, emulate);
2360 * text_poke_bp() -- update instructions on live kernel on SMP
2361 * @addr: address to patch
2362 * @opcode: opcode of new instruction
2363 * @len: length to copy
2364 * @emulate: instruction to be emulated
2366 * Update a single instruction with the vector in the stack, avoiding
2367 * dynamically allocated memory. This function should be used when it is
2368 * not possible to allocate memory.
2370 void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
2372 struct text_poke_loc tp;
2374 text_poke_loc_init(&tp, addr, opcode, len, emulate);
2375 text_poke_bp_batch(&tp, 1);