1 #include <linux/module.h>
2 #include <linux/sched.h>
3 #include <linux/mutex.h>
4 #include <linux/list.h>
5 #include <linux/stringify.h>
6 #include <linux/kprobes.h>
8 #include <linux/vmalloc.h>
9 #include <linux/memory.h>
10 #include <linux/stop_machine.h>
11 #include <linux/slab.h>
12 #include <asm/alternative.h>
13 #include <asm/sections.h>
14 #include <asm/pgtable.h>
17 #include <asm/cacheflush.h>
18 #include <asm/tlbflush.h>
20 #include <asm/fixmap.h>
22 #define MAX_PATCH_LEN (255-1)
24 static int __initdata_or_module debug_alternative;
26 static int __init debug_alt(char *str)
28 debug_alternative = 1;
31 __setup("debug-alternative", debug_alt);
33 static int noreplace_smp;
35 static int __init setup_noreplace_smp(char *str)
40 __setup("noreplace-smp", setup_noreplace_smp);
42 #ifdef CONFIG_PARAVIRT
43 static int __initdata_or_module noreplace_paravirt = 0;
45 static int __init setup_noreplace_paravirt(char *str)
47 noreplace_paravirt = 1;
50 __setup("noreplace-paravirt", setup_noreplace_paravirt);
53 #define DPRINTK(fmt, args...) \
55 if (debug_alternative) \
56 printk(KERN_DEBUG "%s: " fmt "\n", __func__, ##args); \
59 #define DUMP_BYTES(buf, len, fmt, args...) \
61 if (unlikely(debug_alternative)) { \
67 printk(KERN_DEBUG fmt, ##args); \
68 for (j = 0; j < (len) - 1; j++) \
69 printk(KERN_CONT "%02hhx ", buf[j]); \
70 printk(KERN_CONT "%02hhx\n", buf[j]); \
75 * Each GENERIC_NOPX is of X bytes, and defined as an array of bytes
76 * that correspond to that nop. Getting from one nop to the next, we
77 * add to the array the offset that is equal to the sum of all sizes of
78 * nops preceding the one we are after.
80 * Note: The GENERIC_NOP5_ATOMIC is at the end, as it breaks the
81 * nice symmetry of sizes of the previous nops.
83 #if defined(GENERIC_NOP1) && !defined(CONFIG_X86_64)
84 static const unsigned char intelnops[] =
96 static const unsigned char * const intel_nops[ASM_NOP_MAX+2] =
102 intelnops + 1 + 2 + 3,
103 intelnops + 1 + 2 + 3 + 4,
104 intelnops + 1 + 2 + 3 + 4 + 5,
105 intelnops + 1 + 2 + 3 + 4 + 5 + 6,
106 intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
107 intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
112 static const unsigned char k8nops[] =
124 static const unsigned char * const k8_nops[ASM_NOP_MAX+2] =
131 k8nops + 1 + 2 + 3 + 4,
132 k8nops + 1 + 2 + 3 + 4 + 5,
133 k8nops + 1 + 2 + 3 + 4 + 5 + 6,
134 k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
135 k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
139 #if defined(K7_NOP1) && !defined(CONFIG_X86_64)
140 static const unsigned char k7nops[] =
152 static const unsigned char * const k7_nops[ASM_NOP_MAX+2] =
159 k7nops + 1 + 2 + 3 + 4,
160 k7nops + 1 + 2 + 3 + 4 + 5,
161 k7nops + 1 + 2 + 3 + 4 + 5 + 6,
162 k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
163 k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
168 static const unsigned char p6nops[] =
180 static const unsigned char * const p6_nops[ASM_NOP_MAX+2] =
187 p6nops + 1 + 2 + 3 + 4,
188 p6nops + 1 + 2 + 3 + 4 + 5,
189 p6nops + 1 + 2 + 3 + 4 + 5 + 6,
190 p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
191 p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
195 /* Initialize these to a safe default */
197 const unsigned char * const *ideal_nops = p6_nops;
199 const unsigned char * const *ideal_nops = intel_nops;
202 void __init arch_init_ideal_nops(void)
204 switch (boot_cpu_data.x86_vendor) {
205 case X86_VENDOR_INTEL:
207 * Due to a decoder implementation quirk, some
208 * specific Intel CPUs actually perform better with
209 * the "k8_nops" than with the SDM-recommended NOPs.
211 if (boot_cpu_data.x86 == 6 &&
212 boot_cpu_data.x86_model >= 0x0f &&
213 boot_cpu_data.x86_model != 0x1c &&
214 boot_cpu_data.x86_model != 0x26 &&
215 boot_cpu_data.x86_model != 0x27 &&
216 boot_cpu_data.x86_model < 0x30) {
217 ideal_nops = k8_nops;
218 } else if (boot_cpu_has(X86_FEATURE_NOPL)) {
219 ideal_nops = p6_nops;
222 ideal_nops = k8_nops;
224 ideal_nops = intel_nops;
230 ideal_nops = k8_nops;
232 if (boot_cpu_has(X86_FEATURE_K8))
233 ideal_nops = k8_nops;
234 else if (boot_cpu_has(X86_FEATURE_K7))
235 ideal_nops = k7_nops;
237 ideal_nops = intel_nops;
242 /* Use this to add nops to a buffer, then text_poke the whole buffer. */
243 static void __init_or_module add_nops(void *insns, unsigned int len)
246 unsigned int noplen = len;
247 if (noplen > ASM_NOP_MAX)
248 noplen = ASM_NOP_MAX;
249 memcpy(insns, ideal_nops[noplen], noplen);
255 extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
256 extern s32 __smp_locks[], __smp_locks_end[];
257 void *text_poke_early(void *addr, const void *opcode, size_t len);
260 * Are we looking at a near JMP with a 1 or 4-byte displacement.
262 static inline bool is_jmp(const u8 opcode)
264 return opcode == 0xeb || opcode == 0xe9;
267 static void __init_or_module
268 recompute_jump(struct alt_instr *a, u8 *orig_insn, u8 *repl_insn, u8 *insnbuf)
270 u8 *next_rip, *tgt_rip;
274 if (a->replacementlen != 5)
277 o_dspl = *(s32 *)(insnbuf + 1);
279 /* next_rip of the replacement JMP */
280 next_rip = repl_insn + a->replacementlen;
281 /* target rip of the replacement JMP */
282 tgt_rip = next_rip + o_dspl;
283 n_dspl = tgt_rip - orig_insn;
285 DPRINTK("target RIP: %p, new_displ: 0x%x", tgt_rip, n_dspl);
287 if (tgt_rip - orig_insn >= 0) {
288 if (n_dspl - 2 <= 127)
292 /* negative offset */
294 if (((n_dspl - 2) & 0xff) == (n_dspl - 2))
304 insnbuf[1] = (s8)n_dspl;
305 add_nops(insnbuf + 2, 3);
314 *(s32 *)&insnbuf[1] = n_dspl;
320 DPRINTK("final displ: 0x%08x, JMP 0x%lx",
321 n_dspl, (unsigned long)orig_insn + n_dspl + repl_len);
324 static void __init_or_module optimize_nops(struct alt_instr *a, u8 *instr)
329 for (i = 0; i < a->padlen; i++) {
330 if (instr[i] != 0x90)
334 local_irq_save(flags);
335 add_nops(instr + (a->instrlen - a->padlen), a->padlen);
337 local_irq_restore(flags);
339 DUMP_BYTES(instr, a->instrlen, "%p: [%d:%d) optimized NOPs: ",
340 instr, a->instrlen - a->padlen, a->padlen);
344 * Replace instructions with better alternatives for this CPU type. This runs
345 * before SMP is initialized to avoid SMP problems with self modifying code.
346 * This implies that asymmetric systems where APs have less capabilities than
347 * the boot processor are not handled. Tough. Make sure you disable such
350 void __init_or_module apply_alternatives(struct alt_instr *start,
351 struct alt_instr *end)
354 u8 *instr, *replacement;
355 u8 insnbuf[MAX_PATCH_LEN];
357 DPRINTK("alt table %p -> %p", start, end);
359 * The scan order should be from start to end. A later scanned
360 * alternative code can overwrite previously scanned alternative code.
361 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
364 * So be careful if you want to change the scan order to any other
367 for (a = start; a < end; a++) {
370 instr = (u8 *)&a->instr_offset + a->instr_offset;
371 replacement = (u8 *)&a->repl_offset + a->repl_offset;
372 BUG_ON(a->instrlen > sizeof(insnbuf));
373 BUG_ON(a->cpuid >= (NCAPINTS + NBUGINTS) * 32);
374 if (!boot_cpu_has(a->cpuid)) {
376 optimize_nops(a, instr);
381 DPRINTK("feat: %d*32+%d, old: (%p, len: %d), repl: (%p, len: %d), pad: %d",
385 replacement, a->replacementlen, a->padlen);
387 DUMP_BYTES(instr, a->instrlen, "%p: old_insn: ", instr);
388 DUMP_BYTES(replacement, a->replacementlen, "%p: rpl_insn: ", replacement);
390 memcpy(insnbuf, replacement, a->replacementlen);
391 insnbuf_sz = a->replacementlen;
393 /* 0xe8 is a relative jump; fix the offset. */
394 if (*insnbuf == 0xe8 && a->replacementlen == 5) {
395 *(s32 *)(insnbuf + 1) += replacement - instr;
396 DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
397 *(s32 *)(insnbuf + 1),
398 (unsigned long)instr + *(s32 *)(insnbuf + 1) + 5);
401 if (a->replacementlen && is_jmp(replacement[0]))
402 recompute_jump(a, instr, replacement, insnbuf);
404 if (a->instrlen > a->replacementlen) {
405 add_nops(insnbuf + a->replacementlen,
406 a->instrlen - a->replacementlen);
407 insnbuf_sz += a->instrlen - a->replacementlen;
409 DUMP_BYTES(insnbuf, insnbuf_sz, "%p: final_insn: ", instr);
411 text_poke_early(instr, insnbuf, insnbuf_sz);
416 static void alternatives_smp_lock(const s32 *start, const s32 *end,
417 u8 *text, u8 *text_end)
421 for (poff = start; poff < end; poff++) {
422 u8 *ptr = (u8 *)poff + *poff;
424 if (!*poff || ptr < text || ptr >= text_end)
426 /* turn DS segment override prefix into lock prefix */
428 text_poke(ptr, ((unsigned char []){0xf0}), 1);
432 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
433 u8 *text, u8 *text_end)
437 for (poff = start; poff < end; poff++) {
438 u8 *ptr = (u8 *)poff + *poff;
440 if (!*poff || ptr < text || ptr >= text_end)
442 /* turn lock prefix into DS segment override prefix */
444 text_poke(ptr, ((unsigned char []){0x3E}), 1);
448 struct smp_alt_module {
449 /* what is this ??? */
453 /* ptrs to lock prefixes */
455 const s32 *locks_end;
457 /* .text segment, needed to avoid patching init code ;) */
461 struct list_head next;
463 static LIST_HEAD(smp_alt_modules);
464 static bool uniproc_patched = false; /* protected by text_mutex */
466 void __init_or_module alternatives_smp_module_add(struct module *mod,
468 void *locks, void *locks_end,
469 void *text, void *text_end)
471 struct smp_alt_module *smp;
473 mutex_lock(&text_mutex);
474 if (!uniproc_patched)
477 if (num_possible_cpus() == 1)
478 /* Don't bother remembering, we'll never have to undo it. */
481 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
483 /* we'll run the (safe but slow) SMP code then ... */
489 smp->locks_end = locks_end;
491 smp->text_end = text_end;
492 DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
493 smp->locks, smp->locks_end,
494 smp->text, smp->text_end, smp->name);
496 list_add_tail(&smp->next, &smp_alt_modules);
498 alternatives_smp_unlock(locks, locks_end, text, text_end);
500 mutex_unlock(&text_mutex);
503 void __init_or_module alternatives_smp_module_del(struct module *mod)
505 struct smp_alt_module *item;
507 mutex_lock(&text_mutex);
508 list_for_each_entry(item, &smp_alt_modules, next) {
509 if (mod != item->mod)
511 list_del(&item->next);
515 mutex_unlock(&text_mutex);
518 void alternatives_enable_smp(void)
520 struct smp_alt_module *mod;
522 #ifdef CONFIG_LOCKDEP
524 * Older binutils section handling bug prevented
525 * alternatives-replacement from working reliably.
527 * If this still occurs then you should see a hang
528 * or crash shortly after this line:
530 printk("lockdep: fixing up alternatives.\n");
533 /* Why bother if there are no other CPUs? */
534 BUG_ON(num_possible_cpus() == 1);
536 mutex_lock(&text_mutex);
538 if (uniproc_patched) {
539 printk(KERN_INFO "SMP alternatives: switching to SMP code\n");
540 BUG_ON(num_online_cpus() != 1);
541 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
542 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
543 list_for_each_entry(mod, &smp_alt_modules, next)
544 alternatives_smp_lock(mod->locks, mod->locks_end,
545 mod->text, mod->text_end);
546 uniproc_patched = false;
548 mutex_unlock(&text_mutex);
552 * Return 1 if the address range is reserved for SMP-alternatives.
553 * Must hold text_mutex.
555 int alternatives_text_reserved(void *start, void *end)
557 struct smp_alt_module *mod;
559 u8 *text_start = start;
562 lockdep_assert_held(&text_mutex);
564 list_for_each_entry(mod, &smp_alt_modules, next) {
565 if (mod->text > text_end || mod->text_end < text_start)
567 for (poff = mod->locks; poff < mod->locks_end; poff++) {
568 const u8 *ptr = (const u8 *)poff + *poff;
570 if (text_start <= ptr && text_end > ptr)
577 #endif /* CONFIG_SMP */
579 #ifdef CONFIG_PARAVIRT
580 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
581 struct paravirt_patch_site *end)
583 struct paravirt_patch_site *p;
584 char insnbuf[MAX_PATCH_LEN];
586 if (noreplace_paravirt)
589 for (p = start; p < end; p++) {
592 BUG_ON(p->len > MAX_PATCH_LEN);
593 /* prep the buffer with the original instructions */
594 memcpy(insnbuf, p->instr, p->len);
595 used = pv_init_ops.patch(p->instrtype, p->clobbers, insnbuf,
596 (unsigned long)p->instr, p->len);
598 BUG_ON(used > p->len);
600 /* Pad the rest with nops */
601 add_nops(insnbuf + used, p->len - used);
602 text_poke_early(p->instr, insnbuf, p->len);
605 extern struct paravirt_patch_site __start_parainstructions[],
606 __stop_parainstructions[];
607 #endif /* CONFIG_PARAVIRT */
609 void __init alternative_instructions(void)
611 /* The patching is not fully atomic, so try to avoid local interruptions
612 that might execute the to be patched code.
613 Other CPUs are not running. */
617 * Don't stop machine check exceptions while patching.
618 * MCEs only happen when something got corrupted and in this
619 * case we must do something about the corruption.
620 * Ignoring it is worse than a unlikely patching race.
621 * Also machine checks tend to be broadcast and if one CPU
622 * goes into machine check the others follow quickly, so we don't
623 * expect a machine check to cause undue problems during to code
627 apply_alternatives(__alt_instructions, __alt_instructions_end);
630 /* Patch to UP if other cpus not imminent. */
631 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
632 uniproc_patched = true;
633 alternatives_smp_module_add(NULL, "core kernel",
634 __smp_locks, __smp_locks_end,
638 if (!uniproc_patched || num_possible_cpus() == 1)
639 free_init_pages("SMP alternatives",
640 (unsigned long)__smp_locks,
641 (unsigned long)__smp_locks_end);
644 apply_paravirt(__parainstructions, __parainstructions_end);
650 * text_poke_early - Update instructions on a live kernel at boot time
651 * @addr: address to modify
652 * @opcode: source of the copy
653 * @len: length to copy
655 * When you use this code to patch more than one byte of an instruction
656 * you need to make sure that other CPUs cannot execute this code in parallel.
657 * Also no thread must be currently preempted in the middle of these
658 * instructions. And on the local CPU you need to be protected again NMI or MCE
659 * handlers seeing an inconsistent instruction while you patch.
661 void *__init_or_module text_poke_early(void *addr, const void *opcode,
665 local_irq_save(flags);
666 memcpy(addr, opcode, len);
668 local_irq_restore(flags);
669 /* Could also do a CLFLUSH here to speed up CPU recovery; but
670 that causes hangs on some VIA CPUs. */
675 * text_poke - Update instructions on a live kernel
676 * @addr: address to modify
677 * @opcode: source of the copy
678 * @len: length to copy
680 * Only atomic text poke/set should be allowed when not doing early patching.
681 * It means the size must be writable atomically and the address must be aligned
682 * in a way that permits an atomic write. It also makes sure we fit on a single
685 * Note: Must be called under text_mutex.
687 void *__kprobes text_poke(void *addr, const void *opcode, size_t len)
691 struct page *pages[2];
694 if (!core_kernel_text((unsigned long)addr)) {
695 pages[0] = vmalloc_to_page(addr);
696 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
698 pages[0] = virt_to_page(addr);
699 WARN_ON(!PageReserved(pages[0]));
700 pages[1] = virt_to_page(addr + PAGE_SIZE);
703 local_irq_save(flags);
704 set_fixmap(FIX_TEXT_POKE0, page_to_phys(pages[0]));
706 set_fixmap(FIX_TEXT_POKE1, page_to_phys(pages[1]));
707 vaddr = (char *)fix_to_virt(FIX_TEXT_POKE0);
708 memcpy(&vaddr[(unsigned long)addr & ~PAGE_MASK], opcode, len);
709 clear_fixmap(FIX_TEXT_POKE0);
711 clear_fixmap(FIX_TEXT_POKE1);
714 /* Could also do a CLFLUSH here to speed up CPU recovery; but
715 that causes hangs on some VIA CPUs. */
716 for (i = 0; i < len; i++)
717 BUG_ON(((char *)addr)[i] != ((char *)opcode)[i]);
718 local_irq_restore(flags);
723 * Cross-modifying kernel text with stop_machine().
724 * This code originally comes from immediate value.
726 static atomic_t stop_machine_first;
727 static int wrote_text;
729 struct text_poke_params {
730 struct text_poke_param *params;
734 static int __kprobes stop_machine_text_poke(void *data)
736 struct text_poke_params *tpp = data;
737 struct text_poke_param *p;
740 if (atomic_dec_and_test(&stop_machine_first)) {
741 for (i = 0; i < tpp->nparams; i++) {
743 text_poke(p->addr, p->opcode, p->len);
745 smp_wmb(); /* Make sure other cpus see that this has run */
750 smp_mb(); /* Load wrote_text before following execution */
753 for (i = 0; i < tpp->nparams; i++) {
755 flush_icache_range((unsigned long)p->addr,
756 (unsigned long)p->addr + p->len);
759 * Intel Archiecture Software Developer's Manual section 7.1.3 specifies
760 * that a core serializing instruction such as "cpuid" should be
761 * executed on _each_ core before the new instruction is made visible.
768 * text_poke_smp - Update instructions on a live kernel on SMP
769 * @addr: address to modify
770 * @opcode: source of the copy
771 * @len: length to copy
773 * Modify multi-byte instruction by using stop_machine() on SMP. This allows
774 * user to poke/set multi-byte text on SMP. Only non-NMI/MCE code modifying
775 * should be allowed, since stop_machine() does _not_ protect code against
778 * Note: Must be called under get_online_cpus() and text_mutex.
780 void *__kprobes text_poke_smp(void *addr, const void *opcode, size_t len)
782 struct text_poke_params tpp;
783 struct text_poke_param p;
790 atomic_set(&stop_machine_first, 1);
792 /* Use __stop_machine() because the caller already got online_cpus. */
793 __stop_machine(stop_machine_text_poke, (void *)&tpp, cpu_online_mask);
798 * text_poke_smp_batch - Update instructions on a live kernel on SMP
799 * @params: an array of text_poke parameters
800 * @n: the number of elements in params.
802 * Modify multi-byte instruction by using stop_machine() on SMP. Since the
803 * stop_machine() is heavy task, it is better to aggregate text_poke requests
804 * and do it once if possible.
806 * Note: Must be called under get_online_cpus() and text_mutex.
808 void __kprobes text_poke_smp_batch(struct text_poke_param *params, int n)
810 struct text_poke_params tpp = {.params = params, .nparams = n};
812 atomic_set(&stop_machine_first, 1);
814 __stop_machine(stop_machine_text_poke, (void *)&tpp, cpu_online_mask);