1 #define pr_fmt(fmt) "SMP alternatives: " fmt
3 #include <linux/module.h>
4 #include <linux/sched.h>
5 #include <linux/mutex.h>
6 #include <linux/list.h>
7 #include <linux/stringify.h>
9 #include <linux/vmalloc.h>
10 #include <linux/memory.h>
11 #include <linux/stop_machine.h>
12 #include <linux/slab.h>
13 #include <linux/kdebug.h>
14 #include <asm/alternative.h>
15 #include <asm/sections.h>
16 #include <asm/pgtable.h>
19 #include <asm/cacheflush.h>
20 #include <asm/tlbflush.h>
22 #include <asm/fixmap.h>
24 int __read_mostly alternatives_patched;
26 EXPORT_SYMBOL_GPL(alternatives_patched);
28 #define MAX_PATCH_LEN (255-1)
30 static int __initdata_or_module debug_alternative;
32 static int __init debug_alt(char *str)
34 debug_alternative = 1;
37 __setup("debug-alternative", debug_alt);
39 static int noreplace_smp;
41 static int __init setup_noreplace_smp(char *str)
46 __setup("noreplace-smp", setup_noreplace_smp);
48 #define DPRINTK(fmt, args...) \
50 if (debug_alternative) \
51 printk(KERN_DEBUG "%s: " fmt "\n", __func__, ##args); \
54 #define DUMP_BYTES(buf, len, fmt, args...) \
56 if (unlikely(debug_alternative)) { \
62 printk(KERN_DEBUG fmt, ##args); \
63 for (j = 0; j < (len) - 1; j++) \
64 printk(KERN_CONT "%02hhx ", buf[j]); \
65 printk(KERN_CONT "%02hhx\n", buf[j]); \
70 * Each GENERIC_NOPX is of X bytes, and defined as an array of bytes
71 * that correspond to that nop. Getting from one nop to the next, we
72 * add to the array the offset that is equal to the sum of all sizes of
73 * nops preceding the one we are after.
75 * Note: The GENERIC_NOP5_ATOMIC is at the end, as it breaks the
76 * nice symmetry of sizes of the previous nops.
78 #if defined(GENERIC_NOP1) && !defined(CONFIG_X86_64)
79 static const unsigned char intelnops[] =
91 static const unsigned char * const intel_nops[ASM_NOP_MAX+2] =
97 intelnops + 1 + 2 + 3,
98 intelnops + 1 + 2 + 3 + 4,
99 intelnops + 1 + 2 + 3 + 4 + 5,
100 intelnops + 1 + 2 + 3 + 4 + 5 + 6,
101 intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
102 intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
107 static const unsigned char k8nops[] =
119 static const unsigned char * const k8_nops[ASM_NOP_MAX+2] =
126 k8nops + 1 + 2 + 3 + 4,
127 k8nops + 1 + 2 + 3 + 4 + 5,
128 k8nops + 1 + 2 + 3 + 4 + 5 + 6,
129 k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
130 k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
134 #if defined(K7_NOP1) && !defined(CONFIG_X86_64)
135 static const unsigned char k7nops[] =
147 static const unsigned char * const k7_nops[ASM_NOP_MAX+2] =
154 k7nops + 1 + 2 + 3 + 4,
155 k7nops + 1 + 2 + 3 + 4 + 5,
156 k7nops + 1 + 2 + 3 + 4 + 5 + 6,
157 k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
158 k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
163 static const unsigned char p6nops[] =
175 static const unsigned char * const p6_nops[ASM_NOP_MAX+2] =
182 p6nops + 1 + 2 + 3 + 4,
183 p6nops + 1 + 2 + 3 + 4 + 5,
184 p6nops + 1 + 2 + 3 + 4 + 5 + 6,
185 p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
186 p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
190 /* Initialize these to a safe default */
192 const unsigned char * const *ideal_nops = p6_nops;
194 const unsigned char * const *ideal_nops = intel_nops;
197 void __init arch_init_ideal_nops(void)
199 switch (boot_cpu_data.x86_vendor) {
200 case X86_VENDOR_INTEL:
202 * Due to a decoder implementation quirk, some
203 * specific Intel CPUs actually perform better with
204 * the "k8_nops" than with the SDM-recommended NOPs.
206 if (boot_cpu_data.x86 == 6 &&
207 boot_cpu_data.x86_model >= 0x0f &&
208 boot_cpu_data.x86_model != 0x1c &&
209 boot_cpu_data.x86_model != 0x26 &&
210 boot_cpu_data.x86_model != 0x27 &&
211 boot_cpu_data.x86_model < 0x30) {
212 ideal_nops = k8_nops;
213 } else if (boot_cpu_has(X86_FEATURE_NOPL)) {
214 ideal_nops = p6_nops;
217 ideal_nops = k8_nops;
219 ideal_nops = intel_nops;
225 if (boot_cpu_data.x86 > 0xf) {
226 ideal_nops = p6_nops;
234 ideal_nops = k8_nops;
236 if (boot_cpu_has(X86_FEATURE_K8))
237 ideal_nops = k8_nops;
238 else if (boot_cpu_has(X86_FEATURE_K7))
239 ideal_nops = k7_nops;
241 ideal_nops = intel_nops;
246 /* Use this to add nops to a buffer, then text_poke the whole buffer. */
247 static void __init_or_module add_nops(void *insns, unsigned int len)
250 unsigned int noplen = len;
251 if (noplen > ASM_NOP_MAX)
252 noplen = ASM_NOP_MAX;
253 memcpy(insns, ideal_nops[noplen], noplen);
259 extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
260 extern s32 __smp_locks[], __smp_locks_end[];
261 void *text_poke_early(void *addr, const void *opcode, size_t len);
264 * Are we looking at a near JMP with a 1 or 4-byte displacement.
266 static inline bool is_jmp(const u8 opcode)
268 return opcode == 0xeb || opcode == 0xe9;
271 static void __init_or_module
272 recompute_jump(struct alt_instr *a, u8 *orig_insn, u8 *repl_insn, u8 *insnbuf)
274 u8 *next_rip, *tgt_rip;
278 if (a->replacementlen != 5)
281 o_dspl = *(s32 *)(insnbuf + 1);
283 /* next_rip of the replacement JMP */
284 next_rip = repl_insn + a->replacementlen;
285 /* target rip of the replacement JMP */
286 tgt_rip = next_rip + o_dspl;
287 n_dspl = tgt_rip - orig_insn;
289 DPRINTK("target RIP: %p, new_displ: 0x%x", tgt_rip, n_dspl);
291 if (tgt_rip - orig_insn >= 0) {
292 if (n_dspl - 2 <= 127)
296 /* negative offset */
298 if (((n_dspl - 2) & 0xff) == (n_dspl - 2))
308 insnbuf[1] = (s8)n_dspl;
309 add_nops(insnbuf + 2, 3);
318 *(s32 *)&insnbuf[1] = n_dspl;
324 DPRINTK("final displ: 0x%08x, JMP 0x%lx",
325 n_dspl, (unsigned long)orig_insn + n_dspl + repl_len);
328 static void __init_or_module optimize_nops(struct alt_instr *a, u8 *instr)
333 for (i = 0; i < a->padlen; i++) {
334 if (instr[i] != 0x90)
338 local_irq_save(flags);
339 add_nops(instr + (a->instrlen - a->padlen), a->padlen);
341 local_irq_restore(flags);
343 DUMP_BYTES(instr, a->instrlen, "%p: [%d:%d) optimized NOPs: ",
344 instr, a->instrlen - a->padlen, a->padlen);
348 * Replace instructions with better alternatives for this CPU type. This runs
349 * before SMP is initialized to avoid SMP problems with self modifying code.
350 * This implies that asymmetric systems where APs have less capabilities than
351 * the boot processor are not handled. Tough. Make sure you disable such
354 void __init_or_module apply_alternatives(struct alt_instr *start,
355 struct alt_instr *end)
358 u8 *instr, *replacement;
359 u8 insnbuf[MAX_PATCH_LEN];
361 DPRINTK("alt table %p -> %p", start, end);
363 * The scan order should be from start to end. A later scanned
364 * alternative code can overwrite previously scanned alternative code.
365 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
368 * So be careful if you want to change the scan order to any other
371 for (a = start; a < end; a++) {
374 instr = (u8 *)&a->instr_offset + a->instr_offset;
375 replacement = (u8 *)&a->repl_offset + a->repl_offset;
376 BUG_ON(a->instrlen > sizeof(insnbuf));
377 BUG_ON(a->cpuid >= (NCAPINTS + NBUGINTS) * 32);
378 if (!boot_cpu_has(a->cpuid)) {
380 optimize_nops(a, instr);
385 DPRINTK("feat: %d*32+%d, old: (%p, len: %d), repl: (%p, len: %d), pad: %d",
389 replacement, a->replacementlen, a->padlen);
391 DUMP_BYTES(instr, a->instrlen, "%p: old_insn: ", instr);
392 DUMP_BYTES(replacement, a->replacementlen, "%p: rpl_insn: ", replacement);
394 memcpy(insnbuf, replacement, a->replacementlen);
395 insnbuf_sz = a->replacementlen;
397 /* 0xe8 is a relative jump; fix the offset. */
398 if (*insnbuf == 0xe8 && a->replacementlen == 5) {
399 *(s32 *)(insnbuf + 1) += replacement - instr;
400 DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
401 *(s32 *)(insnbuf + 1),
402 (unsigned long)instr + *(s32 *)(insnbuf + 1) + 5);
405 if (a->replacementlen && is_jmp(replacement[0]))
406 recompute_jump(a, instr, replacement, insnbuf);
408 if (a->instrlen > a->replacementlen) {
409 add_nops(insnbuf + a->replacementlen,
410 a->instrlen - a->replacementlen);
411 insnbuf_sz += a->instrlen - a->replacementlen;
413 DUMP_BYTES(insnbuf, insnbuf_sz, "%p: final_insn: ", instr);
415 text_poke_early(instr, insnbuf, insnbuf_sz);
420 static void alternatives_smp_lock(const s32 *start, const s32 *end,
421 u8 *text, u8 *text_end)
425 mutex_lock(&text_mutex);
426 for (poff = start; poff < end; poff++) {
427 u8 *ptr = (u8 *)poff + *poff;
429 if (!*poff || ptr < text || ptr >= text_end)
431 /* turn DS segment override prefix into lock prefix */
433 text_poke(ptr, ((unsigned char []){0xf0}), 1);
435 mutex_unlock(&text_mutex);
438 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
439 u8 *text, u8 *text_end)
443 mutex_lock(&text_mutex);
444 for (poff = start; poff < end; poff++) {
445 u8 *ptr = (u8 *)poff + *poff;
447 if (!*poff || ptr < text || ptr >= text_end)
449 /* turn lock prefix into DS segment override prefix */
451 text_poke(ptr, ((unsigned char []){0x3E}), 1);
453 mutex_unlock(&text_mutex);
456 struct smp_alt_module {
457 /* what is this ??? */
461 /* ptrs to lock prefixes */
463 const s32 *locks_end;
465 /* .text segment, needed to avoid patching init code ;) */
469 struct list_head next;
471 static LIST_HEAD(smp_alt_modules);
472 static DEFINE_MUTEX(smp_alt);
473 static bool uniproc_patched = false; /* protected by smp_alt */
475 void __init_or_module alternatives_smp_module_add(struct module *mod,
477 void *locks, void *locks_end,
478 void *text, void *text_end)
480 struct smp_alt_module *smp;
482 mutex_lock(&smp_alt);
483 if (!uniproc_patched)
486 if (num_possible_cpus() == 1)
487 /* Don't bother remembering, we'll never have to undo it. */
490 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
492 /* we'll run the (safe but slow) SMP code then ... */
498 smp->locks_end = locks_end;
500 smp->text_end = text_end;
501 DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
502 smp->locks, smp->locks_end,
503 smp->text, smp->text_end, smp->name);
505 list_add_tail(&smp->next, &smp_alt_modules);
507 alternatives_smp_unlock(locks, locks_end, text, text_end);
509 mutex_unlock(&smp_alt);
512 void __init_or_module alternatives_smp_module_del(struct module *mod)
514 struct smp_alt_module *item;
516 mutex_lock(&smp_alt);
517 list_for_each_entry(item, &smp_alt_modules, next) {
518 if (mod != item->mod)
520 list_del(&item->next);
524 mutex_unlock(&smp_alt);
527 void alternatives_enable_smp(void)
529 struct smp_alt_module *mod;
531 /* Why bother if there are no other CPUs? */
532 BUG_ON(num_possible_cpus() == 1);
534 mutex_lock(&smp_alt);
536 if (uniproc_patched) {
537 pr_info("switching to SMP code\n");
538 BUG_ON(num_online_cpus() != 1);
539 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
540 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
541 list_for_each_entry(mod, &smp_alt_modules, next)
542 alternatives_smp_lock(mod->locks, mod->locks_end,
543 mod->text, mod->text_end);
544 uniproc_patched = false;
546 mutex_unlock(&smp_alt);
549 /* Return 1 if the address range is reserved for smp-alternatives */
550 int alternatives_text_reserved(void *start, void *end)
552 struct smp_alt_module *mod;
554 u8 *text_start = start;
557 list_for_each_entry(mod, &smp_alt_modules, next) {
558 if (mod->text > text_end || mod->text_end < text_start)
560 for (poff = mod->locks; poff < mod->locks_end; poff++) {
561 const u8 *ptr = (const u8 *)poff + *poff;
563 if (text_start <= ptr && text_end > ptr)
570 #endif /* CONFIG_SMP */
572 #ifdef CONFIG_PARAVIRT
573 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
574 struct paravirt_patch_site *end)
576 struct paravirt_patch_site *p;
577 char insnbuf[MAX_PATCH_LEN];
579 for (p = start; p < end; p++) {
582 BUG_ON(p->len > MAX_PATCH_LEN);
583 /* prep the buffer with the original instructions */
584 memcpy(insnbuf, p->instr, p->len);
585 used = pv_init_ops.patch(p->instrtype, p->clobbers, insnbuf,
586 (unsigned long)p->instr, p->len);
588 BUG_ON(used > p->len);
590 /* Pad the rest with nops */
591 add_nops(insnbuf + used, p->len - used);
592 text_poke_early(p->instr, insnbuf, p->len);
595 extern struct paravirt_patch_site __start_parainstructions[],
596 __stop_parainstructions[];
597 #endif /* CONFIG_PARAVIRT */
599 void __init alternative_instructions(void)
601 /* The patching is not fully atomic, so try to avoid local interruptions
602 that might execute the to be patched code.
603 Other CPUs are not running. */
607 * Don't stop machine check exceptions while patching.
608 * MCEs only happen when something got corrupted and in this
609 * case we must do something about the corruption.
610 * Ignoring it is worse than a unlikely patching race.
611 * Also machine checks tend to be broadcast and if one CPU
612 * goes into machine check the others follow quickly, so we don't
613 * expect a machine check to cause undue problems during to code
617 apply_alternatives(__alt_instructions, __alt_instructions_end);
620 /* Patch to UP if other cpus not imminent. */
621 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
622 uniproc_patched = true;
623 alternatives_smp_module_add(NULL, "core kernel",
624 __smp_locks, __smp_locks_end,
628 if (!uniproc_patched || num_possible_cpus() == 1)
629 free_init_pages("SMP alternatives",
630 (unsigned long)__smp_locks,
631 (unsigned long)__smp_locks_end);
634 apply_paravirt(__parainstructions, __parainstructions_end);
637 alternatives_patched = 1;
641 * text_poke_early - Update instructions on a live kernel at boot time
642 * @addr: address to modify
643 * @opcode: source of the copy
644 * @len: length to copy
646 * When you use this code to patch more than one byte of an instruction
647 * you need to make sure that other CPUs cannot execute this code in parallel.
648 * Also no thread must be currently preempted in the middle of these
649 * instructions. And on the local CPU you need to be protected again NMI or MCE
650 * handlers seeing an inconsistent instruction while you patch.
652 void *__init_or_module text_poke_early(void *addr, const void *opcode,
656 local_irq_save(flags);
657 memcpy(addr, opcode, len);
659 local_irq_restore(flags);
660 /* Could also do a CLFLUSH here to speed up CPU recovery; but
661 that causes hangs on some VIA CPUs. */
666 * text_poke - Update instructions on a live kernel
667 * @addr: address to modify
668 * @opcode: source of the copy
669 * @len: length to copy
671 * Only atomic text poke/set should be allowed when not doing early patching.
672 * It means the size must be writable atomically and the address must be aligned
673 * in a way that permits an atomic write. It also makes sure we fit on a single
676 * Note: Must be called under text_mutex.
678 void *text_poke(void *addr, const void *opcode, size_t len)
682 struct page *pages[2];
685 if (!core_kernel_text((unsigned long)addr)) {
686 pages[0] = vmalloc_to_page(addr);
687 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
689 pages[0] = virt_to_page(addr);
690 WARN_ON(!PageReserved(pages[0]));
691 pages[1] = virt_to_page(addr + PAGE_SIZE);
694 local_irq_save(flags);
695 set_fixmap(FIX_TEXT_POKE0, page_to_phys(pages[0]));
697 set_fixmap(FIX_TEXT_POKE1, page_to_phys(pages[1]));
698 vaddr = (char *)fix_to_virt(FIX_TEXT_POKE0);
699 memcpy(&vaddr[(unsigned long)addr & ~PAGE_MASK], opcode, len);
700 clear_fixmap(FIX_TEXT_POKE0);
702 clear_fixmap(FIX_TEXT_POKE1);
705 /* Could also do a CLFLUSH here to speed up CPU recovery; but
706 that causes hangs on some VIA CPUs. */
707 for (i = 0; i < len; i++)
708 BUG_ON(((char *)addr)[i] != ((char *)opcode)[i]);
709 local_irq_restore(flags);
713 static void do_sync_core(void *info)
718 static bool bp_patching_in_progress;
719 static void *bp_int3_handler, *bp_int3_addr;
721 int poke_int3_handler(struct pt_regs *regs)
723 /* bp_patching_in_progress */
726 if (likely(!bp_patching_in_progress))
729 if (user_mode(regs) || regs->ip != (unsigned long)bp_int3_addr)
732 /* set up the specified breakpoint handler */
733 regs->ip = (unsigned long) bp_int3_handler;
740 * text_poke_bp() -- update instructions on live kernel on SMP
741 * @addr: address to patch
742 * @opcode: opcode of new instruction
743 * @len: length to copy
744 * @handler: address to jump to when the temporary breakpoint is hit
746 * Modify multi-byte instruction by using int3 breakpoint on SMP.
747 * We completely avoid stop_machine() here, and achieve the
748 * synchronization using int3 breakpoint.
750 * The way it is done:
751 * - add a int3 trap to the address that will be patched
753 * - update all but the first byte of the patched range
755 * - replace the first byte (int3) by the first byte of
759 * Note: must be called under text_mutex.
761 void *text_poke_bp(void *addr, const void *opcode, size_t len, void *handler)
763 unsigned char int3 = 0xcc;
765 bp_int3_handler = handler;
766 bp_int3_addr = (u8 *)addr + sizeof(int3);
767 bp_patching_in_progress = true;
769 * Corresponding read barrier in int3 notifier for
770 * making sure the in_progress flags is correctly ordered wrt.
775 text_poke(addr, &int3, sizeof(int3));
777 on_each_cpu(do_sync_core, NULL, 1);
779 if (len - sizeof(int3) > 0) {
780 /* patch all but the first byte */
781 text_poke((char *)addr + sizeof(int3),
782 (const char *) opcode + sizeof(int3),
785 * According to Intel, this core syncing is very likely
786 * not necessary and we'd be safe even without it. But
787 * better safe than sorry (plus there's not only Intel).
789 on_each_cpu(do_sync_core, NULL, 1);
792 /* patch the first byte */
793 text_poke(addr, opcode, sizeof(int3));
795 on_each_cpu(do_sync_core, NULL, 1);
797 bp_patching_in_progress = false;