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/mutex.h>
7 #include <linux/list.h>
8 #include <linux/stringify.h>
10 #include <linux/vmalloc.h>
11 #include <linux/memory.h>
12 #include <linux/stop_machine.h>
13 #include <linux/slab.h>
14 #include <linux/kdebug.h>
15 #include <linux/kprobes.h>
16 #include <linux/mmu_context.h>
17 #include <linux/bsearch.h>
18 #include <asm/text-patching.h>
19 #include <asm/alternative.h>
20 #include <asm/sections.h>
21 #include <asm/pgtable.h>
24 #include <asm/cacheflush.h>
25 #include <asm/tlbflush.h>
28 #include <asm/fixmap.h>
30 int __read_mostly alternatives_patched
;
32 EXPORT_SYMBOL_GPL(alternatives_patched
);
34 #define MAX_PATCH_LEN (255-1)
36 static int __initdata_or_module debug_alternative
;
38 static int __init
debug_alt(char *str
)
40 debug_alternative
= 1;
43 __setup("debug-alternative", debug_alt
);
45 static int noreplace_smp
;
47 static int __init
setup_noreplace_smp(char *str
)
52 __setup("noreplace-smp", setup_noreplace_smp
);
54 #define DPRINTK(fmt, args...) \
56 if (debug_alternative) \
57 printk(KERN_DEBUG "%s: " fmt "\n", __func__, ##args); \
60 #define DUMP_BYTES(buf, len, fmt, args...) \
62 if (unlikely(debug_alternative)) { \
68 printk(KERN_DEBUG fmt, ##args); \
69 for (j = 0; j < (len) - 1; j++) \
70 printk(KERN_CONT "%02hhx ", buf[j]); \
71 printk(KERN_CONT "%02hhx\n", buf[j]); \
76 * Each GENERIC_NOPX is of X bytes, and defined as an array of bytes
77 * that correspond to that nop. Getting from one nop to the next, we
78 * add to the array the offset that is equal to the sum of all sizes of
79 * nops preceding the one we are after.
81 * Note: The GENERIC_NOP5_ATOMIC is at the end, as it breaks the
82 * nice symmetry of sizes of the previous nops.
84 #if defined(GENERIC_NOP1) && !defined(CONFIG_X86_64)
85 static const unsigned char intelnops
[] =
97 static const unsigned char * const intel_nops
[ASM_NOP_MAX
+2] =
103 intelnops
+ 1 + 2 + 3,
104 intelnops
+ 1 + 2 + 3 + 4,
105 intelnops
+ 1 + 2 + 3 + 4 + 5,
106 intelnops
+ 1 + 2 + 3 + 4 + 5 + 6,
107 intelnops
+ 1 + 2 + 3 + 4 + 5 + 6 + 7,
108 intelnops
+ 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
113 static const unsigned char k8nops
[] =
125 static const unsigned char * const k8_nops
[ASM_NOP_MAX
+2] =
132 k8nops
+ 1 + 2 + 3 + 4,
133 k8nops
+ 1 + 2 + 3 + 4 + 5,
134 k8nops
+ 1 + 2 + 3 + 4 + 5 + 6,
135 k8nops
+ 1 + 2 + 3 + 4 + 5 + 6 + 7,
136 k8nops
+ 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
140 #if defined(K7_NOP1) && !defined(CONFIG_X86_64)
141 static const unsigned char k7nops
[] =
153 static const unsigned char * const k7_nops
[ASM_NOP_MAX
+2] =
160 k7nops
+ 1 + 2 + 3 + 4,
161 k7nops
+ 1 + 2 + 3 + 4 + 5,
162 k7nops
+ 1 + 2 + 3 + 4 + 5 + 6,
163 k7nops
+ 1 + 2 + 3 + 4 + 5 + 6 + 7,
164 k7nops
+ 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
169 static const unsigned char p6nops
[] =
181 static const unsigned char * const p6_nops
[ASM_NOP_MAX
+2] =
188 p6nops
+ 1 + 2 + 3 + 4,
189 p6nops
+ 1 + 2 + 3 + 4 + 5,
190 p6nops
+ 1 + 2 + 3 + 4 + 5 + 6,
191 p6nops
+ 1 + 2 + 3 + 4 + 5 + 6 + 7,
192 p6nops
+ 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
196 /* Initialize these to a safe default */
198 const unsigned char * const *ideal_nops
= p6_nops
;
200 const unsigned char * const *ideal_nops
= intel_nops
;
203 void __init
arch_init_ideal_nops(void)
205 switch (boot_cpu_data
.x86_vendor
) {
206 case X86_VENDOR_INTEL
:
208 * Due to a decoder implementation quirk, some
209 * specific Intel CPUs actually perform better with
210 * the "k8_nops" than with the SDM-recommended NOPs.
212 if (boot_cpu_data
.x86
== 6 &&
213 boot_cpu_data
.x86_model
>= 0x0f &&
214 boot_cpu_data
.x86_model
!= 0x1c &&
215 boot_cpu_data
.x86_model
!= 0x26 &&
216 boot_cpu_data
.x86_model
!= 0x27 &&
217 boot_cpu_data
.x86_model
< 0x30) {
218 ideal_nops
= k8_nops
;
219 } else if (boot_cpu_has(X86_FEATURE_NOPL
)) {
220 ideal_nops
= p6_nops
;
223 ideal_nops
= k8_nops
;
225 ideal_nops
= intel_nops
;
230 case X86_VENDOR_HYGON
:
231 ideal_nops
= p6_nops
;
235 if (boot_cpu_data
.x86
> 0xf) {
236 ideal_nops
= p6_nops
;
244 ideal_nops
= k8_nops
;
246 if (boot_cpu_has(X86_FEATURE_K8
))
247 ideal_nops
= k8_nops
;
248 else if (boot_cpu_has(X86_FEATURE_K7
))
249 ideal_nops
= k7_nops
;
251 ideal_nops
= intel_nops
;
256 /* Use this to add nops to a buffer, then text_poke the whole buffer. */
257 static void __init_or_module
add_nops(void *insns
, unsigned int len
)
260 unsigned int noplen
= len
;
261 if (noplen
> ASM_NOP_MAX
)
262 noplen
= ASM_NOP_MAX
;
263 memcpy(insns
, ideal_nops
[noplen
], noplen
);
269 extern struct alt_instr __alt_instructions
[], __alt_instructions_end
[];
270 extern s32 __smp_locks
[], __smp_locks_end
[];
271 void text_poke_early(void *addr
, const void *opcode
, size_t len
);
274 * Are we looking at a near JMP with a 1 or 4-byte displacement.
276 static inline bool is_jmp(const u8 opcode
)
278 return opcode
== 0xeb || opcode
== 0xe9;
281 static void __init_or_module
282 recompute_jump(struct alt_instr
*a
, u8
*orig_insn
, u8
*repl_insn
, u8
*insn_buff
)
284 u8
*next_rip
, *tgt_rip
;
288 if (a
->replacementlen
!= 5)
291 o_dspl
= *(s32
*)(insn_buff
+ 1);
293 /* next_rip of the replacement JMP */
294 next_rip
= repl_insn
+ a
->replacementlen
;
295 /* target rip of the replacement JMP */
296 tgt_rip
= next_rip
+ o_dspl
;
297 n_dspl
= tgt_rip
- orig_insn
;
299 DPRINTK("target RIP: %px, new_displ: 0x%x", tgt_rip
, n_dspl
);
301 if (tgt_rip
- orig_insn
>= 0) {
302 if (n_dspl
- 2 <= 127)
306 /* negative offset */
308 if (((n_dspl
- 2) & 0xff) == (n_dspl
- 2))
318 insn_buff
[1] = (s8
)n_dspl
;
319 add_nops(insn_buff
+ 2, 3);
328 *(s32
*)&insn_buff
[1] = n_dspl
;
334 DPRINTK("final displ: 0x%08x, JMP 0x%lx",
335 n_dspl
, (unsigned long)orig_insn
+ n_dspl
+ repl_len
);
339 * "noinline" to cause control flow change and thus invalidate I$ and
340 * cause refetch after modification.
342 static void __init_or_module noinline
optimize_nops(struct alt_instr
*a
, u8
*instr
)
347 for (i
= 0; i
< a
->padlen
; i
++) {
348 if (instr
[i
] != 0x90)
352 local_irq_save(flags
);
353 add_nops(instr
+ (a
->instrlen
- a
->padlen
), a
->padlen
);
354 local_irq_restore(flags
);
356 DUMP_BYTES(instr
, a
->instrlen
, "%px: [%d:%d) optimized NOPs: ",
357 instr
, a
->instrlen
- a
->padlen
, a
->padlen
);
361 * Replace instructions with better alternatives for this CPU type. This runs
362 * before SMP is initialized to avoid SMP problems with self modifying code.
363 * This implies that asymmetric systems where APs have less capabilities than
364 * the boot processor are not handled. Tough. Make sure you disable such
367 * Marked "noinline" to cause control flow change and thus insn cache
368 * to refetch changed I$ lines.
370 void __init_or_module noinline
apply_alternatives(struct alt_instr
*start
,
371 struct alt_instr
*end
)
374 u8
*instr
, *replacement
;
375 u8 insn_buff
[MAX_PATCH_LEN
];
377 DPRINTK("alt table %px, -> %px", start
, end
);
379 * The scan order should be from start to end. A later scanned
380 * alternative code can overwrite previously scanned alternative code.
381 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
384 * So be careful if you want to change the scan order to any other
387 for (a
= start
; a
< end
; a
++) {
388 int insn_buff_sz
= 0;
390 instr
= (u8
*)&a
->instr_offset
+ a
->instr_offset
;
391 replacement
= (u8
*)&a
->repl_offset
+ a
->repl_offset
;
392 BUG_ON(a
->instrlen
> sizeof(insn_buff
));
393 BUG_ON(a
->cpuid
>= (NCAPINTS
+ NBUGINTS
) * 32);
394 if (!boot_cpu_has(a
->cpuid
)) {
396 optimize_nops(a
, instr
);
401 DPRINTK("feat: %d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d), pad: %d",
404 instr
, instr
, a
->instrlen
,
405 replacement
, a
->replacementlen
, a
->padlen
);
407 DUMP_BYTES(instr
, a
->instrlen
, "%px: old_insn: ", instr
);
408 DUMP_BYTES(replacement
, a
->replacementlen
, "%px: rpl_insn: ", replacement
);
410 memcpy(insn_buff
, replacement
, a
->replacementlen
);
411 insn_buff_sz
= a
->replacementlen
;
414 * 0xe8 is a relative jump; fix the offset.
416 * Instruction length is checked before the opcode to avoid
417 * accessing uninitialized bytes for zero-length replacements.
419 if (a
->replacementlen
== 5 && *insn_buff
== 0xe8) {
420 *(s32
*)(insn_buff
+ 1) += replacement
- instr
;
421 DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
422 *(s32
*)(insn_buff
+ 1),
423 (unsigned long)instr
+ *(s32
*)(insn_buff
+ 1) + 5);
426 if (a
->replacementlen
&& is_jmp(replacement
[0]))
427 recompute_jump(a
, instr
, replacement
, insn_buff
);
429 if (a
->instrlen
> a
->replacementlen
) {
430 add_nops(insn_buff
+ a
->replacementlen
,
431 a
->instrlen
- a
->replacementlen
);
432 insn_buff_sz
+= a
->instrlen
- a
->replacementlen
;
434 DUMP_BYTES(insn_buff
, insn_buff_sz
, "%px: final_insn: ", instr
);
436 text_poke_early(instr
, insn_buff
, insn_buff_sz
);
441 static void alternatives_smp_lock(const s32
*start
, const s32
*end
,
442 u8
*text
, u8
*text_end
)
446 for (poff
= start
; poff
< end
; poff
++) {
447 u8
*ptr
= (u8
*)poff
+ *poff
;
449 if (!*poff
|| ptr
< text
|| ptr
>= text_end
)
451 /* turn DS segment override prefix into lock prefix */
453 text_poke(ptr
, ((unsigned char []){0xf0}), 1);
457 static void alternatives_smp_unlock(const s32
*start
, const s32
*end
,
458 u8
*text
, u8
*text_end
)
462 for (poff
= start
; poff
< end
; poff
++) {
463 u8
*ptr
= (u8
*)poff
+ *poff
;
465 if (!*poff
|| ptr
< text
|| ptr
>= text_end
)
467 /* turn lock prefix into DS segment override prefix */
469 text_poke(ptr
, ((unsigned char []){0x3E}), 1);
473 struct smp_alt_module
{
474 /* what is this ??? */
478 /* ptrs to lock prefixes */
480 const s32
*locks_end
;
482 /* .text segment, needed to avoid patching init code ;) */
486 struct list_head next
;
488 static LIST_HEAD(smp_alt_modules
);
489 static bool uniproc_patched
= false; /* protected by text_mutex */
491 void __init_or_module
alternatives_smp_module_add(struct module
*mod
,
493 void *locks
, void *locks_end
,
494 void *text
, void *text_end
)
496 struct smp_alt_module
*smp
;
498 mutex_lock(&text_mutex
);
499 if (!uniproc_patched
)
502 if (num_possible_cpus() == 1)
503 /* Don't bother remembering, we'll never have to undo it. */
506 smp
= kzalloc(sizeof(*smp
), GFP_KERNEL
);
508 /* we'll run the (safe but slow) SMP code then ... */
514 smp
->locks_end
= locks_end
;
516 smp
->text_end
= text_end
;
517 DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
518 smp
->locks
, smp
->locks_end
,
519 smp
->text
, smp
->text_end
, smp
->name
);
521 list_add_tail(&smp
->next
, &smp_alt_modules
);
523 alternatives_smp_unlock(locks
, locks_end
, text
, text_end
);
525 mutex_unlock(&text_mutex
);
528 void __init_or_module
alternatives_smp_module_del(struct module
*mod
)
530 struct smp_alt_module
*item
;
532 mutex_lock(&text_mutex
);
533 list_for_each_entry(item
, &smp_alt_modules
, next
) {
534 if (mod
!= item
->mod
)
536 list_del(&item
->next
);
540 mutex_unlock(&text_mutex
);
543 void alternatives_enable_smp(void)
545 struct smp_alt_module
*mod
;
547 /* Why bother if there are no other CPUs? */
548 BUG_ON(num_possible_cpus() == 1);
550 mutex_lock(&text_mutex
);
552 if (uniproc_patched
) {
553 pr_info("switching to SMP code\n");
554 BUG_ON(num_online_cpus() != 1);
555 clear_cpu_cap(&boot_cpu_data
, X86_FEATURE_UP
);
556 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP
);
557 list_for_each_entry(mod
, &smp_alt_modules
, next
)
558 alternatives_smp_lock(mod
->locks
, mod
->locks_end
,
559 mod
->text
, mod
->text_end
);
560 uniproc_patched
= false;
562 mutex_unlock(&text_mutex
);
566 * Return 1 if the address range is reserved for SMP-alternatives.
567 * Must hold text_mutex.
569 int alternatives_text_reserved(void *start
, void *end
)
571 struct smp_alt_module
*mod
;
573 u8
*text_start
= start
;
576 lockdep_assert_held(&text_mutex
);
578 list_for_each_entry(mod
, &smp_alt_modules
, next
) {
579 if (mod
->text
> text_end
|| mod
->text_end
< text_start
)
581 for (poff
= mod
->locks
; poff
< mod
->locks_end
; poff
++) {
582 const u8
*ptr
= (const u8
*)poff
+ *poff
;
584 if (text_start
<= ptr
&& text_end
> ptr
)
591 #endif /* CONFIG_SMP */
593 #ifdef CONFIG_PARAVIRT
594 void __init_or_module
apply_paravirt(struct paravirt_patch_site
*start
,
595 struct paravirt_patch_site
*end
)
597 struct paravirt_patch_site
*p
;
598 char insn_buff
[MAX_PATCH_LEN
];
600 for (p
= start
; p
< end
; p
++) {
603 BUG_ON(p
->len
> MAX_PATCH_LEN
);
604 /* prep the buffer with the original instructions */
605 memcpy(insn_buff
, p
->instr
, p
->len
);
606 used
= pv_ops
.init
.patch(p
->type
, insn_buff
, (unsigned long)p
->instr
, p
->len
);
608 BUG_ON(used
> p
->len
);
610 /* Pad the rest with nops */
611 add_nops(insn_buff
+ used
, p
->len
- used
);
612 text_poke_early(p
->instr
, insn_buff
, p
->len
);
615 extern struct paravirt_patch_site __start_parainstructions
[],
616 __stop_parainstructions
[];
617 #endif /* CONFIG_PARAVIRT */
620 * Self-test for the INT3 based CALL emulation code.
622 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
623 * properly and that there is a stack gap between the INT3 frame and the
624 * previous context. Without this gap doing a virtual PUSH on the interrupted
625 * stack would corrupt the INT3 IRET frame.
627 * See entry_{32,64}.S for more details.
631 * We define the int3_magic() function in assembly to control the calling
632 * convention such that we can 'call' it from assembly.
635 extern void int3_magic(unsigned int *ptr
); /* defined in asm */
638 " .pushsection .init.text, \"ax\", @progbits\n"
639 " .type int3_magic, @function\n"
641 " movl $1, (%" _ASM_ARG1
")\n"
643 " .size int3_magic, .-int3_magic\n"
647 extern __initdata
unsigned long int3_selftest_ip
; /* defined in asm below */
650 int3_exception_notify(struct notifier_block
*self
, unsigned long val
, void *data
)
652 struct die_args
*args
= data
;
653 struct pt_regs
*regs
= args
->regs
;
655 if (!regs
|| user_mode(regs
))
661 if (regs
->ip
- INT3_INSN_SIZE
!= int3_selftest_ip
)
664 int3_emulate_call(regs
, (unsigned long)&int3_magic
);
668 static void __init
int3_selftest(void)
670 static __initdata
struct notifier_block int3_exception_nb
= {
671 .notifier_call
= int3_exception_notify
,
672 .priority
= INT_MAX
-1, /* last */
674 unsigned int val
= 0;
676 BUG_ON(register_die_notifier(&int3_exception_nb
));
679 * Basically: int3_magic(&val); but really complicated :-)
681 * Stick the address of the INT3 instruction into int3_selftest_ip,
682 * then trigger the INT3, padded with NOPs to match a CALL instruction
685 asm volatile ("1: int3; nop; nop; nop; nop\n\t"
686 ".pushsection .init.data,\"aw\"\n\t"
687 ".align " __ASM_SEL(4, 8) "\n\t"
688 ".type int3_selftest_ip, @object\n\t"
689 ".size int3_selftest_ip, " __ASM_SEL(4, 8) "\n\t"
690 "int3_selftest_ip:\n\t"
691 __ASM_SEL(.long, .quad
) " 1b\n\t"
693 : ASM_CALL_CONSTRAINT
694 : __ASM_SEL_RAW(a
, D
) (&val
)
699 unregister_die_notifier(&int3_exception_nb
);
702 void __init
alternative_instructions(void)
707 * The patching is not fully atomic, so try to avoid local
708 * interruptions that might execute the to be patched code.
709 * Other CPUs are not running.
714 * Don't stop machine check exceptions while patching.
715 * MCEs only happen when something got corrupted and in this
716 * case we must do something about the corruption.
717 * Ignoring it is worse than an unlikely patching race.
718 * Also machine checks tend to be broadcast and if one CPU
719 * goes into machine check the others follow quickly, so we don't
720 * expect a machine check to cause undue problems during to code
724 apply_alternatives(__alt_instructions
, __alt_instructions_end
);
727 /* Patch to UP if other cpus not imminent. */
728 if (!noreplace_smp
&& (num_present_cpus() == 1 || setup_max_cpus
<= 1)) {
729 uniproc_patched
= true;
730 alternatives_smp_module_add(NULL
, "core kernel",
731 __smp_locks
, __smp_locks_end
,
735 if (!uniproc_patched
|| num_possible_cpus() == 1) {
736 free_init_pages("SMP alternatives",
737 (unsigned long)__smp_locks
,
738 (unsigned long)__smp_locks_end
);
742 apply_paravirt(__parainstructions
, __parainstructions_end
);
745 alternatives_patched
= 1;
749 * text_poke_early - Update instructions on a live kernel at boot time
750 * @addr: address to modify
751 * @opcode: source of the copy
752 * @len: length to copy
754 * When you use this code to patch more than one byte of an instruction
755 * you need to make sure that other CPUs cannot execute this code in parallel.
756 * Also no thread must be currently preempted in the middle of these
757 * instructions. And on the local CPU you need to be protected against NMI or
758 * MCE handlers seeing an inconsistent instruction while you patch.
760 void __init_or_module
text_poke_early(void *addr
, const void *opcode
,
765 if (boot_cpu_has(X86_FEATURE_NX
) &&
766 is_module_text_address((unsigned long)addr
)) {
768 * Modules text is marked initially as non-executable, so the
769 * code cannot be running and speculative code-fetches are
770 * prevented. Just change the code.
772 memcpy(addr
, opcode
, len
);
774 local_irq_save(flags
);
775 memcpy(addr
, opcode
, len
);
776 local_irq_restore(flags
);
780 * Could also do a CLFLUSH here to speed up CPU recovery; but
781 * that causes hangs on some VIA CPUs.
786 __ro_after_init
struct mm_struct
*poking_mm
;
787 __ro_after_init
unsigned long poking_addr
;
789 static void *__text_poke(void *addr
, const void *opcode
, size_t len
)
791 bool cross_page_boundary
= offset_in_page(addr
) + len
> PAGE_SIZE
;
792 struct page
*pages
[2] = {NULL
};
793 temp_mm_state_t prev
;
800 * While boot memory allocator is running we cannot use struct pages as
801 * they are not yet initialized. There is no way to recover.
803 BUG_ON(!after_bootmem
);
805 if (!core_kernel_text((unsigned long)addr
)) {
806 pages
[0] = vmalloc_to_page(addr
);
807 if (cross_page_boundary
)
808 pages
[1] = vmalloc_to_page(addr
+ PAGE_SIZE
);
810 pages
[0] = virt_to_page(addr
);
811 WARN_ON(!PageReserved(pages
[0]));
812 if (cross_page_boundary
)
813 pages
[1] = virt_to_page(addr
+ PAGE_SIZE
);
816 * If something went wrong, crash and burn since recovery paths are not
819 BUG_ON(!pages
[0] || (cross_page_boundary
&& !pages
[1]));
821 local_irq_save(flags
);
824 * Map the page without the global bit, as TLB flushing is done with
825 * flush_tlb_mm_range(), which is intended for non-global PTEs.
827 pgprot
= __pgprot(pgprot_val(PAGE_KERNEL
) & ~_PAGE_GLOBAL
);
830 * The lock is not really needed, but this allows to avoid open-coding.
832 ptep
= get_locked_pte(poking_mm
, poking_addr
, &ptl
);
835 * This must not fail; preallocated in poking_init().
839 pte
= mk_pte(pages
[0], pgprot
);
840 set_pte_at(poking_mm
, poking_addr
, ptep
, pte
);
842 if (cross_page_boundary
) {
843 pte
= mk_pte(pages
[1], pgprot
);
844 set_pte_at(poking_mm
, poking_addr
+ PAGE_SIZE
, ptep
+ 1, pte
);
848 * Loading the temporary mm behaves as a compiler barrier, which
849 * guarantees that the PTE will be set at the time memcpy() is done.
851 prev
= use_temporary_mm(poking_mm
);
853 kasan_disable_current();
854 memcpy((u8
*)poking_addr
+ offset_in_page(addr
), opcode
, len
);
855 kasan_enable_current();
858 * Ensure that the PTE is only cleared after the instructions of memcpy
859 * were issued by using a compiler barrier.
863 pte_clear(poking_mm
, poking_addr
, ptep
);
864 if (cross_page_boundary
)
865 pte_clear(poking_mm
, poking_addr
+ PAGE_SIZE
, ptep
+ 1);
868 * Loading the previous page-table hierarchy requires a serializing
869 * instruction that already allows the core to see the updated version.
870 * Xen-PV is assumed to serialize execution in a similar manner.
872 unuse_temporary_mm(prev
);
875 * Flushing the TLB might involve IPIs, which would require enabled
876 * IRQs, but not if the mm is not used, as it is in this point.
878 flush_tlb_mm_range(poking_mm
, poking_addr
, poking_addr
+
879 (cross_page_boundary
? 2 : 1) * PAGE_SIZE
,
883 * If the text does not match what we just wrote then something is
884 * fundamentally screwy; there's nothing we can really do about that.
886 BUG_ON(memcmp(addr
, opcode
, len
));
888 pte_unmap_unlock(ptep
, ptl
);
889 local_irq_restore(flags
);
894 * text_poke - Update instructions on a live kernel
895 * @addr: address to modify
896 * @opcode: source of the copy
897 * @len: length to copy
899 * Only atomic text poke/set should be allowed when not doing early patching.
900 * It means the size must be writable atomically and the address must be aligned
901 * in a way that permits an atomic write. It also makes sure we fit on a single
904 * Note that the caller must ensure that if the modified code is part of a
905 * module, the module would not be removed during poking. This can be achieved
906 * by registering a module notifier, and ordering module removal and patching
909 void *text_poke(void *addr
, const void *opcode
, size_t len
)
911 lockdep_assert_held(&text_mutex
);
913 return __text_poke(addr
, opcode
, len
);
917 * text_poke_kgdb - Update instructions on a live kernel by kgdb
918 * @addr: address to modify
919 * @opcode: source of the copy
920 * @len: length to copy
922 * Only atomic text poke/set should be allowed when not doing early patching.
923 * It means the size must be writable atomically and the address must be aligned
924 * in a way that permits an atomic write. It also makes sure we fit on a single
927 * Context: should only be used by kgdb, which ensures no other core is running,
928 * despite the fact it does not hold the text_mutex.
930 void *text_poke_kgdb(void *addr
, const void *opcode
, size_t len
)
932 return __text_poke(addr
, opcode
, len
);
935 static void do_sync_core(void *info
)
940 void text_poke_sync(void)
942 on_each_cpu(do_sync_core
, NULL
, 1);
945 struct text_poke_loc
{
946 s32 rel_addr
; /* addr := _stext + rel_addr */
949 const u8 text
[POKE_MAX_OPCODE_SIZE
];
952 struct bp_patching_desc
{
953 struct text_poke_loc
*vec
;
958 static struct bp_patching_desc
*bp_desc
;
960 static inline struct bp_patching_desc
*try_get_desc(struct bp_patching_desc
**descp
)
962 struct bp_patching_desc
*desc
= READ_ONCE(*descp
); /* rcu_dereference */
964 if (!desc
|| !atomic_inc_not_zero(&desc
->refs
))
970 static inline void put_desc(struct bp_patching_desc
*desc
)
972 smp_mb__before_atomic();
973 atomic_dec(&desc
->refs
);
976 static inline void *text_poke_addr(struct text_poke_loc
*tp
)
978 return _stext
+ tp
->rel_addr
;
981 static int notrace
patch_cmp(const void *key
, const void *elt
)
983 struct text_poke_loc
*tp
= (struct text_poke_loc
*) elt
;
985 if (key
< text_poke_addr(tp
))
987 if (key
> text_poke_addr(tp
))
991 NOKPROBE_SYMBOL(patch_cmp
);
993 int notrace
poke_int3_handler(struct pt_regs
*regs
)
995 struct bp_patching_desc
*desc
;
996 struct text_poke_loc
*tp
;
1000 if (user_mode(regs
))
1004 * Having observed our INT3 instruction, we now must observe
1007 * bp_desc = desc INT3
1009 * write INT3 if (desc)
1013 desc
= try_get_desc(&bp_desc
);
1018 * Discount the INT3. See text_poke_bp_batch().
1020 ip
= (void *) regs
->ip
- INT3_INSN_SIZE
;
1023 * Skip the binary search if there is a single member in the vector.
1025 if (unlikely(desc
->nr_entries
> 1)) {
1026 tp
= bsearch(ip
, desc
->vec
, desc
->nr_entries
,
1027 sizeof(struct text_poke_loc
),
1033 if (text_poke_addr(tp
) != ip
)
1037 len
= text_opcode_size(tp
->opcode
);
1040 switch (tp
->opcode
) {
1041 case INT3_INSN_OPCODE
:
1043 * Someone poked an explicit INT3, they'll want to handle it,
1048 case CALL_INSN_OPCODE
:
1049 int3_emulate_call(regs
, (long)ip
+ tp
->rel32
);
1052 case JMP32_INSN_OPCODE
:
1053 case JMP8_INSN_OPCODE
:
1054 int3_emulate_jmp(regs
, (long)ip
+ tp
->rel32
);
1067 NOKPROBE_SYMBOL(poke_int3_handler
);
1069 #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
1070 static struct text_poke_loc tp_vec
[TP_VEC_MAX
];
1071 static int tp_vec_nr
;
1074 * text_poke_bp_batch() -- update instructions on live kernel on SMP
1075 * @tp: vector of instructions to patch
1076 * @nr_entries: number of entries in the vector
1078 * Modify multi-byte instruction by using int3 breakpoint on SMP.
1079 * We completely avoid stop_machine() here, and achieve the
1080 * synchronization using int3 breakpoint.
1082 * The way it is done:
1083 * - For each entry in the vector:
1084 * - add a int3 trap to the address that will be patched
1086 * - For each entry in the vector:
1087 * - update all but the first byte of the patched range
1089 * - For each entry in the vector:
1090 * - replace the first byte (int3) by the first byte of
1094 static void text_poke_bp_batch(struct text_poke_loc
*tp
, unsigned int nr_entries
)
1096 struct bp_patching_desc desc
= {
1098 .nr_entries
= nr_entries
,
1099 .refs
= ATOMIC_INIT(1),
1101 unsigned char int3
= INT3_INSN_OPCODE
;
1105 lockdep_assert_held(&text_mutex
);
1107 smp_store_release(&bp_desc
, &desc
); /* rcu_assign_pointer */
1110 * Corresponding read barrier in int3 notifier for making sure the
1111 * nr_entries and handler are correctly ordered wrt. patching.
1116 * First step: add a int3 trap to the address that will be patched.
1118 for (i
= 0; i
< nr_entries
; i
++)
1119 text_poke(text_poke_addr(&tp
[i
]), &int3
, INT3_INSN_SIZE
);
1124 * Second step: update all but the first byte of the patched range.
1126 for (do_sync
= 0, i
= 0; i
< nr_entries
; i
++) {
1127 int len
= text_opcode_size(tp
[i
].opcode
);
1129 if (len
- INT3_INSN_SIZE
> 0) {
1130 text_poke(text_poke_addr(&tp
[i
]) + INT3_INSN_SIZE
,
1131 (const char *)tp
[i
].text
+ INT3_INSN_SIZE
,
1132 len
- INT3_INSN_SIZE
);
1139 * According to Intel, this core syncing is very likely
1140 * not necessary and we'd be safe even without it. But
1141 * better safe than sorry (plus there's not only Intel).
1147 * Third step: replace the first byte (int3) by the first byte of
1150 for (do_sync
= 0, i
= 0; i
< nr_entries
; i
++) {
1151 if (tp
[i
].text
[0] == INT3_INSN_OPCODE
)
1154 text_poke(text_poke_addr(&tp
[i
]), tp
[i
].text
, INT3_INSN_SIZE
);
1162 * Remove and synchronize_rcu(), except we have a very primitive
1163 * refcount based completion.
1165 WRITE_ONCE(bp_desc
, NULL
); /* RCU_INIT_POINTER */
1166 if (!atomic_dec_and_test(&desc
.refs
))
1167 atomic_cond_read_acquire(&desc
.refs
, !VAL
);
1170 static void text_poke_loc_init(struct text_poke_loc
*tp
, void *addr
,
1171 const void *opcode
, size_t len
, const void *emulate
)
1175 memcpy((void *)tp
->text
, opcode
, len
);
1179 kernel_insn_init(&insn
, emulate
, MAX_INSN_SIZE
);
1180 insn_get_length(&insn
);
1182 BUG_ON(!insn_complete(&insn
));
1183 BUG_ON(len
!= insn
.length
);
1185 tp
->rel_addr
= addr
- (void *)_stext
;
1186 tp
->opcode
= insn
.opcode
.bytes
[0];
1188 switch (tp
->opcode
) {
1189 case INT3_INSN_OPCODE
:
1192 case CALL_INSN_OPCODE
:
1193 case JMP32_INSN_OPCODE
:
1194 case JMP8_INSN_OPCODE
:
1195 tp
->rel32
= insn
.immediate
.value
;
1198 default: /* assume NOP */
1200 case 2: /* NOP2 -- emulate as JMP8+0 */
1201 BUG_ON(memcmp(emulate
, ideal_nops
[len
], len
));
1202 tp
->opcode
= JMP8_INSN_OPCODE
;
1206 case 5: /* NOP5 -- emulate as JMP32+0 */
1207 BUG_ON(memcmp(emulate
, ideal_nops
[NOP_ATOMIC5
], len
));
1208 tp
->opcode
= JMP32_INSN_OPCODE
;
1212 default: /* unknown instruction */
1220 * We hard rely on the tp_vec being ordered; ensure this is so by flushing
1223 static bool tp_order_fail(void *addr
)
1225 struct text_poke_loc
*tp
;
1230 if (!addr
) /* force */
1233 tp
= &tp_vec
[tp_vec_nr
- 1];
1234 if ((unsigned long)text_poke_addr(tp
) > (unsigned long)addr
)
1240 static void text_poke_flush(void *addr
)
1242 if (tp_vec_nr
== TP_VEC_MAX
|| tp_order_fail(addr
)) {
1243 text_poke_bp_batch(tp_vec
, tp_vec_nr
);
1248 void text_poke_finish(void)
1250 text_poke_flush(NULL
);
1253 void __ref
text_poke_queue(void *addr
, const void *opcode
, size_t len
, const void *emulate
)
1255 struct text_poke_loc
*tp
;
1257 if (unlikely(system_state
== SYSTEM_BOOTING
)) {
1258 text_poke_early(addr
, opcode
, len
);
1262 text_poke_flush(addr
);
1264 tp
= &tp_vec
[tp_vec_nr
++];
1265 text_poke_loc_init(tp
, addr
, opcode
, len
, emulate
);
1269 * text_poke_bp() -- update instructions on live kernel on SMP
1270 * @addr: address to patch
1271 * @opcode: opcode of new instruction
1272 * @len: length to copy
1273 * @handler: address to jump to when the temporary breakpoint is hit
1275 * Update a single instruction with the vector in the stack, avoiding
1276 * dynamically allocated memory. This function should be used when it is
1277 * not possible to allocate memory.
1279 void __ref
text_poke_bp(void *addr
, const void *opcode
, size_t len
, const void *emulate
)
1281 struct text_poke_loc tp
;
1283 if (unlikely(system_state
== SYSTEM_BOOTING
)) {
1284 text_poke_early(addr
, opcode
, len
);
1288 text_poke_loc_init(&tp
, addr
, opcode
, len
, emulate
);
1289 text_poke_bp_batch(&tp
, 1);