1 // SPDX-License-Identifier: GPL-2.0-only
2 #define pr_fmt(fmt) "SMP alternatives: " fmt
3
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>
11 #include <linux/mm.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 <linux/moduleloader.h>
22 #include <linux/cleanup.h>
23 #include <asm/text-patching.h>
24 #include <asm/alternative.h>
25 #include <asm/sections.h>
26 #include <asm/mce.h>
27 #include <asm/nmi.h>
28 #include <asm/cacheflush.h>
29 #include <asm/tlbflush.h>
30 #include <asm/insn.h>
31 #include <asm/io.h>
32 #include <asm/fixmap.h>
33 #include <asm/paravirt.h>
34 #include <asm/asm-prototypes.h>
35 #include <asm/cfi.h>
36 #include <asm/set_memory.h>
37
38 int __read_mostly alternatives_patched;
39
40 EXPORT_SYMBOL_GPL(alternatives_patched);
41
42 #define MAX_PATCH_LEN (255-1)
43
44 #define DA_ALL (~0)
45 #define DA_ALT 0x01
46 #define DA_RET 0x02
47 #define DA_RETPOLINE 0x04
48 #define DA_ENDBR 0x08
49 #define DA_SMP 0x10
50
51 static unsigned int __initdata_or_module debug_alternative;
52
debug_alt(char * str)53 static int __init debug_alt(char *str)
54 {
55 if (str && *str == '=')
56 str++;
57
58 if (!str || kstrtouint(str, 0, &debug_alternative))
59 debug_alternative = DA_ALL;
60
61 return 1;
62 }
63 __setup("debug-alternative", debug_alt);
64
65 static int noreplace_smp;
66
setup_noreplace_smp(char * str)67 static int __init setup_noreplace_smp(char *str)
68 {
69 noreplace_smp = 1;
70 return 1;
71 }
72 __setup("noreplace-smp", setup_noreplace_smp);
73
74 #define DPRINTK(type, fmt, args...) \
75 do { \
76 if (debug_alternative & DA_##type) \
77 printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \
78 } while (0)
79
80 #define DUMP_BYTES(type, buf, len, fmt, args...) \
81 do { \
82 if (unlikely(debug_alternative & DA_##type)) { \
83 int j; \
84 \
85 if (!(len)) \
86 break; \
87 \
88 printk(KERN_DEBUG pr_fmt(fmt), ##args); \
89 for (j = 0; j < (len) - 1; j++) \
90 printk(KERN_CONT "%02hhx ", buf[j]); \
91 printk(KERN_CONT "%02hhx\n", buf[j]); \
92 } \
93 } while (0)
94
95 static const unsigned char x86nops[] =
96 {
97 BYTES_NOP1,
98 BYTES_NOP2,
99 BYTES_NOP3,
100 BYTES_NOP4,
101 BYTES_NOP5,
102 BYTES_NOP6,
103 BYTES_NOP7,
104 BYTES_NOP8,
105 #ifdef CONFIG_64BIT
106 BYTES_NOP9,
107 BYTES_NOP10,
108 BYTES_NOP11,
109 #endif
110 };
111
112 const unsigned char * const x86_nops[ASM_NOP_MAX+1] =
113 {
114 NULL,
115 x86nops,
116 x86nops + 1,
117 x86nops + 1 + 2,
118 x86nops + 1 + 2 + 3,
119 x86nops + 1 + 2 + 3 + 4,
120 x86nops + 1 + 2 + 3 + 4 + 5,
121 x86nops + 1 + 2 + 3 + 4 + 5 + 6,
122 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
123 #ifdef CONFIG_64BIT
124 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
125 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
126 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
127 #endif
128 };
129
130 #ifdef CONFIG_MITIGATION_ITS
131
132 #ifdef CONFIG_MODULES
133 static struct module *its_mod;
134 static void *its_page;
135 static unsigned int its_offset;
136
137 /* Initialize a thunk with the "jmp *reg; int3" instructions. */
its_init_thunk(void * thunk,int reg)138 static void *its_init_thunk(void *thunk, int reg)
139 {
140 u8 *bytes = thunk;
141 int i = 0;
142
143 if (reg >= 8) {
144 bytes[i++] = 0x41; /* REX.B prefix */
145 reg -= 8;
146 }
147 bytes[i++] = 0xff;
148 bytes[i++] = 0xe0 + reg; /* jmp *reg */
149 bytes[i++] = 0xcc;
150
151 return thunk;
152 }
153
its_init_mod(struct module * mod)154 void its_init_mod(struct module *mod)
155 {
156 if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
157 return;
158
159 mutex_lock(&text_mutex);
160 its_mod = mod;
161 its_page = NULL;
162 }
163
its_fini_mod(struct module * mod)164 void its_fini_mod(struct module *mod)
165 {
166 if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
167 return;
168
169 WARN_ON_ONCE(its_mod != mod);
170
171 its_mod = NULL;
172 its_page = NULL;
173 mutex_unlock(&text_mutex);
174
175 for (int i = 0; i < mod->its_num_pages; i++) {
176 void *page = mod->its_page_array[i];
177 set_memory_rox((unsigned long)page, 1);
178 }
179 }
180
its_free_mod(struct module * mod)181 void its_free_mod(struct module *mod)
182 {
183 if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
184 return;
185
186 for (int i = 0; i < mod->its_num_pages; i++) {
187 void *page = mod->its_page_array[i];
188 module_memfree(page);
189 }
190 kfree(mod->its_page_array);
191 }
192
193 DEFINE_FREE(its_execmem, void *, if (_T) module_memfree(_T));
194
its_alloc(void)195 static void *its_alloc(void)
196 {
197 void *page __free(its_execmem) = module_alloc(PAGE_SIZE);
198
199 if (!page)
200 return NULL;
201
202 if (its_mod) {
203 void *tmp = krealloc(its_mod->its_page_array,
204 (its_mod->its_num_pages+1) * sizeof(void *),
205 GFP_KERNEL);
206 if (!tmp)
207 return NULL;
208
209 its_mod->its_page_array = tmp;
210 its_mod->its_page_array[its_mod->its_num_pages++] = page;
211 }
212
213 return no_free_ptr(page);
214 }
215
its_allocate_thunk(int reg)216 static void *its_allocate_thunk(int reg)
217 {
218 int size = 3 + (reg / 8);
219 void *thunk;
220
221 if (!its_page || (its_offset + size - 1) >= PAGE_SIZE) {
222 its_page = its_alloc();
223 if (!its_page) {
224 pr_err("ITS page allocation failed\n");
225 return NULL;
226 }
227 memset(its_page, INT3_INSN_OPCODE, PAGE_SIZE);
228 its_offset = 32;
229 }
230
231 /*
232 * If the indirect branch instruction will be in the lower half
233 * of a cacheline, then update the offset to reach the upper half.
234 */
235 if ((its_offset + size - 1) % 64 < 32)
236 its_offset = ((its_offset - 1) | 0x3F) + 33;
237
238 thunk = its_page + its_offset;
239 its_offset += size;
240
241 set_memory_rw((unsigned long)its_page, 1);
242 thunk = its_init_thunk(thunk, reg);
243 set_memory_rox((unsigned long)its_page, 1);
244
245 return thunk;
246 }
247
248 #else /* CONFIG_MODULES */
249
its_allocate_thunk(int reg)250 static void *its_allocate_thunk(int reg)
251 {
252 return NULL;
253 }
254
255 #endif /* CONFIG_MODULES */
256
257 #endif /* CONFIG_MITIGATION_ITS */
258
259 /*
260 * Fill the buffer with a single effective instruction of size @len.
261 *
262 * In order not to issue an ORC stack depth tracking CFI entry (Call Frame Info)
263 * for every single-byte NOP, try to generate the maximally available NOP of
264 * size <= ASM_NOP_MAX such that only a single CFI entry is generated (vs one for
265 * each single-byte NOPs). If @len to fill out is > ASM_NOP_MAX, pad with INT3 and
266 * *jump* over instead of executing long and daft NOPs.
267 */
add_nop(u8 * instr,unsigned int len)268 static void __init_or_module add_nop(u8 *instr, unsigned int len)
269 {
270 u8 *target = instr + len;
271
272 if (!len)
273 return;
274
275 if (len <= ASM_NOP_MAX) {
276 memcpy(instr, x86_nops[len], len);
277 return;
278 }
279
280 if (len < 128) {
281 __text_gen_insn(instr, JMP8_INSN_OPCODE, instr, target, JMP8_INSN_SIZE);
282 instr += JMP8_INSN_SIZE;
283 } else {
284 __text_gen_insn(instr, JMP32_INSN_OPCODE, instr, target, JMP32_INSN_SIZE);
285 instr += JMP32_INSN_SIZE;
286 }
287
288 for (;instr < target; instr++)
289 *instr = INT3_INSN_OPCODE;
290 }
291
292 extern s32 __retpoline_sites[], __retpoline_sites_end[];
293 extern s32 __return_sites[], __return_sites_end[];
294 extern s32 __cfi_sites[], __cfi_sites_end[];
295 extern s32 __ibt_endbr_seal[], __ibt_endbr_seal_end[];
296 extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
297 extern s32 __smp_locks[], __smp_locks_end[];
298 void text_poke_early(void *addr, const void *opcode, size_t len);
299
300 /*
301 * Matches NOP and NOPL, not any of the other possible NOPs.
302 */
insn_is_nop(struct insn * insn)303 static bool insn_is_nop(struct insn *insn)
304 {
305 /* Anything NOP, but no REP NOP */
306 if (insn->opcode.bytes[0] == 0x90 &&
307 (!insn->prefixes.nbytes || insn->prefixes.bytes[0] != 0xF3))
308 return true;
309
310 /* NOPL */
311 if (insn->opcode.bytes[0] == 0x0F && insn->opcode.bytes[1] == 0x1F)
312 return true;
313
314 /* TODO: more nops */
315
316 return false;
317 }
318
319 /*
320 * Find the offset of the first non-NOP instruction starting at @offset
321 * but no further than @len.
322 */
skip_nops(u8 * instr,int offset,int len)323 static int skip_nops(u8 *instr, int offset, int len)
324 {
325 struct insn insn;
326
327 for (; offset < len; offset += insn.length) {
328 if (insn_decode_kernel(&insn, &instr[offset]))
329 break;
330
331 if (!insn_is_nop(&insn))
332 break;
333 }
334
335 return offset;
336 }
337
338 /*
339 * Optimize a sequence of NOPs, possibly preceded by an unconditional jump
340 * to the end of the NOP sequence into a single NOP.
341 */
342 static bool __init_or_module
__optimize_nops(u8 * instr,size_t len,struct insn * insn,int * next,int * prev,int * target)343 __optimize_nops(u8 *instr, size_t len, struct insn *insn, int *next, int *prev, int *target)
344 {
345 int i = *next - insn->length;
346
347 switch (insn->opcode.bytes[0]) {
348 case JMP8_INSN_OPCODE:
349 case JMP32_INSN_OPCODE:
350 *prev = i;
351 *target = *next + insn->immediate.value;
352 return false;
353 }
354
355 if (insn_is_nop(insn)) {
356 int nop = i;
357
358 *next = skip_nops(instr, *next, len);
359 if (*target && *next == *target)
360 nop = *prev;
361
362 add_nop(instr + nop, *next - nop);
363 DUMP_BYTES(ALT, instr, len, "%px: [%d:%d) optimized NOPs: ", instr, nop, *next);
364 return true;
365 }
366
367 *target = 0;
368 return false;
369 }
370
371 /*
372 * "noinline" to cause control flow change and thus invalidate I$ and
373 * cause refetch after modification.
374 */
optimize_nops(u8 * instr,size_t len)375 static void __init_or_module noinline optimize_nops(u8 *instr, size_t len)
376 {
377 int prev, target = 0;
378
379 for (int next, i = 0; i < len; i = next) {
380 struct insn insn;
381
382 if (insn_decode_kernel(&insn, &instr[i]))
383 return;
384
385 next = i + insn.length;
386
387 __optimize_nops(instr, len, &insn, &next, &prev, &target);
388 }
389 }
390
optimize_nops_inplace(u8 * instr,size_t len)391 static void __init_or_module noinline optimize_nops_inplace(u8 *instr, size_t len)
392 {
393 unsigned long flags;
394
395 local_irq_save(flags);
396 optimize_nops(instr, len);
397 sync_core();
398 local_irq_restore(flags);
399 }
400
401 /*
402 * In this context, "source" is where the instructions are placed in the
403 * section .altinstr_replacement, for example during kernel build by the
404 * toolchain.
405 * "Destination" is where the instructions are being patched in by this
406 * machinery.
407 *
408 * The source offset is:
409 *
410 * src_imm = target - src_next_ip (1)
411 *
412 * and the target offset is:
413 *
414 * dst_imm = target - dst_next_ip (2)
415 *
416 * so rework (1) as an expression for target like:
417 *
418 * target = src_imm + src_next_ip (1a)
419 *
420 * and substitute in (2) to get:
421 *
422 * dst_imm = (src_imm + src_next_ip) - dst_next_ip (3)
423 *
424 * Now, since the instruction stream is 'identical' at src and dst (it
425 * is being copied after all) it can be stated that:
426 *
427 * src_next_ip = src + ip_offset
428 * dst_next_ip = dst + ip_offset (4)
429 *
430 * Substitute (4) in (3) and observe ip_offset being cancelled out to
431 * obtain:
432 *
433 * dst_imm = src_imm + (src + ip_offset) - (dst + ip_offset)
434 * = src_imm + src - dst + ip_offset - ip_offset
435 * = src_imm + src - dst (5)
436 *
437 * IOW, only the relative displacement of the code block matters.
438 */
439
440 #define apply_reloc_n(n_, p_, d_) \
441 do { \
442 s32 v = *(s##n_ *)(p_); \
443 v += (d_); \
444 BUG_ON((v >> 31) != (v >> (n_-1))); \
445 *(s##n_ *)(p_) = (s##n_)v; \
446 } while (0)
447
448
449 static __always_inline
apply_reloc(int n,void * ptr,uintptr_t diff)450 void apply_reloc(int n, void *ptr, uintptr_t diff)
451 {
452 switch (n) {
453 case 1: apply_reloc_n(8, ptr, diff); break;
454 case 2: apply_reloc_n(16, ptr, diff); break;
455 case 4: apply_reloc_n(32, ptr, diff); break;
456 default: BUG();
457 }
458 }
459
460 static __always_inline
need_reloc(unsigned long offset,u8 * src,size_t src_len)461 bool need_reloc(unsigned long offset, u8 *src, size_t src_len)
462 {
463 u8 *target = src + offset;
464 /*
465 * If the target is inside the patched block, it's relative to the
466 * block itself and does not need relocation.
467 */
468 return (target < src || target > src + src_len);
469 }
470
471 static void __init_or_module noinline
apply_relocation(u8 * buf,size_t len,u8 * dest,u8 * src,size_t src_len)472 apply_relocation(u8 *buf, size_t len, u8 *dest, u8 *src, size_t src_len)
473 {
474 int prev, target = 0;
475
476 for (int next, i = 0; i < len; i = next) {
477 struct insn insn;
478
479 if (WARN_ON_ONCE(insn_decode_kernel(&insn, &buf[i])))
480 return;
481
482 next = i + insn.length;
483
484 if (__optimize_nops(buf, len, &insn, &next, &prev, &target))
485 continue;
486
487 switch (insn.opcode.bytes[0]) {
488 case 0x0f:
489 if (insn.opcode.bytes[1] < 0x80 ||
490 insn.opcode.bytes[1] > 0x8f)
491 break;
492
493 fallthrough; /* Jcc.d32 */
494 case 0x70 ... 0x7f: /* Jcc.d8 */
495 case JMP8_INSN_OPCODE:
496 case JMP32_INSN_OPCODE:
497 case CALL_INSN_OPCODE:
498 if (need_reloc(next + insn.immediate.value, src, src_len)) {
499 apply_reloc(insn.immediate.nbytes,
500 buf + i + insn_offset_immediate(&insn),
501 src - dest);
502 }
503
504 /*
505 * Where possible, convert JMP.d32 into JMP.d8.
506 */
507 if (insn.opcode.bytes[0] == JMP32_INSN_OPCODE) {
508 s32 imm = insn.immediate.value;
509 imm += src - dest;
510 imm += JMP32_INSN_SIZE - JMP8_INSN_SIZE;
511 if ((imm >> 31) == (imm >> 7)) {
512 buf[i+0] = JMP8_INSN_OPCODE;
513 buf[i+1] = (s8)imm;
514
515 memset(&buf[i+2], INT3_INSN_OPCODE, insn.length - 2);
516 }
517 }
518 break;
519 }
520
521 if (insn_rip_relative(&insn)) {
522 if (need_reloc(next + insn.displacement.value, src, src_len)) {
523 apply_reloc(insn.displacement.nbytes,
524 buf + i + insn_offset_displacement(&insn),
525 src - dest);
526 }
527 }
528 }
529 }
530
531 /*
532 * Replace instructions with better alternatives for this CPU type. This runs
533 * before SMP is initialized to avoid SMP problems with self modifying code.
534 * This implies that asymmetric systems where APs have less capabilities than
535 * the boot processor are not handled. Tough. Make sure you disable such
536 * features by hand.
537 *
538 * Marked "noinline" to cause control flow change and thus insn cache
539 * to refetch changed I$ lines.
540 */
apply_alternatives(struct alt_instr * start,struct alt_instr * end)541 void __init_or_module noinline apply_alternatives(struct alt_instr *start,
542 struct alt_instr *end)
543 {
544 struct alt_instr *a;
545 u8 *instr, *replacement;
546 u8 insn_buff[MAX_PATCH_LEN];
547
548 DPRINTK(ALT, "alt table %px, -> %px", start, end);
549
550 /*
551 * In the case CONFIG_X86_5LEVEL=y, KASAN_SHADOW_START is defined using
552 * cpu_feature_enabled(X86_FEATURE_LA57) and is therefore patched here.
553 * During the process, KASAN becomes confused seeing partial LA57
554 * conversion and triggers a false-positive out-of-bound report.
555 *
556 * Disable KASAN until the patching is complete.
557 */
558 kasan_disable_current();
559
560 /*
561 * The scan order should be from start to end. A later scanned
562 * alternative code can overwrite previously scanned alternative code.
563 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
564 * patch code.
565 *
566 * So be careful if you want to change the scan order to any other
567 * order.
568 */
569 for (a = start; a < end; a++) {
570 int insn_buff_sz = 0;
571
572 instr = (u8 *)&a->instr_offset + a->instr_offset;
573 replacement = (u8 *)&a->repl_offset + a->repl_offset;
574 BUG_ON(a->instrlen > sizeof(insn_buff));
575 BUG_ON(a->cpuid >= (NCAPINTS + NBUGINTS) * 32);
576
577 /*
578 * Patch if either:
579 * - feature is present
580 * - feature not present but ALT_FLAG_NOT is set to mean,
581 * patch if feature is *NOT* present.
582 */
583 if (!boot_cpu_has(a->cpuid) == !(a->flags & ALT_FLAG_NOT)) {
584 optimize_nops_inplace(instr, a->instrlen);
585 continue;
586 }
587
588 DPRINTK(ALT, "feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)",
589 (a->flags & ALT_FLAG_NOT) ? "!" : "",
590 a->cpuid >> 5,
591 a->cpuid & 0x1f,
592 instr, instr, a->instrlen,
593 replacement, a->replacementlen);
594
595 memcpy(insn_buff, replacement, a->replacementlen);
596 insn_buff_sz = a->replacementlen;
597
598 for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
599 insn_buff[insn_buff_sz] = 0x90;
600
601 apply_relocation(insn_buff, a->instrlen, instr, replacement, a->replacementlen);
602
603 DUMP_BYTES(ALT, instr, a->instrlen, "%px: old_insn: ", instr);
604 DUMP_BYTES(ALT, replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
605 DUMP_BYTES(ALT, insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
606
607 text_poke_early(instr, insn_buff, insn_buff_sz);
608 }
609
610 kasan_enable_current();
611 }
612
is_jcc32(struct insn * insn)613 static inline bool is_jcc32(struct insn *insn)
614 {
615 /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
616 return insn->opcode.bytes[0] == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80;
617 }
618
619 #if defined(CONFIG_RETPOLINE) && defined(CONFIG_OBJTOOL)
620
621 /*
622 * CALL/JMP *%\reg
623 */
emit_indirect(int op,int reg,u8 * bytes)624 static int emit_indirect(int op, int reg, u8 *bytes)
625 {
626 int i = 0;
627 u8 modrm;
628
629 switch (op) {
630 case CALL_INSN_OPCODE:
631 modrm = 0x10; /* Reg = 2; CALL r/m */
632 break;
633
634 case JMP32_INSN_OPCODE:
635 modrm = 0x20; /* Reg = 4; JMP r/m */
636 break;
637
638 default:
639 WARN_ON_ONCE(1);
640 return -1;
641 }
642
643 if (reg >= 8) {
644 bytes[i++] = 0x41; /* REX.B prefix */
645 reg -= 8;
646 }
647
648 modrm |= 0xc0; /* Mod = 3 */
649 modrm += reg;
650
651 bytes[i++] = 0xff; /* opcode */
652 bytes[i++] = modrm;
653
654 return i;
655 }
656
__emit_trampoline(void * addr,struct insn * insn,u8 * bytes,void * call_dest,void * jmp_dest)657 static int __emit_trampoline(void *addr, struct insn *insn, u8 *bytes,
658 void *call_dest, void *jmp_dest)
659 {
660 u8 op = insn->opcode.bytes[0];
661 int i = 0;
662
663 /*
664 * Clang does 'weird' Jcc __x86_indirect_thunk_r11 conditional
665 * tail-calls. Deal with them.
666 */
667 if (is_jcc32(insn)) {
668 bytes[i++] = op;
669 op = insn->opcode.bytes[1];
670 goto clang_jcc;
671 }
672
673 if (insn->length == 6)
674 bytes[i++] = 0x2e; /* CS-prefix */
675
676 switch (op) {
677 case CALL_INSN_OPCODE:
678 __text_gen_insn(bytes+i, op, addr+i,
679 call_dest,
680 CALL_INSN_SIZE);
681 i += CALL_INSN_SIZE;
682 break;
683
684 case JMP32_INSN_OPCODE:
685 clang_jcc:
686 __text_gen_insn(bytes+i, op, addr+i,
687 jmp_dest,
688 JMP32_INSN_SIZE);
689 i += JMP32_INSN_SIZE;
690 break;
691
692 default:
693 WARN(1, "%pS %px %*ph\n", addr, addr, 6, addr);
694 return -1;
695 }
696
697 WARN_ON_ONCE(i != insn->length);
698
699 return i;
700 }
701
emit_call_track_retpoline(void * addr,struct insn * insn,int reg,u8 * bytes)702 static int emit_call_track_retpoline(void *addr, struct insn *insn, int reg, u8 *bytes)
703 {
704 return __emit_trampoline(addr, insn, bytes,
705 __x86_indirect_call_thunk_array[reg],
706 __x86_indirect_jump_thunk_array[reg]);
707 }
708
709 #ifdef CONFIG_MITIGATION_ITS
emit_its_trampoline(void * addr,struct insn * insn,int reg,u8 * bytes)710 static int emit_its_trampoline(void *addr, struct insn *insn, int reg, u8 *bytes)
711 {
712 u8 *thunk = __x86_indirect_its_thunk_array[reg];
713 u8 *tmp = its_allocate_thunk(reg);
714
715 if (tmp)
716 thunk = tmp;
717
718 return __emit_trampoline(addr, insn, bytes, thunk, thunk);
719 }
720
721 /* Check if an indirect branch is at ITS-unsafe address */
cpu_wants_indirect_its_thunk_at(unsigned long addr,int reg)722 static bool cpu_wants_indirect_its_thunk_at(unsigned long addr, int reg)
723 {
724 if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
725 return false;
726
727 /* Indirect branch opcode is 2 or 3 bytes depending on reg */
728 addr += 1 + reg / 8;
729
730 /* Lower-half of the cacheline? */
731 return !(addr & 0x20);
732 }
733
its_static_thunk(int reg)734 u8 *its_static_thunk(int reg)
735 {
736 u8 *thunk = __x86_indirect_its_thunk_array[reg];
737
738 return thunk;
739 }
740
741 #endif /* CONFIG_MITIGATION_ITS */
742
743 /*
744 * Rewrite the compiler generated retpoline thunk calls.
745 *
746 * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
747 * indirect instructions, avoiding the extra indirection.
748 *
749 * For example, convert:
750 *
751 * CALL __x86_indirect_thunk_\reg
752 *
753 * into:
754 *
755 * CALL *%\reg
756 *
757 * It also tries to inline spectre_v2=retpoline,lfence when size permits.
758 */
patch_retpoline(void * addr,struct insn * insn,u8 * bytes)759 static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
760 {
761 retpoline_thunk_t *target;
762 int reg, ret, i = 0;
763 u8 op, cc;
764
765 target = addr + insn->length + insn->immediate.value;
766 reg = target - __x86_indirect_thunk_array;
767
768 if (WARN_ON_ONCE(reg & ~0xf))
769 return -1;
770
771 /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
772 BUG_ON(reg == 4);
773
774 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
775 !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
776 if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
777 return emit_call_track_retpoline(addr, insn, reg, bytes);
778
779 return -1;
780 }
781
782 op = insn->opcode.bytes[0];
783
784 /*
785 * Convert:
786 *
787 * Jcc.d32 __x86_indirect_thunk_\reg
788 *
789 * into:
790 *
791 * Jncc.d8 1f
792 * [ LFENCE ]
793 * JMP *%\reg
794 * [ NOP ]
795 * 1:
796 */
797 if (is_jcc32(insn)) {
798 cc = insn->opcode.bytes[1] & 0xf;
799 cc ^= 1; /* invert condition */
800
801 bytes[i++] = 0x70 + cc; /* Jcc.d8 */
802 bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
803
804 /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
805 op = JMP32_INSN_OPCODE;
806 }
807
808 /*
809 * For RETPOLINE_LFENCE: prepend the indirect CALL/JMP with an LFENCE.
810 */
811 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
812 bytes[i++] = 0x0f;
813 bytes[i++] = 0xae;
814 bytes[i++] = 0xe8; /* LFENCE */
815 }
816
817 #ifdef CONFIG_MITIGATION_ITS
818 /*
819 * Check if the address of last byte of emitted-indirect is in
820 * lower-half of the cacheline. Such branches need ITS mitigation.
821 */
822 if (cpu_wants_indirect_its_thunk_at((unsigned long)addr + i, reg))
823 return emit_its_trampoline(addr, insn, reg, bytes);
824 #endif
825
826 ret = emit_indirect(op, reg, bytes + i);
827 if (ret < 0)
828 return ret;
829 i += ret;
830
831 /*
832 * The compiler is supposed to EMIT an INT3 after every unconditional
833 * JMP instruction due to AMD BTC. However, if the compiler is too old
834 * or SLS isn't enabled, we still need an INT3 after indirect JMPs
835 * even on Intel.
836 */
837 if (op == JMP32_INSN_OPCODE && i < insn->length)
838 bytes[i++] = INT3_INSN_OPCODE;
839
840 for (; i < insn->length;)
841 bytes[i++] = BYTES_NOP1;
842
843 return i;
844 }
845
846 /*
847 * Generated by 'objtool --retpoline'.
848 */
apply_retpolines(s32 * start,s32 * end)849 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
850 {
851 s32 *s;
852
853 for (s = start; s < end; s++) {
854 void *addr = (void *)s + *s;
855 struct insn insn;
856 int len, ret;
857 u8 bytes[16];
858 u8 op1, op2;
859
860 ret = insn_decode_kernel(&insn, addr);
861 if (WARN_ON_ONCE(ret < 0))
862 continue;
863
864 op1 = insn.opcode.bytes[0];
865 op2 = insn.opcode.bytes[1];
866
867 switch (op1) {
868 case CALL_INSN_OPCODE:
869 case JMP32_INSN_OPCODE:
870 break;
871
872 case 0x0f: /* escape */
873 if (op2 >= 0x80 && op2 <= 0x8f)
874 break;
875 fallthrough;
876 default:
877 WARN_ON_ONCE(1);
878 continue;
879 }
880
881 DPRINTK(RETPOLINE, "retpoline at: %pS (%px) len: %d to: %pS",
882 addr, addr, insn.length,
883 addr + insn.length + insn.immediate.value);
884
885 len = patch_retpoline(addr, &insn, bytes);
886 if (len == insn.length) {
887 optimize_nops(bytes, len);
888 DUMP_BYTES(RETPOLINE, ((u8*)addr), len, "%px: orig: ", addr);
889 DUMP_BYTES(RETPOLINE, ((u8*)bytes), len, "%px: repl: ", addr);
890 text_poke_early(addr, bytes, len);
891 }
892 }
893 }
894
895 #ifdef CONFIG_RETHUNK
896
cpu_wants_rethunk(void)897 bool cpu_wants_rethunk(void)
898 {
899 return cpu_feature_enabled(X86_FEATURE_RETHUNK);
900 }
901
cpu_wants_rethunk_at(void * addr)902 bool cpu_wants_rethunk_at(void *addr)
903 {
904 if (!cpu_feature_enabled(X86_FEATURE_RETHUNK))
905 return false;
906 if (x86_return_thunk != its_return_thunk)
907 return true;
908
909 return !((unsigned long)addr & 0x20);
910 }
911
912 /*
913 * Rewrite the compiler generated return thunk tail-calls.
914 *
915 * For example, convert:
916 *
917 * JMP __x86_return_thunk
918 *
919 * into:
920 *
921 * RET
922 */
patch_return(void * addr,struct insn * insn,u8 * bytes)923 static int patch_return(void *addr, struct insn *insn, u8 *bytes)
924 {
925 int i = 0;
926
927 /* Patch the custom return thunks... */
928 if (cpu_wants_rethunk_at(addr)) {
929 i = JMP32_INSN_SIZE;
930 __text_gen_insn(bytes, JMP32_INSN_OPCODE, addr, x86_return_thunk, i);
931 } else {
932 /* ... or patch them out if not needed. */
933 bytes[i++] = RET_INSN_OPCODE;
934 }
935
936 for (; i < insn->length;)
937 bytes[i++] = INT3_INSN_OPCODE;
938 return i;
939 }
940
apply_returns(s32 * start,s32 * end)941 void __init_or_module noinline apply_returns(s32 *start, s32 *end)
942 {
943 s32 *s;
944
945 if (cpu_wants_rethunk())
946 static_call_force_reinit();
947
948 for (s = start; s < end; s++) {
949 void *dest = NULL, *addr = (void *)s + *s;
950 struct insn insn;
951 int len, ret;
952 u8 bytes[16];
953 u8 op;
954
955 ret = insn_decode_kernel(&insn, addr);
956 if (WARN_ON_ONCE(ret < 0))
957 continue;
958
959 op = insn.opcode.bytes[0];
960 if (op == JMP32_INSN_OPCODE)
961 dest = addr + insn.length + insn.immediate.value;
962
963 if (__static_call_fixup(addr, op, dest) ||
964 WARN_ONCE(dest != &__x86_return_thunk,
965 "missing return thunk: %pS-%pS: %*ph",
966 addr, dest, 5, addr))
967 continue;
968
969 DPRINTK(RET, "return thunk at: %pS (%px) len: %d to: %pS",
970 addr, addr, insn.length,
971 addr + insn.length + insn.immediate.value);
972
973 len = patch_return(addr, &insn, bytes);
974 if (len == insn.length) {
975 DUMP_BYTES(RET, ((u8*)addr), len, "%px: orig: ", addr);
976 DUMP_BYTES(RET, ((u8*)bytes), len, "%px: repl: ", addr);
977 text_poke_early(addr, bytes, len);
978 }
979 }
980 }
981 #else
apply_returns(s32 * start,s32 * end)982 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
983 #endif /* CONFIG_RETHUNK */
984
985 #else /* !CONFIG_RETPOLINE || !CONFIG_OBJTOOL */
986
apply_retpolines(s32 * start,s32 * end)987 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
apply_returns(s32 * start,s32 * end)988 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
989
990 #endif /* CONFIG_RETPOLINE && CONFIG_OBJTOOL */
991
992 #ifdef CONFIG_X86_KERNEL_IBT
993
994 static void poison_cfi(void *addr);
995
poison_endbr(void * addr,bool warn)996 static void __init_or_module poison_endbr(void *addr, bool warn)
997 {
998 u32 endbr, poison = gen_endbr_poison();
999
1000 if (WARN_ON_ONCE(get_kernel_nofault(endbr, addr)))
1001 return;
1002
1003 if (!is_endbr(endbr)) {
1004 WARN_ON_ONCE(warn);
1005 return;
1006 }
1007
1008 DPRINTK(ENDBR, "ENDBR at: %pS (%px)", addr, addr);
1009
1010 /*
1011 * When we have IBT, the lack of ENDBR will trigger #CP
1012 */
1013 DUMP_BYTES(ENDBR, ((u8*)addr), 4, "%px: orig: ", addr);
1014 DUMP_BYTES(ENDBR, ((u8*)&poison), 4, "%px: repl: ", addr);
1015 text_poke_early(addr, &poison, 4);
1016 }
1017
1018 /*
1019 * Generated by: objtool --ibt
1020 *
1021 * Seal the functions for indirect calls by clobbering the ENDBR instructions
1022 * and the kCFI hash value.
1023 */
apply_seal_endbr(s32 * start,s32 * end)1024 void __init_or_module noinline apply_seal_endbr(s32 *start, s32 *end)
1025 {
1026 s32 *s;
1027
1028 for (s = start; s < end; s++) {
1029 void *addr = (void *)s + *s;
1030
1031 poison_endbr(addr, true);
1032 if (IS_ENABLED(CONFIG_FINEIBT))
1033 poison_cfi(addr - 16);
1034 }
1035 }
1036
1037 #else
1038
apply_seal_endbr(s32 * start,s32 * end)1039 void __init_or_module apply_seal_endbr(s32 *start, s32 *end) { }
1040
1041 #endif /* CONFIG_X86_KERNEL_IBT */
1042
1043 #ifdef CONFIG_FINEIBT
1044
1045 enum cfi_mode {
1046 CFI_DEFAULT,
1047 CFI_OFF,
1048 CFI_KCFI,
1049 CFI_FINEIBT,
1050 };
1051
1052 static enum cfi_mode cfi_mode __ro_after_init = CFI_DEFAULT;
1053 static bool cfi_rand __ro_after_init = true;
1054 static u32 cfi_seed __ro_after_init;
1055
1056 /*
1057 * Re-hash the CFI hash with a boot-time seed while making sure the result is
1058 * not a valid ENDBR instruction.
1059 */
cfi_rehash(u32 hash)1060 static u32 cfi_rehash(u32 hash)
1061 {
1062 hash ^= cfi_seed;
1063 while (unlikely(is_endbr(hash) || is_endbr(-hash))) {
1064 bool lsb = hash & 1;
1065 hash >>= 1;
1066 if (lsb)
1067 hash ^= 0x80200003;
1068 }
1069 return hash;
1070 }
1071
cfi_parse_cmdline(char * str)1072 static __init int cfi_parse_cmdline(char *str)
1073 {
1074 if (!str)
1075 return -EINVAL;
1076
1077 while (str) {
1078 char *next = strchr(str, ',');
1079 if (next) {
1080 *next = 0;
1081 next++;
1082 }
1083
1084 if (!strcmp(str, "auto")) {
1085 cfi_mode = CFI_DEFAULT;
1086 } else if (!strcmp(str, "off")) {
1087 cfi_mode = CFI_OFF;
1088 cfi_rand = false;
1089 } else if (!strcmp(str, "kcfi")) {
1090 cfi_mode = CFI_KCFI;
1091 } else if (!strcmp(str, "fineibt")) {
1092 cfi_mode = CFI_FINEIBT;
1093 } else if (!strcmp(str, "norand")) {
1094 cfi_rand = false;
1095 } else {
1096 pr_err("Ignoring unknown cfi option (%s).", str);
1097 }
1098
1099 str = next;
1100 }
1101
1102 return 0;
1103 }
1104 early_param("cfi", cfi_parse_cmdline);
1105
1106 /*
1107 * kCFI FineIBT
1108 *
1109 * __cfi_\func: __cfi_\func:
1110 * movl $0x12345678,%eax // 5 endbr64 // 4
1111 * nop subl $0x12345678,%r10d // 7
1112 * nop jz 1f // 2
1113 * nop ud2 // 2
1114 * nop 1: nop // 1
1115 * nop
1116 * nop
1117 * nop
1118 * nop
1119 * nop
1120 * nop
1121 * nop
1122 *
1123 *
1124 * caller: caller:
1125 * movl $(-0x12345678),%r10d // 6 movl $0x12345678,%r10d // 6
1126 * addl $-15(%r11),%r10d // 4 sub $16,%r11 // 4
1127 * je 1f // 2 nop4 // 4
1128 * ud2 // 2
1129 * 1: call __x86_indirect_thunk_r11 // 5 call *%r11; nop2; // 5
1130 *
1131 */
1132
1133 asm( ".pushsection .rodata \n"
1134 "fineibt_preamble_start: \n"
1135 " endbr64 \n"
1136 " subl $0x12345678, %r10d \n"
1137 " je fineibt_preamble_end \n"
1138 " ud2 \n"
1139 " nop \n"
1140 "fineibt_preamble_end: \n"
1141 ".popsection\n"
1142 );
1143
1144 extern u8 fineibt_preamble_start[];
1145 extern u8 fineibt_preamble_end[];
1146
1147 #define fineibt_preamble_size (fineibt_preamble_end - fineibt_preamble_start)
1148 #define fineibt_preamble_hash 7
1149
1150 asm( ".pushsection .rodata \n"
1151 "fineibt_caller_start: \n"
1152 " movl $0x12345678, %r10d \n"
1153 " sub $16, %r11 \n"
1154 ASM_NOP4
1155 "fineibt_caller_end: \n"
1156 ".popsection \n"
1157 );
1158
1159 extern u8 fineibt_caller_start[];
1160 extern u8 fineibt_caller_end[];
1161
1162 #define fineibt_caller_size (fineibt_caller_end - fineibt_caller_start)
1163 #define fineibt_caller_hash 2
1164
1165 #define fineibt_caller_jmp (fineibt_caller_size - 2)
1166
decode_preamble_hash(void * addr)1167 static u32 decode_preamble_hash(void *addr)
1168 {
1169 u8 *p = addr;
1170
1171 /* b8 78 56 34 12 mov $0x12345678,%eax */
1172 if (p[0] == 0xb8)
1173 return *(u32 *)(addr + 1);
1174
1175 return 0; /* invalid hash value */
1176 }
1177
decode_caller_hash(void * addr)1178 static u32 decode_caller_hash(void *addr)
1179 {
1180 u8 *p = addr;
1181
1182 /* 41 ba 78 56 34 12 mov $0x12345678,%r10d */
1183 if (p[0] == 0x41 && p[1] == 0xba)
1184 return -*(u32 *)(addr + 2);
1185
1186 /* e8 0c 78 56 34 12 jmp.d8 +12 */
1187 if (p[0] == JMP8_INSN_OPCODE && p[1] == fineibt_caller_jmp)
1188 return -*(u32 *)(addr + 2);
1189
1190 return 0; /* invalid hash value */
1191 }
1192
1193 /* .retpoline_sites */
cfi_disable_callers(s32 * start,s32 * end)1194 static int cfi_disable_callers(s32 *start, s32 *end)
1195 {
1196 /*
1197 * Disable kCFI by patching in a JMP.d8, this leaves the hash immediate
1198 * in tact for later usage. Also see decode_caller_hash() and
1199 * cfi_rewrite_callers().
1200 */
1201 const u8 jmp[] = { JMP8_INSN_OPCODE, fineibt_caller_jmp };
1202 s32 *s;
1203
1204 for (s = start; s < end; s++) {
1205 void *addr = (void *)s + *s;
1206 u32 hash;
1207
1208 addr -= fineibt_caller_size;
1209 hash = decode_caller_hash(addr);
1210 if (!hash) /* nocfi callers */
1211 continue;
1212
1213 text_poke_early(addr, jmp, 2);
1214 }
1215
1216 return 0;
1217 }
1218
cfi_enable_callers(s32 * start,s32 * end)1219 static int cfi_enable_callers(s32 *start, s32 *end)
1220 {
1221 /*
1222 * Re-enable kCFI, undo what cfi_disable_callers() did.
1223 */
1224 const u8 mov[] = { 0x41, 0xba };
1225 s32 *s;
1226
1227 for (s = start; s < end; s++) {
1228 void *addr = (void *)s + *s;
1229 u32 hash;
1230
1231 addr -= fineibt_caller_size;
1232 hash = decode_caller_hash(addr);
1233 if (!hash) /* nocfi callers */
1234 continue;
1235
1236 text_poke_early(addr, mov, 2);
1237 }
1238
1239 return 0;
1240 }
1241
1242 /* .cfi_sites */
cfi_rand_preamble(s32 * start,s32 * end)1243 static int cfi_rand_preamble(s32 *start, s32 *end)
1244 {
1245 s32 *s;
1246
1247 for (s = start; s < end; s++) {
1248 void *addr = (void *)s + *s;
1249 u32 hash;
1250
1251 hash = decode_preamble_hash(addr);
1252 if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1253 addr, addr, 5, addr))
1254 return -EINVAL;
1255
1256 hash = cfi_rehash(hash);
1257 text_poke_early(addr + 1, &hash, 4);
1258 }
1259
1260 return 0;
1261 }
1262
cfi_rewrite_preamble(s32 * start,s32 * end)1263 static int cfi_rewrite_preamble(s32 *start, s32 *end)
1264 {
1265 s32 *s;
1266
1267 for (s = start; s < end; s++) {
1268 void *addr = (void *)s + *s;
1269 u32 hash;
1270
1271 hash = decode_preamble_hash(addr);
1272 if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1273 addr, addr, 5, addr))
1274 return -EINVAL;
1275
1276 text_poke_early(addr, fineibt_preamble_start, fineibt_preamble_size);
1277 WARN_ON(*(u32 *)(addr + fineibt_preamble_hash) != 0x12345678);
1278 text_poke_early(addr + fineibt_preamble_hash, &hash, 4);
1279 }
1280
1281 return 0;
1282 }
1283
cfi_rewrite_endbr(s32 * start,s32 * end)1284 static void cfi_rewrite_endbr(s32 *start, s32 *end)
1285 {
1286 s32 *s;
1287
1288 for (s = start; s < end; s++) {
1289 void *addr = (void *)s + *s;
1290
1291 poison_endbr(addr+16, false);
1292 }
1293 }
1294
1295 /* .retpoline_sites */
cfi_rand_callers(s32 * start,s32 * end)1296 static int cfi_rand_callers(s32 *start, s32 *end)
1297 {
1298 s32 *s;
1299
1300 for (s = start; s < end; s++) {
1301 void *addr = (void *)s + *s;
1302 u32 hash;
1303
1304 addr -= fineibt_caller_size;
1305 hash = decode_caller_hash(addr);
1306 if (hash) {
1307 hash = -cfi_rehash(hash);
1308 text_poke_early(addr + 2, &hash, 4);
1309 }
1310 }
1311
1312 return 0;
1313 }
1314
cfi_rewrite_callers(s32 * start,s32 * end)1315 static int cfi_rewrite_callers(s32 *start, s32 *end)
1316 {
1317 s32 *s;
1318
1319 for (s = start; s < end; s++) {
1320 void *addr = (void *)s + *s;
1321 u32 hash;
1322
1323 addr -= fineibt_caller_size;
1324 hash = decode_caller_hash(addr);
1325 if (hash) {
1326 text_poke_early(addr, fineibt_caller_start, fineibt_caller_size);
1327 WARN_ON(*(u32 *)(addr + fineibt_caller_hash) != 0x12345678);
1328 text_poke_early(addr + fineibt_caller_hash, &hash, 4);
1329 }
1330 /* rely on apply_retpolines() */
1331 }
1332
1333 return 0;
1334 }
1335
__apply_fineibt(s32 * start_retpoline,s32 * end_retpoline,s32 * start_cfi,s32 * end_cfi,bool builtin)1336 static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1337 s32 *start_cfi, s32 *end_cfi, bool builtin)
1338 {
1339 int ret;
1340
1341 if (WARN_ONCE(fineibt_preamble_size != 16,
1342 "FineIBT preamble wrong size: %ld", fineibt_preamble_size))
1343 return;
1344
1345 if (cfi_mode == CFI_DEFAULT) {
1346 cfi_mode = CFI_KCFI;
1347 if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT))
1348 cfi_mode = CFI_FINEIBT;
1349 }
1350
1351 /*
1352 * Rewrite the callers to not use the __cfi_ stubs, such that we might
1353 * rewrite them. This disables all CFI. If this succeeds but any of the
1354 * later stages fails, we're without CFI.
1355 */
1356 ret = cfi_disable_callers(start_retpoline, end_retpoline);
1357 if (ret)
1358 goto err;
1359
1360 if (cfi_rand) {
1361 if (builtin)
1362 cfi_seed = get_random_u32();
1363
1364 ret = cfi_rand_preamble(start_cfi, end_cfi);
1365 if (ret)
1366 goto err;
1367
1368 ret = cfi_rand_callers(start_retpoline, end_retpoline);
1369 if (ret)
1370 goto err;
1371 }
1372
1373 switch (cfi_mode) {
1374 case CFI_OFF:
1375 if (builtin)
1376 pr_info("Disabling CFI\n");
1377 return;
1378
1379 case CFI_KCFI:
1380 ret = cfi_enable_callers(start_retpoline, end_retpoline);
1381 if (ret)
1382 goto err;
1383
1384 if (builtin)
1385 pr_info("Using kCFI\n");
1386 return;
1387
1388 case CFI_FINEIBT:
1389 /* place the FineIBT preamble at func()-16 */
1390 ret = cfi_rewrite_preamble(start_cfi, end_cfi);
1391 if (ret)
1392 goto err;
1393
1394 /* rewrite the callers to target func()-16 */
1395 ret = cfi_rewrite_callers(start_retpoline, end_retpoline);
1396 if (ret)
1397 goto err;
1398
1399 /* now that nobody targets func()+0, remove ENDBR there */
1400 cfi_rewrite_endbr(start_cfi, end_cfi);
1401
1402 if (builtin)
1403 pr_info("Using FineIBT CFI\n");
1404 return;
1405
1406 default:
1407 break;
1408 }
1409
1410 err:
1411 pr_err("Something went horribly wrong trying to rewrite the CFI implementation.\n");
1412 }
1413
poison_hash(void * addr)1414 static inline void poison_hash(void *addr)
1415 {
1416 *(u32 *)addr = 0;
1417 }
1418
poison_cfi(void * addr)1419 static void poison_cfi(void *addr)
1420 {
1421 switch (cfi_mode) {
1422 case CFI_FINEIBT:
1423 /*
1424 * __cfi_\func:
1425 * osp nopl (%rax)
1426 * subl $0, %r10d
1427 * jz 1f
1428 * ud2
1429 * 1: nop
1430 */
1431 poison_endbr(addr, false);
1432 poison_hash(addr + fineibt_preamble_hash);
1433 break;
1434
1435 case CFI_KCFI:
1436 /*
1437 * __cfi_\func:
1438 * movl $0, %eax
1439 * .skip 11, 0x90
1440 */
1441 poison_hash(addr + 1);
1442 break;
1443
1444 default:
1445 break;
1446 }
1447 }
1448
1449 #else
1450
__apply_fineibt(s32 * start_retpoline,s32 * end_retpoline,s32 * start_cfi,s32 * end_cfi,bool builtin)1451 static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1452 s32 *start_cfi, s32 *end_cfi, bool builtin)
1453 {
1454 }
1455
1456 #ifdef CONFIG_X86_KERNEL_IBT
poison_cfi(void * addr)1457 static void poison_cfi(void *addr) { }
1458 #endif
1459
1460 #endif
1461
apply_fineibt(s32 * start_retpoline,s32 * end_retpoline,s32 * start_cfi,s32 * end_cfi)1462 void apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1463 s32 *start_cfi, s32 *end_cfi)
1464 {
1465 return __apply_fineibt(start_retpoline, end_retpoline,
1466 start_cfi, end_cfi,
1467 /* .builtin = */ false);
1468 }
1469
1470 #ifdef CONFIG_SMP
alternatives_smp_lock(const s32 * start,const s32 * end,u8 * text,u8 * text_end)1471 static void alternatives_smp_lock(const s32 *start, const s32 *end,
1472 u8 *text, u8 *text_end)
1473 {
1474 const s32 *poff;
1475
1476 for (poff = start; poff < end; poff++) {
1477 u8 *ptr = (u8 *)poff + *poff;
1478
1479 if (!*poff || ptr < text || ptr >= text_end)
1480 continue;
1481 /* turn DS segment override prefix into lock prefix */
1482 if (*ptr == 0x3e)
1483 text_poke(ptr, ((unsigned char []){0xf0}), 1);
1484 }
1485 }
1486
alternatives_smp_unlock(const s32 * start,const s32 * end,u8 * text,u8 * text_end)1487 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
1488 u8 *text, u8 *text_end)
1489 {
1490 const s32 *poff;
1491
1492 for (poff = start; poff < end; poff++) {
1493 u8 *ptr = (u8 *)poff + *poff;
1494
1495 if (!*poff || ptr < text || ptr >= text_end)
1496 continue;
1497 /* turn lock prefix into DS segment override prefix */
1498 if (*ptr == 0xf0)
1499 text_poke(ptr, ((unsigned char []){0x3E}), 1);
1500 }
1501 }
1502
1503 struct smp_alt_module {
1504 /* what is this ??? */
1505 struct module *mod;
1506 char *name;
1507
1508 /* ptrs to lock prefixes */
1509 const s32 *locks;
1510 const s32 *locks_end;
1511
1512 /* .text segment, needed to avoid patching init code ;) */
1513 u8 *text;
1514 u8 *text_end;
1515
1516 struct list_head next;
1517 };
1518 static LIST_HEAD(smp_alt_modules);
1519 static bool uniproc_patched = false; /* protected by text_mutex */
1520
alternatives_smp_module_add(struct module * mod,char * name,void * locks,void * locks_end,void * text,void * text_end)1521 void __init_or_module alternatives_smp_module_add(struct module *mod,
1522 char *name,
1523 void *locks, void *locks_end,
1524 void *text, void *text_end)
1525 {
1526 struct smp_alt_module *smp;
1527
1528 mutex_lock(&text_mutex);
1529 if (!uniproc_patched)
1530 goto unlock;
1531
1532 if (num_possible_cpus() == 1)
1533 /* Don't bother remembering, we'll never have to undo it. */
1534 goto smp_unlock;
1535
1536 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
1537 if (NULL == smp)
1538 /* we'll run the (safe but slow) SMP code then ... */
1539 goto unlock;
1540
1541 smp->mod = mod;
1542 smp->name = name;
1543 smp->locks = locks;
1544 smp->locks_end = locks_end;
1545 smp->text = text;
1546 smp->text_end = text_end;
1547 DPRINTK(SMP, "locks %p -> %p, text %p -> %p, name %s\n",
1548 smp->locks, smp->locks_end,
1549 smp->text, smp->text_end, smp->name);
1550
1551 list_add_tail(&smp->next, &smp_alt_modules);
1552 smp_unlock:
1553 alternatives_smp_unlock(locks, locks_end, text, text_end);
1554 unlock:
1555 mutex_unlock(&text_mutex);
1556 }
1557
alternatives_smp_module_del(struct module * mod)1558 void __init_or_module alternatives_smp_module_del(struct module *mod)
1559 {
1560 struct smp_alt_module *item;
1561
1562 mutex_lock(&text_mutex);
1563 list_for_each_entry(item, &smp_alt_modules, next) {
1564 if (mod != item->mod)
1565 continue;
1566 list_del(&item->next);
1567 kfree(item);
1568 break;
1569 }
1570 mutex_unlock(&text_mutex);
1571 }
1572
alternatives_enable_smp(void)1573 void alternatives_enable_smp(void)
1574 {
1575 struct smp_alt_module *mod;
1576
1577 /* Why bother if there are no other CPUs? */
1578 BUG_ON(num_possible_cpus() == 1);
1579
1580 mutex_lock(&text_mutex);
1581
1582 if (uniproc_patched) {
1583 pr_info("switching to SMP code\n");
1584 BUG_ON(num_online_cpus() != 1);
1585 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
1586 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
1587 list_for_each_entry(mod, &smp_alt_modules, next)
1588 alternatives_smp_lock(mod->locks, mod->locks_end,
1589 mod->text, mod->text_end);
1590 uniproc_patched = false;
1591 }
1592 mutex_unlock(&text_mutex);
1593 }
1594
1595 /*
1596 * Return 1 if the address range is reserved for SMP-alternatives.
1597 * Must hold text_mutex.
1598 */
alternatives_text_reserved(void * start,void * end)1599 int alternatives_text_reserved(void *start, void *end)
1600 {
1601 struct smp_alt_module *mod;
1602 const s32 *poff;
1603 u8 *text_start = start;
1604 u8 *text_end = end;
1605
1606 lockdep_assert_held(&text_mutex);
1607
1608 list_for_each_entry(mod, &smp_alt_modules, next) {
1609 if (mod->text > text_end || mod->text_end < text_start)
1610 continue;
1611 for (poff = mod->locks; poff < mod->locks_end; poff++) {
1612 const u8 *ptr = (const u8 *)poff + *poff;
1613
1614 if (text_start <= ptr && text_end > ptr)
1615 return 1;
1616 }
1617 }
1618
1619 return 0;
1620 }
1621 #endif /* CONFIG_SMP */
1622
1623 #ifdef CONFIG_PARAVIRT
1624
1625 /* Use this to add nops to a buffer, then text_poke the whole buffer. */
add_nops(void * insns,unsigned int len)1626 static void __init_or_module add_nops(void *insns, unsigned int len)
1627 {
1628 while (len > 0) {
1629 unsigned int noplen = len;
1630 if (noplen > ASM_NOP_MAX)
1631 noplen = ASM_NOP_MAX;
1632 memcpy(insns, x86_nops[noplen], noplen);
1633 insns += noplen;
1634 len -= noplen;
1635 }
1636 }
1637
apply_paravirt(struct paravirt_patch_site * start,struct paravirt_patch_site * end)1638 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
1639 struct paravirt_patch_site *end)
1640 {
1641 struct paravirt_patch_site *p;
1642 char insn_buff[MAX_PATCH_LEN];
1643
1644 for (p = start; p < end; p++) {
1645 unsigned int used;
1646
1647 BUG_ON(p->len > MAX_PATCH_LEN);
1648 /* prep the buffer with the original instructions */
1649 memcpy(insn_buff, p->instr, p->len);
1650 used = paravirt_patch(p->type, insn_buff, (unsigned long)p->instr, p->len);
1651
1652 BUG_ON(used > p->len);
1653
1654 /* Pad the rest with nops */
1655 add_nops(insn_buff + used, p->len - used);
1656 text_poke_early(p->instr, insn_buff, p->len);
1657 }
1658 }
1659 extern struct paravirt_patch_site __start_parainstructions[],
1660 __stop_parainstructions[];
1661 #endif /* CONFIG_PARAVIRT */
1662
1663 /*
1664 * Self-test for the INT3 based CALL emulation code.
1665 *
1666 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
1667 * properly and that there is a stack gap between the INT3 frame and the
1668 * previous context. Without this gap doing a virtual PUSH on the interrupted
1669 * stack would corrupt the INT3 IRET frame.
1670 *
1671 * See entry_{32,64}.S for more details.
1672 */
1673
1674 /*
1675 * We define the int3_magic() function in assembly to control the calling
1676 * convention such that we can 'call' it from assembly.
1677 */
1678
1679 extern void int3_magic(unsigned int *ptr); /* defined in asm */
1680
1681 asm (
1682 " .pushsection .init.text, \"ax\", @progbits\n"
1683 " .type int3_magic, @function\n"
1684 "int3_magic:\n"
1685 ANNOTATE_NOENDBR
1686 " movl $1, (%" _ASM_ARG1 ")\n"
1687 ASM_RET
1688 " .size int3_magic, .-int3_magic\n"
1689 " .popsection\n"
1690 );
1691
1692 extern void int3_selftest_ip(void); /* defined in asm below */
1693
1694 static int __init
int3_exception_notify(struct notifier_block * self,unsigned long val,void * data)1695 int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
1696 {
1697 unsigned long selftest = (unsigned long)&int3_selftest_ip;
1698 struct die_args *args = data;
1699 struct pt_regs *regs = args->regs;
1700
1701 OPTIMIZER_HIDE_VAR(selftest);
1702
1703 if (!regs || user_mode(regs))
1704 return NOTIFY_DONE;
1705
1706 if (val != DIE_INT3)
1707 return NOTIFY_DONE;
1708
1709 if (regs->ip - INT3_INSN_SIZE != selftest)
1710 return NOTIFY_DONE;
1711
1712 int3_emulate_call(regs, (unsigned long)&int3_magic);
1713 return NOTIFY_STOP;
1714 }
1715
1716 /* Must be noinline to ensure uniqueness of int3_selftest_ip. */
int3_selftest(void)1717 static noinline void __init int3_selftest(void)
1718 {
1719 static __initdata struct notifier_block int3_exception_nb = {
1720 .notifier_call = int3_exception_notify,
1721 .priority = INT_MAX-1, /* last */
1722 };
1723 unsigned int val = 0;
1724
1725 BUG_ON(register_die_notifier(&int3_exception_nb));
1726
1727 /*
1728 * Basically: int3_magic(&val); but really complicated :-)
1729 *
1730 * INT3 padded with NOP to CALL_INSN_SIZE. The int3_exception_nb
1731 * notifier above will emulate CALL for us.
1732 */
1733 asm volatile ("int3_selftest_ip:\n\t"
1734 ANNOTATE_NOENDBR
1735 " int3; nop; nop; nop; nop\n\t"
1736 : ASM_CALL_CONSTRAINT
1737 : __ASM_SEL_RAW(a, D) (&val)
1738 : "memory");
1739
1740 BUG_ON(val != 1);
1741
1742 unregister_die_notifier(&int3_exception_nb);
1743 }
1744
1745 static __initdata int __alt_reloc_selftest_addr;
1746
1747 extern void __init __alt_reloc_selftest(void *arg);
__alt_reloc_selftest(void * arg)1748 __visible noinline void __init __alt_reloc_selftest(void *arg)
1749 {
1750 WARN_ON(arg != &__alt_reloc_selftest_addr);
1751 }
1752
alt_reloc_selftest(void)1753 static noinline void __init alt_reloc_selftest(void)
1754 {
1755 /*
1756 * Tests apply_relocation().
1757 *
1758 * This has a relative immediate (CALL) in a place other than the first
1759 * instruction and additionally on x86_64 we get a RIP-relative LEA:
1760 *
1761 * lea 0x0(%rip),%rdi # 5d0: R_X86_64_PC32 .init.data+0x5566c
1762 * call +0 # 5d5: R_X86_64_PLT32 __alt_reloc_selftest-0x4
1763 *
1764 * Getting this wrong will either crash and burn or tickle the WARN
1765 * above.
1766 */
1767 asm_inline volatile (
1768 ALTERNATIVE("", "lea %[mem], %%" _ASM_ARG1 "; call __alt_reloc_selftest;", X86_FEATURE_ALWAYS)
1769 : /* output */
1770 : [mem] "m" (__alt_reloc_selftest_addr)
1771 : _ASM_ARG1
1772 );
1773 }
1774
alternative_instructions(void)1775 void __init alternative_instructions(void)
1776 {
1777 u64 ibt;
1778
1779 int3_selftest();
1780
1781 /*
1782 * The patching is not fully atomic, so try to avoid local
1783 * interruptions that might execute the to be patched code.
1784 * Other CPUs are not running.
1785 */
1786 stop_nmi();
1787
1788 /*
1789 * Don't stop machine check exceptions while patching.
1790 * MCEs only happen when something got corrupted and in this
1791 * case we must do something about the corruption.
1792 * Ignoring it is worse than an unlikely patching race.
1793 * Also machine checks tend to be broadcast and if one CPU
1794 * goes into machine check the others follow quickly, so we don't
1795 * expect a machine check to cause undue problems during to code
1796 * patching.
1797 */
1798
1799 /*
1800 * Paravirt patching and alternative patching can be combined to
1801 * replace a function call with a short direct code sequence (e.g.
1802 * by setting a constant return value instead of doing that in an
1803 * external function).
1804 * In order to make this work the following sequence is required:
1805 * 1. set (artificial) features depending on used paravirt
1806 * functions which can later influence alternative patching
1807 * 2. apply paravirt patching (generally replacing an indirect
1808 * function call with a direct one)
1809 * 3. apply alternative patching (e.g. replacing a direct function
1810 * call with a custom code sequence)
1811 * Doing paravirt patching after alternative patching would clobber
1812 * the optimization of the custom code with a function call again.
1813 */
1814 paravirt_set_cap();
1815
1816 /* Keep CET-IBT disabled until caller/callee are patched */
1817 ibt = ibt_save(/*disable*/ true);
1818
1819 /*
1820 * First patch paravirt functions, such that we overwrite the indirect
1821 * call with the direct call.
1822 */
1823 apply_paravirt(__parainstructions, __parainstructions_end);
1824
1825 __apply_fineibt(__retpoline_sites, __retpoline_sites_end,
1826 __cfi_sites, __cfi_sites_end, true);
1827
1828 /*
1829 * Rewrite the retpolines, must be done before alternatives since
1830 * those can rewrite the retpoline thunks.
1831 */
1832 apply_retpolines(__retpoline_sites, __retpoline_sites_end);
1833 apply_returns(__return_sites, __return_sites_end);
1834
1835 /*
1836 * Then patch alternatives, such that those paravirt calls that are in
1837 * alternatives can be overwritten by their immediate fragments.
1838 */
1839 apply_alternatives(__alt_instructions, __alt_instructions_end);
1840
1841 /*
1842 * Now all calls are established. Apply the call thunks if
1843 * required.
1844 */
1845 callthunks_patch_builtin_calls();
1846
1847 /*
1848 * Seal all functions that do not have their address taken.
1849 */
1850 apply_seal_endbr(__ibt_endbr_seal, __ibt_endbr_seal_end);
1851
1852 ibt_restore(ibt);
1853
1854 #ifdef CONFIG_SMP
1855 /* Patch to UP if other cpus not imminent. */
1856 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
1857 uniproc_patched = true;
1858 alternatives_smp_module_add(NULL, "core kernel",
1859 __smp_locks, __smp_locks_end,
1860 _text, _etext);
1861 }
1862
1863 if (!uniproc_patched || num_possible_cpus() == 1) {
1864 free_init_pages("SMP alternatives",
1865 (unsigned long)__smp_locks,
1866 (unsigned long)__smp_locks_end);
1867 }
1868 #endif
1869
1870 restart_nmi();
1871 alternatives_patched = 1;
1872
1873 alt_reloc_selftest();
1874 }
1875
1876 /**
1877 * text_poke_early - Update instructions on a live kernel at boot time
1878 * @addr: address to modify
1879 * @opcode: source of the copy
1880 * @len: length to copy
1881 *
1882 * When you use this code to patch more than one byte of an instruction
1883 * you need to make sure that other CPUs cannot execute this code in parallel.
1884 * Also no thread must be currently preempted in the middle of these
1885 * instructions. And on the local CPU you need to be protected against NMI or
1886 * MCE handlers seeing an inconsistent instruction while you patch.
1887 */
text_poke_early(void * addr,const void * opcode,size_t len)1888 void __init_or_module text_poke_early(void *addr, const void *opcode,
1889 size_t len)
1890 {
1891 unsigned long flags;
1892
1893 if (boot_cpu_has(X86_FEATURE_NX) &&
1894 is_module_text_address((unsigned long)addr)) {
1895 /*
1896 * Modules text is marked initially as non-executable, so the
1897 * code cannot be running and speculative code-fetches are
1898 * prevented. Just change the code.
1899 */
1900 memcpy(addr, opcode, len);
1901 } else {
1902 local_irq_save(flags);
1903 memcpy(addr, opcode, len);
1904 sync_core();
1905 local_irq_restore(flags);
1906
1907 /*
1908 * Could also do a CLFLUSH here to speed up CPU recovery; but
1909 * that causes hangs on some VIA CPUs.
1910 */
1911 }
1912 }
1913
1914 typedef struct {
1915 struct mm_struct *mm;
1916 } temp_mm_state_t;
1917
1918 /*
1919 * Using a temporary mm allows to set temporary mappings that are not accessible
1920 * by other CPUs. Such mappings are needed to perform sensitive memory writes
1921 * that override the kernel memory protections (e.g., W^X), without exposing the
1922 * temporary page-table mappings that are required for these write operations to
1923 * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
1924 * mapping is torn down.
1925 *
1926 * Context: The temporary mm needs to be used exclusively by a single core. To
1927 * harden security IRQs must be disabled while the temporary mm is
1928 * loaded, thereby preventing interrupt handler bugs from overriding
1929 * the kernel memory protection.
1930 */
use_temporary_mm(struct mm_struct * mm)1931 static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
1932 {
1933 temp_mm_state_t temp_state;
1934
1935 lockdep_assert_irqs_disabled();
1936
1937 /*
1938 * Make sure not to be in TLB lazy mode, as otherwise we'll end up
1939 * with a stale address space WITHOUT being in lazy mode after
1940 * restoring the previous mm.
1941 */
1942 if (this_cpu_read(cpu_tlbstate_shared.is_lazy))
1943 leave_mm(smp_processor_id());
1944
1945 temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
1946 switch_mm_irqs_off(NULL, mm, current);
1947
1948 /*
1949 * If breakpoints are enabled, disable them while the temporary mm is
1950 * used. Userspace might set up watchpoints on addresses that are used
1951 * in the temporary mm, which would lead to wrong signals being sent or
1952 * crashes.
1953 *
1954 * Note that breakpoints are not disabled selectively, which also causes
1955 * kernel breakpoints (e.g., perf's) to be disabled. This might be
1956 * undesirable, but still seems reasonable as the code that runs in the
1957 * temporary mm should be short.
1958 */
1959 if (hw_breakpoint_active())
1960 hw_breakpoint_disable();
1961
1962 return temp_state;
1963 }
1964
unuse_temporary_mm(temp_mm_state_t prev_state)1965 static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
1966 {
1967 lockdep_assert_irqs_disabled();
1968 switch_mm_irqs_off(NULL, prev_state.mm, current);
1969
1970 /*
1971 * Restore the breakpoints if they were disabled before the temporary mm
1972 * was loaded.
1973 */
1974 if (hw_breakpoint_active())
1975 hw_breakpoint_restore();
1976 }
1977
1978 __ro_after_init struct mm_struct *poking_mm;
1979 __ro_after_init unsigned long poking_addr;
1980
text_poke_memcpy(void * dst,const void * src,size_t len)1981 static void text_poke_memcpy(void *dst, const void *src, size_t len)
1982 {
1983 memcpy(dst, src, len);
1984 }
1985
text_poke_memset(void * dst,const void * src,size_t len)1986 static void text_poke_memset(void *dst, const void *src, size_t len)
1987 {
1988 int c = *(const int *)src;
1989
1990 memset(dst, c, len);
1991 }
1992
1993 typedef void text_poke_f(void *dst, const void *src, size_t len);
1994
__text_poke(text_poke_f func,void * addr,const void * src,size_t len)1995 static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t len)
1996 {
1997 bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
1998 struct page *pages[2] = {NULL};
1999 temp_mm_state_t prev;
2000 unsigned long flags;
2001 pte_t pte, *ptep;
2002 spinlock_t *ptl;
2003 pgprot_t pgprot;
2004
2005 /*
2006 * While boot memory allocator is running we cannot use struct pages as
2007 * they are not yet initialized. There is no way to recover.
2008 */
2009 BUG_ON(!after_bootmem);
2010
2011 if (!core_kernel_text((unsigned long)addr)) {
2012 pages[0] = vmalloc_to_page(addr);
2013 if (cross_page_boundary)
2014 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
2015 } else {
2016 pages[0] = virt_to_page(addr);
2017 WARN_ON(!PageReserved(pages[0]));
2018 if (cross_page_boundary)
2019 pages[1] = virt_to_page(addr + PAGE_SIZE);
2020 }
2021 /*
2022 * If something went wrong, crash and burn since recovery paths are not
2023 * implemented.
2024 */
2025 BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
2026
2027 /*
2028 * Map the page without the global bit, as TLB flushing is done with
2029 * flush_tlb_mm_range(), which is intended for non-global PTEs.
2030 */
2031 pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
2032
2033 /*
2034 * The lock is not really needed, but this allows to avoid open-coding.
2035 */
2036 ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
2037
2038 /*
2039 * This must not fail; preallocated in poking_init().
2040 */
2041 VM_BUG_ON(!ptep);
2042
2043 local_irq_save(flags);
2044
2045 pte = mk_pte(pages[0], pgprot);
2046 set_pte_at(poking_mm, poking_addr, ptep, pte);
2047
2048 if (cross_page_boundary) {
2049 pte = mk_pte(pages[1], pgprot);
2050 set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
2051 }
2052
2053 /*
2054 * Loading the temporary mm behaves as a compiler barrier, which
2055 * guarantees that the PTE will be set at the time memcpy() is done.
2056 */
2057 prev = use_temporary_mm(poking_mm);
2058
2059 kasan_disable_current();
2060 func((u8 *)poking_addr + offset_in_page(addr), src, len);
2061 kasan_enable_current();
2062
2063 /*
2064 * Ensure that the PTE is only cleared after the instructions of memcpy
2065 * were issued by using a compiler barrier.
2066 */
2067 barrier();
2068
2069 pte_clear(poking_mm, poking_addr, ptep);
2070 if (cross_page_boundary)
2071 pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
2072
2073 /*
2074 * Loading the previous page-table hierarchy requires a serializing
2075 * instruction that already allows the core to see the updated version.
2076 * Xen-PV is assumed to serialize execution in a similar manner.
2077 */
2078 unuse_temporary_mm(prev);
2079
2080 /*
2081 * Flushing the TLB might involve IPIs, which would require enabled
2082 * IRQs, but not if the mm is not used, as it is in this point.
2083 */
2084 flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
2085 (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
2086 PAGE_SHIFT, false);
2087
2088 if (func == text_poke_memcpy) {
2089 /*
2090 * If the text does not match what we just wrote then something is
2091 * fundamentally screwy; there's nothing we can really do about that.
2092 */
2093 BUG_ON(memcmp(addr, src, len));
2094 }
2095
2096 local_irq_restore(flags);
2097 pte_unmap_unlock(ptep, ptl);
2098 return addr;
2099 }
2100
2101 /**
2102 * text_poke - Update instructions on a live kernel
2103 * @addr: address to modify
2104 * @opcode: source of the copy
2105 * @len: length to copy
2106 *
2107 * Only atomic text poke/set should be allowed when not doing early patching.
2108 * It means the size must be writable atomically and the address must be aligned
2109 * in a way that permits an atomic write. It also makes sure we fit on a single
2110 * page.
2111 *
2112 * Note that the caller must ensure that if the modified code is part of a
2113 * module, the module would not be removed during poking. This can be achieved
2114 * by registering a module notifier, and ordering module removal and patching
2115 * trough a mutex.
2116 */
text_poke(void * addr,const void * opcode,size_t len)2117 void *text_poke(void *addr, const void *opcode, size_t len)
2118 {
2119 lockdep_assert_held(&text_mutex);
2120
2121 return __text_poke(text_poke_memcpy, addr, opcode, len);
2122 }
2123
2124 /**
2125 * text_poke_kgdb - Update instructions on a live kernel by kgdb
2126 * @addr: address to modify
2127 * @opcode: source of the copy
2128 * @len: length to copy
2129 *
2130 * Only atomic text poke/set should be allowed when not doing early patching.
2131 * It means the size must be writable atomically and the address must be aligned
2132 * in a way that permits an atomic write. It also makes sure we fit on a single
2133 * page.
2134 *
2135 * Context: should only be used by kgdb, which ensures no other core is running,
2136 * despite the fact it does not hold the text_mutex.
2137 */
text_poke_kgdb(void * addr,const void * opcode,size_t len)2138 void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
2139 {
2140 return __text_poke(text_poke_memcpy, addr, opcode, len);
2141 }
2142
text_poke_copy_locked(void * addr,const void * opcode,size_t len,bool core_ok)2143 void *text_poke_copy_locked(void *addr, const void *opcode, size_t len,
2144 bool core_ok)
2145 {
2146 unsigned long start = (unsigned long)addr;
2147 size_t patched = 0;
2148
2149 if (WARN_ON_ONCE(!core_ok && core_kernel_text(start)))
2150 return NULL;
2151
2152 while (patched < len) {
2153 unsigned long ptr = start + patched;
2154 size_t s;
2155
2156 s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
2157
2158 __text_poke(text_poke_memcpy, (void *)ptr, opcode + patched, s);
2159 patched += s;
2160 }
2161 return addr;
2162 }
2163
2164 /**
2165 * text_poke_copy - Copy instructions into (an unused part of) RX memory
2166 * @addr: address to modify
2167 * @opcode: source of the copy
2168 * @len: length to copy, could be more than 2x PAGE_SIZE
2169 *
2170 * Not safe against concurrent execution; useful for JITs to dump
2171 * new code blocks into unused regions of RX memory. Can be used in
2172 * conjunction with synchronize_rcu_tasks() to wait for existing
2173 * execution to quiesce after having made sure no existing functions
2174 * pointers are live.
2175 */
text_poke_copy(void * addr,const void * opcode,size_t len)2176 void *text_poke_copy(void *addr, const void *opcode, size_t len)
2177 {
2178 mutex_lock(&text_mutex);
2179 addr = text_poke_copy_locked(addr, opcode, len, false);
2180 mutex_unlock(&text_mutex);
2181 return addr;
2182 }
2183
2184 /**
2185 * text_poke_set - memset into (an unused part of) RX memory
2186 * @addr: address to modify
2187 * @c: the byte to fill the area with
2188 * @len: length to copy, could be more than 2x PAGE_SIZE
2189 *
2190 * This is useful to overwrite unused regions of RX memory with illegal
2191 * instructions.
2192 */
text_poke_set(void * addr,int c,size_t len)2193 void *text_poke_set(void *addr, int c, size_t len)
2194 {
2195 unsigned long start = (unsigned long)addr;
2196 size_t patched = 0;
2197
2198 if (WARN_ON_ONCE(core_kernel_text(start)))
2199 return NULL;
2200
2201 mutex_lock(&text_mutex);
2202 while (patched < len) {
2203 unsigned long ptr = start + patched;
2204 size_t s;
2205
2206 s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
2207
2208 __text_poke(text_poke_memset, (void *)ptr, (void *)&c, s);
2209 patched += s;
2210 }
2211 mutex_unlock(&text_mutex);
2212 return addr;
2213 }
2214
do_sync_core(void * info)2215 static void do_sync_core(void *info)
2216 {
2217 sync_core();
2218 }
2219
text_poke_sync(void)2220 void text_poke_sync(void)
2221 {
2222 on_each_cpu(do_sync_core, NULL, 1);
2223 }
2224
2225 /*
2226 * NOTE: crazy scheme to allow patching Jcc.d32 but not increase the size of
2227 * this thing. When len == 6 everything is prefixed with 0x0f and we map
2228 * opcode to Jcc.d8, using len to distinguish.
2229 */
2230 struct text_poke_loc {
2231 /* addr := _stext + rel_addr */
2232 s32 rel_addr;
2233 s32 disp;
2234 u8 len;
2235 u8 opcode;
2236 const u8 text[POKE_MAX_OPCODE_SIZE];
2237 /* see text_poke_bp_batch() */
2238 u8 old;
2239 };
2240
2241 struct bp_patching_desc {
2242 struct text_poke_loc *vec;
2243 int nr_entries;
2244 atomic_t refs;
2245 };
2246
2247 static struct bp_patching_desc bp_desc;
2248
2249 static __always_inline
try_get_desc(void)2250 struct bp_patching_desc *try_get_desc(void)
2251 {
2252 struct bp_patching_desc *desc = &bp_desc;
2253
2254 if (!raw_atomic_inc_not_zero(&desc->refs))
2255 return NULL;
2256
2257 return desc;
2258 }
2259
put_desc(void)2260 static __always_inline void put_desc(void)
2261 {
2262 struct bp_patching_desc *desc = &bp_desc;
2263
2264 smp_mb__before_atomic();
2265 raw_atomic_dec(&desc->refs);
2266 }
2267
text_poke_addr(struct text_poke_loc * tp)2268 static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
2269 {
2270 return _stext + tp->rel_addr;
2271 }
2272
patch_cmp(const void * key,const void * elt)2273 static __always_inline int patch_cmp(const void *key, const void *elt)
2274 {
2275 struct text_poke_loc *tp = (struct text_poke_loc *) elt;
2276
2277 if (key < text_poke_addr(tp))
2278 return -1;
2279 if (key > text_poke_addr(tp))
2280 return 1;
2281 return 0;
2282 }
2283
poke_int3_handler(struct pt_regs * regs)2284 noinstr int poke_int3_handler(struct pt_regs *regs)
2285 {
2286 struct bp_patching_desc *desc;
2287 struct text_poke_loc *tp;
2288 int ret = 0;
2289 void *ip;
2290
2291 if (user_mode(regs))
2292 return 0;
2293
2294 /*
2295 * Having observed our INT3 instruction, we now must observe
2296 * bp_desc with non-zero refcount:
2297 *
2298 * bp_desc.refs = 1 INT3
2299 * WMB RMB
2300 * write INT3 if (bp_desc.refs != 0)
2301 */
2302 smp_rmb();
2303
2304 desc = try_get_desc();
2305 if (!desc)
2306 return 0;
2307
2308 /*
2309 * Discount the INT3. See text_poke_bp_batch().
2310 */
2311 ip = (void *) regs->ip - INT3_INSN_SIZE;
2312
2313 /*
2314 * Skip the binary search if there is a single member in the vector.
2315 */
2316 if (unlikely(desc->nr_entries > 1)) {
2317 tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
2318 sizeof(struct text_poke_loc),
2319 patch_cmp);
2320 if (!tp)
2321 goto out_put;
2322 } else {
2323 tp = desc->vec;
2324 if (text_poke_addr(tp) != ip)
2325 goto out_put;
2326 }
2327
2328 ip += tp->len;
2329
2330 switch (tp->opcode) {
2331 case INT3_INSN_OPCODE:
2332 /*
2333 * Someone poked an explicit INT3, they'll want to handle it,
2334 * do not consume.
2335 */
2336 goto out_put;
2337
2338 case RET_INSN_OPCODE:
2339 int3_emulate_ret(regs);
2340 break;
2341
2342 case CALL_INSN_OPCODE:
2343 int3_emulate_call(regs, (long)ip + tp->disp);
2344 break;
2345
2346 case JMP32_INSN_OPCODE:
2347 case JMP8_INSN_OPCODE:
2348 int3_emulate_jmp(regs, (long)ip + tp->disp);
2349 break;
2350
2351 case 0x70 ... 0x7f: /* Jcc */
2352 int3_emulate_jcc(regs, tp->opcode & 0xf, (long)ip, tp->disp);
2353 break;
2354
2355 default:
2356 BUG();
2357 }
2358
2359 ret = 1;
2360
2361 out_put:
2362 put_desc();
2363 return ret;
2364 }
2365
2366 #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
2367 static struct text_poke_loc tp_vec[TP_VEC_MAX];
2368 static int tp_vec_nr;
2369
2370 /**
2371 * text_poke_bp_batch() -- update instructions on live kernel on SMP
2372 * @tp: vector of instructions to patch
2373 * @nr_entries: number of entries in the vector
2374 *
2375 * Modify multi-byte instruction by using int3 breakpoint on SMP.
2376 * We completely avoid stop_machine() here, and achieve the
2377 * synchronization using int3 breakpoint.
2378 *
2379 * The way it is done:
2380 * - For each entry in the vector:
2381 * - add a int3 trap to the address that will be patched
2382 * - sync cores
2383 * - For each entry in the vector:
2384 * - update all but the first byte of the patched range
2385 * - sync cores
2386 * - For each entry in the vector:
2387 * - replace the first byte (int3) by the first byte of
2388 * replacing opcode
2389 * - sync cores
2390 */
text_poke_bp_batch(struct text_poke_loc * tp,unsigned int nr_entries)2391 static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
2392 {
2393 unsigned char int3 = INT3_INSN_OPCODE;
2394 unsigned int i;
2395 int do_sync;
2396
2397 lockdep_assert_held(&text_mutex);
2398
2399 bp_desc.vec = tp;
2400 bp_desc.nr_entries = nr_entries;
2401
2402 /*
2403 * Corresponds to the implicit memory barrier in try_get_desc() to
2404 * ensure reading a non-zero refcount provides up to date bp_desc data.
2405 */
2406 atomic_set_release(&bp_desc.refs, 1);
2407
2408 /*
2409 * Function tracing can enable thousands of places that need to be
2410 * updated. This can take quite some time, and with full kernel debugging
2411 * enabled, this could cause the softlockup watchdog to trigger.
2412 * This function gets called every 256 entries added to be patched.
2413 * Call cond_resched() here to make sure that other tasks can get scheduled
2414 * while processing all the functions being patched.
2415 */
2416 cond_resched();
2417
2418 /*
2419 * Corresponding read barrier in int3 notifier for making sure the
2420 * nr_entries and handler are correctly ordered wrt. patching.
2421 */
2422 smp_wmb();
2423
2424 /*
2425 * First step: add a int3 trap to the address that will be patched.
2426 */
2427 for (i = 0; i < nr_entries; i++) {
2428 tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
2429 text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
2430 }
2431
2432 text_poke_sync();
2433
2434 /*
2435 * Second step: update all but the first byte of the patched range.
2436 */
2437 for (do_sync = 0, i = 0; i < nr_entries; i++) {
2438 u8 old[POKE_MAX_OPCODE_SIZE+1] = { tp[i].old, };
2439 u8 _new[POKE_MAX_OPCODE_SIZE+1];
2440 const u8 *new = tp[i].text;
2441 int len = tp[i].len;
2442
2443 if (len - INT3_INSN_SIZE > 0) {
2444 memcpy(old + INT3_INSN_SIZE,
2445 text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
2446 len - INT3_INSN_SIZE);
2447
2448 if (len == 6) {
2449 _new[0] = 0x0f;
2450 memcpy(_new + 1, new, 5);
2451 new = _new;
2452 }
2453
2454 text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
2455 new + INT3_INSN_SIZE,
2456 len - INT3_INSN_SIZE);
2457
2458 do_sync++;
2459 }
2460
2461 /*
2462 * Emit a perf event to record the text poke, primarily to
2463 * support Intel PT decoding which must walk the executable code
2464 * to reconstruct the trace. The flow up to here is:
2465 * - write INT3 byte
2466 * - IPI-SYNC
2467 * - write instruction tail
2468 * At this point the actual control flow will be through the
2469 * INT3 and handler and not hit the old or new instruction.
2470 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
2471 * can still be decoded. Subsequently:
2472 * - emit RECORD_TEXT_POKE with the new instruction
2473 * - IPI-SYNC
2474 * - write first byte
2475 * - IPI-SYNC
2476 * So before the text poke event timestamp, the decoder will see
2477 * either the old instruction flow or FUP/TIP of INT3. After the
2478 * text poke event timestamp, the decoder will see either the
2479 * new instruction flow or FUP/TIP of INT3. Thus decoders can
2480 * use the timestamp as the point at which to modify the
2481 * executable code.
2482 * The old instruction is recorded so that the event can be
2483 * processed forwards or backwards.
2484 */
2485 perf_event_text_poke(text_poke_addr(&tp[i]), old, len, new, len);
2486 }
2487
2488 if (do_sync) {
2489 /*
2490 * According to Intel, this core syncing is very likely
2491 * not necessary and we'd be safe even without it. But
2492 * better safe than sorry (plus there's not only Intel).
2493 */
2494 text_poke_sync();
2495 }
2496
2497 /*
2498 * Third step: replace the first byte (int3) by the first byte of
2499 * replacing opcode.
2500 */
2501 for (do_sync = 0, i = 0; i < nr_entries; i++) {
2502 u8 byte = tp[i].text[0];
2503
2504 if (tp[i].len == 6)
2505 byte = 0x0f;
2506
2507 if (byte == INT3_INSN_OPCODE)
2508 continue;
2509
2510 text_poke(text_poke_addr(&tp[i]), &byte, INT3_INSN_SIZE);
2511 do_sync++;
2512 }
2513
2514 if (do_sync)
2515 text_poke_sync();
2516
2517 /*
2518 * Remove and wait for refs to be zero.
2519 */
2520 if (!atomic_dec_and_test(&bp_desc.refs))
2521 atomic_cond_read_acquire(&bp_desc.refs, !VAL);
2522 }
2523
text_poke_loc_init(struct text_poke_loc * tp,void * addr,const void * opcode,size_t len,const void * emulate)2524 static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
2525 const void *opcode, size_t len, const void *emulate)
2526 {
2527 struct insn insn;
2528 int ret, i = 0;
2529
2530 if (len == 6)
2531 i = 1;
2532 memcpy((void *)tp->text, opcode+i, len-i);
2533 if (!emulate)
2534 emulate = opcode;
2535
2536 ret = insn_decode_kernel(&insn, emulate);
2537 BUG_ON(ret < 0);
2538
2539 tp->rel_addr = addr - (void *)_stext;
2540 tp->len = len;
2541 tp->opcode = insn.opcode.bytes[0];
2542
2543 if (is_jcc32(&insn)) {
2544 /*
2545 * Map Jcc.d32 onto Jcc.d8 and use len to distinguish.
2546 */
2547 tp->opcode = insn.opcode.bytes[1] - 0x10;
2548 }
2549
2550 switch (tp->opcode) {
2551 case RET_INSN_OPCODE:
2552 case JMP32_INSN_OPCODE:
2553 case JMP8_INSN_OPCODE:
2554 /*
2555 * Control flow instructions without implied execution of the
2556 * next instruction can be padded with INT3.
2557 */
2558 for (i = insn.length; i < len; i++)
2559 BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
2560 break;
2561
2562 default:
2563 BUG_ON(len != insn.length);
2564 }
2565
2566 switch (tp->opcode) {
2567 case INT3_INSN_OPCODE:
2568 case RET_INSN_OPCODE:
2569 break;
2570
2571 case CALL_INSN_OPCODE:
2572 case JMP32_INSN_OPCODE:
2573 case JMP8_INSN_OPCODE:
2574 case 0x70 ... 0x7f: /* Jcc */
2575 tp->disp = insn.immediate.value;
2576 break;
2577
2578 default: /* assume NOP */
2579 switch (len) {
2580 case 2: /* NOP2 -- emulate as JMP8+0 */
2581 BUG_ON(memcmp(emulate, x86_nops[len], len));
2582 tp->opcode = JMP8_INSN_OPCODE;
2583 tp->disp = 0;
2584 break;
2585
2586 case 5: /* NOP5 -- emulate as JMP32+0 */
2587 BUG_ON(memcmp(emulate, x86_nops[len], len));
2588 tp->opcode = JMP32_INSN_OPCODE;
2589 tp->disp = 0;
2590 break;
2591
2592 default: /* unknown instruction */
2593 BUG();
2594 }
2595 break;
2596 }
2597 }
2598
2599 /*
2600 * We hard rely on the tp_vec being ordered; ensure this is so by flushing
2601 * early if needed.
2602 */
tp_order_fail(void * addr)2603 static bool tp_order_fail(void *addr)
2604 {
2605 struct text_poke_loc *tp;
2606
2607 if (!tp_vec_nr)
2608 return false;
2609
2610 if (!addr) /* force */
2611 return true;
2612
2613 tp = &tp_vec[tp_vec_nr - 1];
2614 if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
2615 return true;
2616
2617 return false;
2618 }
2619
text_poke_flush(void * addr)2620 static void text_poke_flush(void *addr)
2621 {
2622 if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
2623 text_poke_bp_batch(tp_vec, tp_vec_nr);
2624 tp_vec_nr = 0;
2625 }
2626 }
2627
text_poke_finish(void)2628 void text_poke_finish(void)
2629 {
2630 text_poke_flush(NULL);
2631 }
2632
text_poke_queue(void * addr,const void * opcode,size_t len,const void * emulate)2633 void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
2634 {
2635 struct text_poke_loc *tp;
2636
2637 text_poke_flush(addr);
2638
2639 tp = &tp_vec[tp_vec_nr++];
2640 text_poke_loc_init(tp, addr, opcode, len, emulate);
2641 }
2642
2643 /**
2644 * text_poke_bp() -- update instructions on live kernel on SMP
2645 * @addr: address to patch
2646 * @opcode: opcode of new instruction
2647 * @len: length to copy
2648 * @emulate: instruction to be emulated
2649 *
2650 * Update a single instruction with the vector in the stack, avoiding
2651 * dynamically allocated memory. This function should be used when it is
2652 * not possible to allocate memory.
2653 */
text_poke_bp(void * addr,const void * opcode,size_t len,const void * emulate)2654 void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
2655 {
2656 struct text_poke_loc tp;
2657
2658 text_poke_loc_init(&tp, addr, opcode, len, emulate);
2659 text_poke_bp_batch(&tp, 1);
2660 }
2661