Linux 6.16-rc6
[linux-2.6-block.git] / arch / x86 / kernel / alternative.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
c767a54b
JP
2#define pr_fmt(fmt) "SMP alternatives: " fmt
3
db5c68c8 4#include <linux/mmu_context.h>
d769811c 5#include <linux/perf_event.h>
19d36ccd 6#include <linux/vmalloc.h>
3945dab4 7#include <linux/memory.h>
872df34d 8#include <linux/execmem.h>
db5c68c8 9
35de5b06 10#include <asm/text-patching.h>
3a125539 11#include <asm/insn.h>
ebebe307 12#include <asm/ibt.h>
872df34d 13#include <asm/set_memory.h>
db5c68c8 14#include <asm/nmi.h>
9a0b5817 15
5e907bb0
IM
16int __read_mostly alternatives_patched;
17
18EXPORT_SYMBOL_GPL(alternatives_patched);
19
ab144f5e
AK
20#define MAX_PATCH_LEN (255-1)
21
6becb502
PZ
22#define DA_ALL (~0)
23#define DA_ALT 0x01
24#define DA_RET 0x02
25#define DA_RETPOLINE 0x04
26#define DA_ENDBR 0x08
27#define DA_SMP 0x10
28
86ed430c 29static unsigned int debug_alternative;
b7fb4af0 30
d167a518
GH
31static int __init debug_alt(char *str)
32{
6becb502
PZ
33 if (str && *str == '=')
34 str++;
35
36 if (!str || kstrtouint(str, 0, &debug_alternative))
37 debug_alternative = DA_ALL;
38
d167a518
GH
39 return 1;
40}
d167a518
GH
41__setup("debug-alternative", debug_alt);
42
09488165
JB
43static int noreplace_smp;
44
b7fb4af0
JF
45static int __init setup_noreplace_smp(char *str)
46{
47 noreplace_smp = 1;
48 return 1;
49}
50__setup("noreplace-smp", setup_noreplace_smp);
51
6becb502 52#define DPRINTK(type, fmt, args...) \
db477a33 53do { \
6becb502 54 if (debug_alternative & DA_##type) \
1b2e335e 55 printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \
c767a54b 56} while (0)
d167a518 57
6becb502 58#define DUMP_BYTES(type, buf, len, fmt, args...) \
48c7a250 59do { \
6becb502 60 if (unlikely(debug_alternative & DA_##type)) { \
48c7a250
BP
61 int j; \
62 \
63 if (!(len)) \
64 break; \
65 \
1b2e335e 66 printk(KERN_DEBUG pr_fmt(fmt), ##args); \
48c7a250
BP
67 for (j = 0; j < (len) - 1; j++) \
68 printk(KERN_CONT "%02hhx ", buf[j]); \
69 printk(KERN_CONT "%02hhx\n", buf[j]); \
70 } \
71} while (0)
72
64e1f587 73static const unsigned char x86nops[] =
dc326fca 74{
a89dfde3
PZ
75 BYTES_NOP1,
76 BYTES_NOP2,
77 BYTES_NOP3,
78 BYTES_NOP4,
79 BYTES_NOP5,
80 BYTES_NOP6,
81 BYTES_NOP7,
82 BYTES_NOP8,
df25edba
PZ
83#ifdef CONFIG_64BIT
84 BYTES_NOP9,
85 BYTES_NOP10,
86 BYTES_NOP11,
87#endif
9a0b5817 88};
d167a518 89
a89dfde3 90const unsigned char * const x86_nops[ASM_NOP_MAX+1] =
dc326fca 91{
32c464f5 92 NULL,
a89dfde3
PZ
93 x86nops,
94 x86nops + 1,
95 x86nops + 1 + 2,
96 x86nops + 1 + 2 + 3,
97 x86nops + 1 + 2 + 3 + 4,
98 x86nops + 1 + 2 + 3 + 4 + 5,
99 x86nops + 1 + 2 + 3 + 4 + 5 + 6,
100 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
df25edba
PZ
101#ifdef CONFIG_64BIT
102 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
103 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
104 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
105#endif
32c464f5 106};
9a0b5817 107
e52c1dc7
PZ
108#ifdef CONFIG_FINEIBT
109static bool cfi_paranoid __ro_after_init;
110#endif
111
872df34d
PZ
112#ifdef CONFIG_MITIGATION_ITS
113
9f35e331 114#ifdef CONFIG_MODULES
872df34d 115static struct module *its_mod;
9f35e331 116#endif
872df34d
PZ
117static void *its_page;
118static unsigned int its_offset;
a82b2645
PZI
119struct its_array its_pages;
120
121static void *__its_alloc(struct its_array *pages)
122{
123 void *page __free(execmem) = execmem_alloc(EXECMEM_MODULE_TEXT, PAGE_SIZE);
124 if (!page)
125 return NULL;
126
127 void *tmp = krealloc(pages->pages, (pages->num+1) * sizeof(void *),
128 GFP_KERNEL);
129 if (!tmp)
130 return NULL;
131
132 pages->pages = tmp;
133 pages->pages[pages->num++] = page;
134
135 return no_free_ptr(page);
136}
872df34d
PZ
137
138/* Initialize a thunk with the "jmp *reg; int3" instructions. */
139static void *its_init_thunk(void *thunk, int reg)
140{
141 u8 *bytes = thunk;
e52c1dc7 142 int offset = 0;
872df34d
PZ
143 int i = 0;
144
e52c1dc7
PZ
145#ifdef CONFIG_FINEIBT
146 if (cfi_paranoid) {
147 /*
148 * When ITS uses indirect branch thunk the fineibt_paranoid
149 * caller sequence doesn't fit in the caller site. So put the
150 * remaining part of the sequence (<ea> + JNE) into the ITS
151 * thunk.
152 */
153 bytes[i++] = 0xea; /* invalid instruction */
154 bytes[i++] = 0x75; /* JNE */
155 bytes[i++] = 0xfd;
156
157 offset = 1;
158 }
159#endif
160
872df34d
PZ
161 if (reg >= 8) {
162 bytes[i++] = 0x41; /* REX.B prefix */
163 reg -= 8;
164 }
165 bytes[i++] = 0xff;
166 bytes[i++] = 0xe0 + reg; /* jmp *reg */
167 bytes[i++] = 0xcc;
168
e52c1dc7 169 return thunk + offset;
872df34d
PZ
170}
171
a82b2645
PZI
172static void its_pages_protect(struct its_array *pages)
173{
174 for (int i = 0; i < pages->num; i++) {
175 void *page = pages->pages[i];
176 execmem_restore_rox(page, PAGE_SIZE);
177 }
178}
179
180static void its_fini_core(void)
181{
182 if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX))
183 its_pages_protect(&its_pages);
184 kfree(its_pages.pages);
185}
186
9f35e331 187#ifdef CONFIG_MODULES
872df34d
PZ
188void its_init_mod(struct module *mod)
189{
190 if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
191 return;
192
193 mutex_lock(&text_mutex);
194 its_mod = mod;
195 its_page = NULL;
196}
197
198void its_fini_mod(struct module *mod)
199{
200 if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
201 return;
202
203 WARN_ON_ONCE(its_mod != mod);
204
205 its_mod = NULL;
206 its_page = NULL;
207 mutex_unlock(&text_mutex);
208
a82b2645
PZI
209 if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
210 its_pages_protect(&mod->arch.its_pages);
872df34d
PZ
211}
212
213void its_free_mod(struct module *mod)
214{
215 if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
216 return;
217
0b0cae71
MRM
218 for (int i = 0; i < mod->arch.its_pages.num; i++) {
219 void *page = mod->arch.its_pages.pages[i];
872df34d
PZ
220 execmem_free(page);
221 }
0b0cae71 222 kfree(mod->arch.its_pages.pages);
872df34d 223}
9f35e331 224#endif /* CONFIG_MODULES */
872df34d
PZ
225
226static void *its_alloc(void)
227{
a82b2645
PZI
228 struct its_array *pages = &its_pages;
229 void *page;
872df34d 230
3c902383 231#ifdef CONFIG_MODULES
a82b2645
PZI
232 if (its_mod)
233 pages = &its_mod->arch.its_pages;
234#endif
235
236 page = __its_alloc(pages);
872df34d
PZ
237 if (!page)
238 return NULL;
239
a82b2645
PZI
240 execmem_make_temp_rw(page, PAGE_SIZE);
241 if (pages == &its_pages)
242 set_memory_x((unsigned long)page, 1);
872df34d 243
a82b2645 244 return page;
872df34d
PZ
245}
246
247static void *its_allocate_thunk(int reg)
248{
249 int size = 3 + (reg / 8);
250 void *thunk;
251
e52c1dc7
PZ
252#ifdef CONFIG_FINEIBT
253 /*
254 * The ITS thunk contains an indirect jump and an int3 instruction so
255 * its size is 3 or 4 bytes depending on the register used. If CFI
256 * paranoid is used then 3 extra bytes are added in the ITS thunk to
257 * complete the fineibt_paranoid caller sequence.
258 */
259 if (cfi_paranoid)
260 size += 3;
261#endif
262
872df34d
PZ
263 if (!its_page || (its_offset + size - 1) >= PAGE_SIZE) {
264 its_page = its_alloc();
265 if (!its_page) {
266 pr_err("ITS page allocation failed\n");
267 return NULL;
268 }
269 memset(its_page, INT3_INSN_OPCODE, PAGE_SIZE);
270 its_offset = 32;
271 }
272
273 /*
274 * If the indirect branch instruction will be in the lower half
275 * of a cacheline, then update the offset to reach the upper half.
276 */
277 if ((its_offset + size - 1) % 64 < 32)
278 its_offset = ((its_offset - 1) | 0x3F) + 33;
279
280 thunk = its_page + its_offset;
281 its_offset += size;
282
283 return its_init_thunk(thunk, reg);
284}
285
e52c1dc7
PZ
286u8 *its_static_thunk(int reg)
287{
288 u8 *thunk = __x86_indirect_its_thunk_array[reg];
289
290#ifdef CONFIG_FINEIBT
291 /* Paranoid thunk starts 2 bytes before */
292 if (cfi_paranoid)
293 return thunk - 2;
294#endif
295 return thunk;
296}
297
a82b2645
PZI
298#else
299static inline void its_fini_core(void) {}
300#endif /* CONFIG_MITIGATION_ITS */
872df34d 301
f796c758
BPA
302/*
303 * Nomenclature for variable names to simplify and clarify this code and ease
304 * any potential staring at it:
305 *
306 * @instr: source address of the original instructions in the kernel text as
307 * generated by the compiler.
308 *
309 * @buf: temporary buffer on which the patching operates. This buffer is
310 * eventually text-poked into the kernel image.
311 *
312 * @replacement/@repl: pointer to the opcodes which are replacing @instr, located
313 * in the .altinstr_replacement section.
314 */
315
6c480f22 316/*
b6c881b2
PZ
317 * Fill the buffer with a single effective instruction of size @len.
318 *
6c480f22
PZ
319 * In order not to issue an ORC stack depth tracking CFI entry (Call Frame Info)
320 * for every single-byte NOP, try to generate the maximally available NOP of
321 * size <= ASM_NOP_MAX such that only a single CFI entry is generated (vs one for
322 * each single-byte NOPs). If @len to fill out is > ASM_NOP_MAX, pad with INT3 and
323 * *jump* over instead of executing long and daft NOPs.
324 */
f796c758 325static void add_nop(u8 *buf, unsigned int len)
139ec7c4 326{
f796c758 327 u8 *target = buf + len;
6c480f22
PZ
328
329 if (!len)
330 return;
331
332 if (len <= ASM_NOP_MAX) {
f796c758 333 memcpy(buf, x86_nops[len], len);
6c480f22 334 return;
139ec7c4 335 }
6c480f22
PZ
336
337 if (len < 128) {
f796c758
BPA
338 __text_gen_insn(buf, JMP8_INSN_OPCODE, buf, target, JMP8_INSN_SIZE);
339 buf += JMP8_INSN_SIZE;
6c480f22 340 } else {
f796c758
BPA
341 __text_gen_insn(buf, JMP32_INSN_OPCODE, buf, target, JMP32_INSN_SIZE);
342 buf += JMP32_INSN_SIZE;
6c480f22
PZ
343 }
344
f796c758
BPA
345 for (;buf < target; buf++)
346 *buf = INT3_INSN_OPCODE;
139ec7c4
RR
347}
348
b6c881b2
PZ
349/*
350 * Matches NOP and NOPL, not any of the other possible NOPs.
351 */
6c480f22 352static bool insn_is_nop(struct insn *insn)
2b31e8ed 353{
2bd4aa93
PZ
354 /* Anything NOP, but no REP NOP */
355 if (insn->opcode.bytes[0] == 0x90 &&
356 (!insn->prefixes.nbytes || insn->prefixes.bytes[0] != 0xF3))
6c480f22 357 return true;
2b31e8ed 358
2bd4aa93 359 /* NOPL */
6c480f22
PZ
360 if (insn->opcode.bytes[0] == 0x0F && insn->opcode.bytes[1] == 0x1F)
361 return true;
2b31e8ed 362
6c480f22 363 /* TODO: more nops */
2b31e8ed 364
6c480f22
PZ
365 return false;
366}
2b31e8ed 367
b6c881b2
PZ
368/*
369 * Find the offset of the first non-NOP instruction starting at @offset
370 * but no further than @len.
371 */
f796c758 372static int skip_nops(u8 *buf, int offset, int len)
6c480f22
PZ
373{
374 struct insn insn;
2b31e8ed 375
6c480f22 376 for (; offset < len; offset += insn.length) {
f796c758 377 if (insn_decode_kernel(&insn, &buf[offset]))
6c480f22 378 break;
2b31e8ed 379
6c480f22
PZ
380 if (!insn_is_nop(&insn))
381 break;
382 }
2b31e8ed 383
6c480f22 384 return offset;
2b31e8ed
BP
385}
386
34bfab0e
BP
387/*
388 * "noinline" to cause control flow change and thus invalidate I$ and
389 * cause refetch after modification.
390 */
da8f9cf7 391static void noinline optimize_nops(const u8 * const instr, u8 *buf, size_t len)
4fd4b6e5 392{
6c480f22
PZ
393 for (int next, i = 0; i < len; i = next) {
394 struct insn insn;
66c117d7 395
f796c758 396 if (insn_decode_kernel(&insn, &buf[i]))
23c1ad53
PZ
397 return;
398
6c480f22 399 next = i + insn.length;
23c1ad53 400
da8f9cf7
BPA
401 if (insn_is_nop(&insn)) {
402 int nop = i;
403
c3a3cb5c
BPA
404 /* Has the NOP already been optimized? */
405 if (i + insn.length == len)
406 return;
407
da8f9cf7
BPA
408 next = skip_nops(buf, next, len);
409
410 add_nop(buf + nop, next - nop);
411 DUMP_BYTES(ALT, buf, len, "%px: [%d:%d) optimized NOPs: ", instr, nop, next);
412 }
612e8e93 413 }
4fd4b6e5
BP
414}
415
270a69c4
PZ
416/*
417 * In this context, "source" is where the instructions are placed in the
418 * section .altinstr_replacement, for example during kernel build by the
419 * toolchain.
420 * "Destination" is where the instructions are being patched in by this
421 * machinery.
422 *
423 * The source offset is:
424 *
425 * src_imm = target - src_next_ip (1)
426 *
427 * and the target offset is:
428 *
429 * dst_imm = target - dst_next_ip (2)
430 *
431 * so rework (1) as an expression for target like:
432 *
433 * target = src_imm + src_next_ip (1a)
434 *
435 * and substitute in (2) to get:
436 *
437 * dst_imm = (src_imm + src_next_ip) - dst_next_ip (3)
438 *
439 * Now, since the instruction stream is 'identical' at src and dst (it
440 * is being copied after all) it can be stated that:
441 *
442 * src_next_ip = src + ip_offset
443 * dst_next_ip = dst + ip_offset (4)
444 *
445 * Substitute (4) in (3) and observe ip_offset being cancelled out to
446 * obtain:
447 *
448 * dst_imm = src_imm + (src + ip_offset) - (dst + ip_offset)
449 * = src_imm + src - dst + ip_offset - ip_offset
450 * = src_imm + src - dst (5)
451 *
452 * IOW, only the relative displacement of the code block matters.
453 */
454
455#define apply_reloc_n(n_, p_, d_) \
456 do { \
457 s32 v = *(s##n_ *)(p_); \
458 v += (d_); \
459 BUG_ON((v >> 31) != (v >> (n_-1))); \
460 *(s##n_ *)(p_) = (s##n_)v; \
461 } while (0)
462
463
464static __always_inline
465void apply_reloc(int n, void *ptr, uintptr_t diff)
466{
467 switch (n) {
468 case 1: apply_reloc_n(8, ptr, diff); break;
469 case 2: apply_reloc_n(16, ptr, diff); break;
470 case 4: apply_reloc_n(32, ptr, diff); break;
471 default: BUG();
472 }
473}
474
475static __always_inline
476bool need_reloc(unsigned long offset, u8 *src, size_t src_len)
477{
478 u8 *target = src + offset;
479 /*
480 * If the target is inside the patched block, it's relative to the
481 * block itself and does not need relocation.
482 */
483 return (target < src || target > src + src_len);
484}
485
da8f9cf7 486static void __apply_relocation(u8 *buf, const u8 * const instr, size_t instrlen, u8 *repl, size_t repl_len)
270a69c4 487{
f796c758 488 for (int next, i = 0; i < instrlen; i = next) {
270a69c4
PZ
489 struct insn insn;
490
491 if (WARN_ON_ONCE(insn_decode_kernel(&insn, &buf[i])))
492 return;
493
494 next = i + insn.length;
495
496 switch (insn.opcode.bytes[0]) {
497 case 0x0f:
498 if (insn.opcode.bytes[1] < 0x80 ||
499 insn.opcode.bytes[1] > 0x8f)
500 break;
501
502 fallthrough; /* Jcc.d32 */
503 case 0x70 ... 0x7f: /* Jcc.d8 */
504 case JMP8_INSN_OPCODE:
505 case JMP32_INSN_OPCODE:
506 case CALL_INSN_OPCODE:
f796c758 507 if (need_reloc(next + insn.immediate.value, repl, repl_len)) {
270a69c4
PZ
508 apply_reloc(insn.immediate.nbytes,
509 buf + i + insn_offset_immediate(&insn),
f796c758 510 repl - instr);
270a69c4
PZ
511 }
512
513 /*
514 * Where possible, convert JMP.d32 into JMP.d8.
515 */
516 if (insn.opcode.bytes[0] == JMP32_INSN_OPCODE) {
517 s32 imm = insn.immediate.value;
f796c758 518 imm += repl - instr;
270a69c4
PZ
519 imm += JMP32_INSN_SIZE - JMP8_INSN_SIZE;
520 if ((imm >> 31) == (imm >> 7)) {
521 buf[i+0] = JMP8_INSN_OPCODE;
522 buf[i+1] = (s8)imm;
523
524 memset(&buf[i+2], INT3_INSN_OPCODE, insn.length - 2);
525 }
526 }
527 break;
528 }
529
530 if (insn_rip_relative(&insn)) {
f796c758 531 if (need_reloc(next + insn.displacement.value, repl, repl_len)) {
270a69c4
PZ
532 apply_reloc(insn.displacement.nbytes,
533 buf + i + insn_offset_displacement(&insn),
f796c758 534 repl - instr);
270a69c4
PZ
535 }
536 }
270a69c4
PZ
537 }
538}
539
023f42dd 540void text_poke_apply_relocation(u8 *buf, const u8 * const instr, size_t instrlen, u8 *repl, size_t repl_len)
da8f9cf7
BPA
541{
542 __apply_relocation(buf, instr, instrlen, repl, repl_len);
9dba9c67 543 optimize_nops(instr, buf, instrlen);
da8f9cf7
BPA
544}
545
9824b00c
JG
546/* Low-level backend functions usable from alternative code replacements. */
547DEFINE_ASM_FUNC(nop_func, "", .entry.text);
548EXPORT_SYMBOL_GPL(nop_func);
549
550noinstr void BUG_func(void)
551{
552 BUG();
553}
f7cfe701 554EXPORT_SYMBOL(BUG_func);
9824b00c 555
da0fe6e6
JG
556#define CALL_RIP_REL_OPCODE 0xff
557#define CALL_RIP_REL_MODRM 0x15
558
559/*
560 * Rewrite the "call BUG_func" replacement to point to the target of the
561 * indirect pv_ops call "call *disp(%ip)".
562 */
1d7e707a 563static int alt_replace_call(u8 *instr, u8 *insn_buff, struct alt_instr *a)
da0fe6e6
JG
564{
565 void *target, *bug = &BUG_func;
566 s32 disp;
567
568 if (a->replacementlen != 5 || insn_buff[0] != CALL_INSN_OPCODE) {
569 pr_err("ALT_FLAG_DIRECT_CALL set for a non-call replacement instruction\n");
570 BUG();
571 }
572
573 if (a->instrlen != 6 ||
1d7e707a
MRM
574 instr[0] != CALL_RIP_REL_OPCODE ||
575 instr[1] != CALL_RIP_REL_MODRM) {
da0fe6e6
JG
576 pr_err("ALT_FLAG_DIRECT_CALL set for unrecognized indirect call\n");
577 BUG();
578 }
579
580 /* Skip CALL_RIP_REL_OPCODE and CALL_RIP_REL_MODRM */
1d7e707a 581 disp = *(s32 *)(instr + 2);
da0fe6e6
JG
582#ifdef CONFIG_X86_64
583 /* ff 15 00 00 00 00 call *0x0(%rip) */
584 /* target address is stored at "next instruction + disp". */
585 target = *(void **)(instr + a->instrlen + disp);
586#else
587 /* ff 15 00 00 00 00 call *0x0 */
588 /* target address is stored at disp. */
589 target = *(void **)disp;
590#endif
591 if (!target)
592 target = bug;
593
594 /* (BUG_func - .) + (target - BUG_func) := target - . */
595 *(s32 *)(insn_buff + 1) += target - bug;
596
597 if (target == &nop_func)
598 return 0;
599
600 return 5;
601}
602
d2a793da
PZ
603static inline u8 * instr_va(struct alt_instr *i)
604{
605 return (u8 *)&i->instr_offset + i->instr_offset;
606}
607
db477a33
BP
608/*
609 * Replace instructions with better alternatives for this CPU type. This runs
610 * before SMP is initialized to avoid SMP problems with self modifying code.
611 * This implies that asymmetric systems where APs have less capabilities than
612 * the boot processor are not handled. Tough. Make sure you disable such
613 * features by hand.
34bfab0e
BP
614 *
615 * Marked "noinline" to cause control flow change and thus insn cache
616 * to refetch changed I$ lines.
db477a33 617 */
34bfab0e 618void __init_or_module noinline apply_alternatives(struct alt_instr *start,
1d7e707a 619 struct alt_instr *end)
9a0b5817 620{
1fc654cf 621 u8 insn_buff[MAX_PATCH_LEN];
05d277c9 622 u8 *instr, *replacement;
d2a793da 623 struct alt_instr *a, *b;
9a0b5817 624
6becb502 625 DPRINTK(ALT, "alt table %px, -> %px", start, end);
d35652a5
KS
626
627 /*
7212b58d 628 * KASAN_SHADOW_START is defined using
d35652a5
KS
629 * cpu_feature_enabled(X86_FEATURE_LA57) and is therefore patched here.
630 * During the process, KASAN becomes confused seeing partial LA57
631 * conversion and triggers a false-positive out-of-bound report.
632 *
633 * Disable KASAN until the patching is complete.
634 */
635 kasan_disable_current();
636
50973133
FY
637 /*
638 * The scan order should be from start to end. A later scanned
db477a33 639 * alternative code can overwrite previously scanned alternative code.
50973133
FY
640 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
641 * patch code.
642 *
643 * So be careful if you want to change the scan order to any other
644 * order.
645 */
9a0b5817 646 for (a = start; a < end; a++) {
1fc654cf 647 int insn_buff_sz = 0;
48c7a250 648
d2a793da
PZ
649 /*
650 * In case of nested ALTERNATIVE()s the outer alternative might
651 * add more padding. To ensure consistent patching find the max
652 * padding for all alt_instr entries for this site (nested
653 * alternatives result in consecutive entries).
654 */
655 for (b = a+1; b < end && instr_va(b) == instr_va(a); b++) {
656 u8 len = max(a->instrlen, b->instrlen);
657 a->instrlen = b->instrlen = len;
658 }
659
660 instr = instr_va(a);
59e97e4d 661 replacement = (u8 *)&a->repl_offset + a->repl_offset;
1fc654cf 662 BUG_ON(a->instrlen > sizeof(insn_buff));
5d1dd961 663 BUG_ON(a->cpuid >= (NCAPINTS + NBUGINTS) * 32);
dda7bb76
JG
664
665 /*
666 * Patch if either:
667 * - feature is present
5d1dd961 668 * - feature not present but ALT_FLAG_NOT is set to mean,
dda7bb76
JG
669 * patch if feature is *NOT* present.
670 */
270a69c4 671 if (!boot_cpu_has(a->cpuid) == !(a->flags & ALT_FLAG_NOT)) {
1d7e707a 672 memcpy(insn_buff, instr, a->instrlen);
f796c758 673 optimize_nops(instr, insn_buff, a->instrlen);
1d7e707a 674 text_poke_early(instr, insn_buff, a->instrlen);
270a69c4
PZ
675 continue;
676 }
59e97e4d 677
7991ed43 678 DPRINTK(ALT, "feat: %d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d) flags: 0x%x",
5d1dd961
BPA
679 a->cpuid >> 5,
680 a->cpuid & 0x1f,
c1d4e419 681 instr, instr, a->instrlen,
da0fe6e6 682 replacement, a->replacementlen, a->flags);
db477a33 683
1d7e707a 684 memcpy(insn_buff, replacement, a->replacementlen);
1fc654cf 685 insn_buff_sz = a->replacementlen;
59e97e4d 686
da0fe6e6 687 if (a->flags & ALT_FLAG_DIRECT_CALL) {
1d7e707a 688 insn_buff_sz = alt_replace_call(instr, insn_buff, a);
da0fe6e6
JG
689 if (insn_buff_sz < 0)
690 continue;
691 }
692
23c1ad53
PZ
693 for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
694 insn_buff[insn_buff_sz] = 0x90;
695
023f42dd 696 text_poke_apply_relocation(insn_buff, instr, a->instrlen, replacement, a->replacementlen);
270a69c4 697
1d7e707a 698 DUMP_BYTES(ALT, instr, a->instrlen, "%px: old_insn: ", instr);
270a69c4 699 DUMP_BYTES(ALT, replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
6becb502 700 DUMP_BYTES(ALT, insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
59e97e4d 701
1d7e707a 702 text_poke_early(instr, insn_buff, insn_buff_sz);
9a0b5817 703 }
d35652a5
KS
704
705 kasan_enable_current();
9a0b5817
GH
706}
707
ac0ee0a9
PZ
708static inline bool is_jcc32(struct insn *insn)
709{
710 /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
711 return insn->opcode.bytes[0] == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80;
712}
713
aefb2f2e 714#if defined(CONFIG_MITIGATION_RETPOLINE) && defined(CONFIG_OBJTOOL)
75085009
PZ
715
716/*
717 * CALL/JMP *%\reg
718 */
719static int emit_indirect(int op, int reg, u8 *bytes)
720{
721 int i = 0;
722 u8 modrm;
723
724 switch (op) {
725 case CALL_INSN_OPCODE:
726 modrm = 0x10; /* Reg = 2; CALL r/m */
727 break;
728
729 case JMP32_INSN_OPCODE:
730 modrm = 0x20; /* Reg = 4; JMP r/m */
731 break;
732
733 default:
734 WARN_ON_ONCE(1);
735 return -1;
736 }
737
738 if (reg >= 8) {
739 bytes[i++] = 0x41; /* REX.B prefix */
740 reg -= 8;
741 }
742
743 modrm |= 0xc0; /* Mod = 3 */
744 modrm += reg;
745
746 bytes[i++] = 0xff; /* opcode */
747 bytes[i++] = modrm;
748
749 return i;
750}
751
8754e67a
PG
752static int __emit_trampoline(void *addr, struct insn *insn, u8 *bytes,
753 void *call_dest, void *jmp_dest)
3b6c1747
PZ
754{
755 u8 op = insn->opcode.bytes[0];
756 int i = 0;
757
758 /*
759 * Clang does 'weird' Jcc __x86_indirect_thunk_r11 conditional
760 * tail-calls. Deal with them.
761 */
762 if (is_jcc32(insn)) {
763 bytes[i++] = op;
764 op = insn->opcode.bytes[1];
765 goto clang_jcc;
766 }
767
768 if (insn->length == 6)
769 bytes[i++] = 0x2e; /* CS-prefix */
770
771 switch (op) {
772 case CALL_INSN_OPCODE:
773 __text_gen_insn(bytes+i, op, addr+i,
8754e67a 774 call_dest,
3b6c1747
PZ
775 CALL_INSN_SIZE);
776 i += CALL_INSN_SIZE;
777 break;
778
779 case JMP32_INSN_OPCODE:
780clang_jcc:
781 __text_gen_insn(bytes+i, op, addr+i,
8754e67a 782 jmp_dest,
3b6c1747
PZ
783 JMP32_INSN_SIZE);
784 i += JMP32_INSN_SIZE;
785 break;
786
787 default:
ae25e00b 788 WARN(1, "%pS %px %*ph\n", addr, addr, 6, addr);
3b6c1747
PZ
789 return -1;
790 }
791
792 WARN_ON_ONCE(i != insn->length);
793
794 return i;
795}
796
8754e67a
PG
797static int emit_call_track_retpoline(void *addr, struct insn *insn, int reg, u8 *bytes)
798{
799 return __emit_trampoline(addr, insn, bytes,
800 __x86_indirect_call_thunk_array[reg],
801 __x86_indirect_jump_thunk_array[reg]);
802}
803
804#ifdef CONFIG_MITIGATION_ITS
805static int emit_its_trampoline(void *addr, struct insn *insn, int reg, u8 *bytes)
806{
872df34d
PZ
807 u8 *thunk = __x86_indirect_its_thunk_array[reg];
808 u8 *tmp = its_allocate_thunk(reg);
809
810 if (tmp)
811 thunk = tmp;
812
813 return __emit_trampoline(addr, insn, bytes, thunk, thunk);
8754e67a
PG
814}
815
816/* Check if an indirect branch is at ITS-unsafe address */
817static bool cpu_wants_indirect_its_thunk_at(unsigned long addr, int reg)
818{
819 if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
820 return false;
821
822 /* Indirect branch opcode is 2 or 3 bytes depending on reg */
823 addr += 1 + reg / 8;
824
825 /* Lower-half of the cacheline? */
826 return !(addr & 0x20);
827}
e52c1dc7
PZ
828#else /* CONFIG_MITIGATION_ITS */
829
830#ifdef CONFIG_FINEIBT
831static bool cpu_wants_indirect_its_thunk_at(unsigned long addr, int reg)
832{
833 return false;
834}
8754e67a
PG
835#endif
836
e52c1dc7
PZ
837#endif /* CONFIG_MITIGATION_ITS */
838
75085009
PZ
839/*
840 * Rewrite the compiler generated retpoline thunk calls.
841 *
842 * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
843 * indirect instructions, avoiding the extra indirection.
844 *
845 * For example, convert:
846 *
847 * CALL __x86_indirect_thunk_\reg
848 *
849 * into:
850 *
851 * CALL *%\reg
852 *
d45476d9 853 * It also tries to inline spectre_v2=retpoline,lfence when size permits.
75085009
PZ
854 */
855static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
856{
857 retpoline_thunk_t *target;
2f0cbb2a
PZ
858 int reg, ret, i = 0;
859 u8 op, cc;
75085009
PZ
860
861 target = addr + insn->length + insn->immediate.value;
862 reg = target - __x86_indirect_thunk_array;
863
864 if (WARN_ON_ONCE(reg & ~0xf))
865 return -1;
866
867 /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
868 BUG_ON(reg == 4);
869
bbe2df3f 870 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
3b6c1747
PZ
871 !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
872 if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
873 return emit_call_track_retpoline(addr, insn, reg, bytes);
874
75085009 875 return -1;
3b6c1747 876 }
75085009 877
2f0cbb2a
PZ
878 op = insn->opcode.bytes[0];
879
880 /*
881 * Convert:
882 *
883 * Jcc.d32 __x86_indirect_thunk_\reg
884 *
885 * into:
886 *
887 * Jncc.d8 1f
bbe2df3f 888 * [ LFENCE ]
2f0cbb2a 889 * JMP *%\reg
bbe2df3f 890 * [ NOP ]
2f0cbb2a
PZ
891 * 1:
892 */
3b6c1747 893 if (is_jcc32(insn)) {
2f0cbb2a
PZ
894 cc = insn->opcode.bytes[1] & 0xf;
895 cc ^= 1; /* invert condition */
896
897 bytes[i++] = 0x70 + cc; /* Jcc.d8 */
898 bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
899
900 /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
901 op = JMP32_INSN_OPCODE;
902 }
903
bbe2df3f 904 /*
d45476d9 905 * For RETPOLINE_LFENCE: prepend the indirect CALL/JMP with an LFENCE.
bbe2df3f 906 */
d45476d9 907 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
bbe2df3f
PZ
908 bytes[i++] = 0x0f;
909 bytes[i++] = 0xae;
910 bytes[i++] = 0xe8; /* LFENCE */
911 }
912
8754e67a
PG
913#ifdef CONFIG_MITIGATION_ITS
914 /*
915 * Check if the address of last byte of emitted-indirect is in
916 * lower-half of the cacheline. Such branches need ITS mitigation.
917 */
918 if (cpu_wants_indirect_its_thunk_at((unsigned long)addr + i, reg))
919 return emit_its_trampoline(addr, insn, reg, bytes);
920#endif
921
2f0cbb2a
PZ
922 ret = emit_indirect(op, reg, bytes + i);
923 if (ret < 0)
924 return ret;
925 i += ret;
75085009 926
8c03af3e
PZ
927 /*
928 * The compiler is supposed to EMIT an INT3 after every unconditional
929 * JMP instruction due to AMD BTC. However, if the compiler is too old
7b75782f
BL
930 * or MITIGATION_SLS isn't enabled, we still need an INT3 after
931 * indirect JMPs even on Intel.
8c03af3e
PZ
932 */
933 if (op == JMP32_INSN_OPCODE && i < insn->length)
934 bytes[i++] = INT3_INSN_OPCODE;
935
75085009
PZ
936 for (; i < insn->length;)
937 bytes[i++] = BYTES_NOP1;
938
939 return i;
940}
941
942/*
943 * Generated by 'objtool --retpoline'.
944 */
1d7e707a 945void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
75085009
PZ
946{
947 s32 *s;
948
949 for (s = start; s < end; s++) {
950 void *addr = (void *)s + *s;
951 struct insn insn;
952 int len, ret;
953 u8 bytes[16];
954 u8 op1, op2;
e52c1dc7 955 u8 *dest;
75085009 956
1d7e707a 957 ret = insn_decode_kernel(&insn, addr);
75085009
PZ
958 if (WARN_ON_ONCE(ret < 0))
959 continue;
960
961 op1 = insn.opcode.bytes[0];
962 op2 = insn.opcode.bytes[1];
963
964 switch (op1) {
97e59672
PZ
965 case 0x70 ... 0x7f: /* Jcc.d8 */
966 /* See cfi_paranoid. */
967 WARN_ON_ONCE(cfi_mode != CFI_FINEIBT);
968 continue;
969
75085009
PZ
970 case CALL_INSN_OPCODE:
971 case JMP32_INSN_OPCODE:
e52c1dc7
PZ
972 /* Check for cfi_paranoid + ITS */
973 dest = addr + insn.length + insn.immediate.value;
974 if (dest[-1] == 0xea && (dest[0] & 0xf0) == 0x70) {
975 WARN_ON_ONCE(cfi_mode != CFI_FINEIBT);
976 continue;
977 }
75085009
PZ
978 break;
979
2f0cbb2a
PZ
980 case 0x0f: /* escape */
981 if (op2 >= 0x80 && op2 <= 0x8f)
982 break;
983 fallthrough;
75085009
PZ
984 default:
985 WARN_ON_ONCE(1);
986 continue;
987 }
988
6becb502 989 DPRINTK(RETPOLINE, "retpoline at: %pS (%px) len: %d to: %pS",
d4b5a5c9
PZ
990 addr, addr, insn.length,
991 addr + insn.length + insn.immediate.value);
992
75085009
PZ
993 len = patch_retpoline(addr, &insn, bytes);
994 if (len == insn.length) {
f796c758 995 optimize_nops(addr, bytes, len);
1d7e707a 996 DUMP_BYTES(RETPOLINE, ((u8*)addr), len, "%px: orig: ", addr);
6becb502 997 DUMP_BYTES(RETPOLINE, ((u8*)bytes), len, "%px: repl: ", addr);
1d7e707a 998 text_poke_early(addr, bytes, len);
75085009
PZ
999 }
1000 }
1001}
1002
0911b8c5 1003#ifdef CONFIG_MITIGATION_RETHUNK
770ae1b7 1004
a75bf27f
PG
1005bool cpu_wants_rethunk(void)
1006{
1007 return cpu_feature_enabled(X86_FEATURE_RETHUNK);
1008}
1009
1010bool cpu_wants_rethunk_at(void *addr)
1011{
1012 if (!cpu_feature_enabled(X86_FEATURE_RETHUNK))
1013 return false;
1014 if (x86_return_thunk != its_return_thunk)
1015 return true;
1016
1017 return !((unsigned long)addr & 0x20);
1018}
1019
15e67227
PZ
1020/*
1021 * Rewrite the compiler generated return thunk tail-calls.
1022 *
1023 * For example, convert:
1024 *
1025 * JMP __x86_return_thunk
1026 *
1027 * into:
1028 *
1029 * RET
1030 */
1031static int patch_return(void *addr, struct insn *insn, u8 *bytes)
1032{
1033 int i = 0;
1034
d2408e04 1035 /* Patch the custom return thunks... */
a75bf27f 1036 if (cpu_wants_rethunk_at(addr)) {
770ae1b7
PZ
1037 i = JMP32_INSN_SIZE;
1038 __text_gen_insn(bytes, JMP32_INSN_OPCODE, addr, x86_return_thunk, i);
1039 } else {
d2408e04 1040 /* ... or patch them out if not needed. */
770ae1b7
PZ
1041 bytes[i++] = RET_INSN_OPCODE;
1042 }
15e67227
PZ
1043
1044 for (; i < insn->length;)
1045 bytes[i++] = INT3_INSN_OPCODE;
15e67227
PZ
1046 return i;
1047}
1048
1d7e707a 1049void __init_or_module noinline apply_returns(s32 *start, s32 *end)
15e67227
PZ
1050{
1051 s32 *s;
1052
a75bf27f 1053 if (cpu_wants_rethunk())
aee9d30b 1054 static_call_force_reinit();
d2408e04 1055
15e67227 1056 for (s = start; s < end; s++) {
ee88d363 1057 void *dest = NULL, *addr = (void *)s + *s;
15e67227
PZ
1058 struct insn insn;
1059 int len, ret;
1060 u8 bytes[16];
ee88d363 1061 u8 op;
15e67227 1062
1d7e707a 1063 ret = insn_decode_kernel(&insn, addr);
15e67227
PZ
1064 if (WARN_ON_ONCE(ret < 0))
1065 continue;
1066
ee88d363
PZ
1067 op = insn.opcode.bytes[0];
1068 if (op == JMP32_INSN_OPCODE)
1069 dest = addr + insn.length + insn.immediate.value;
1070
1071 if (__static_call_fixup(addr, op, dest) ||
65cdf0d6
KC
1072 WARN_ONCE(dest != &__x86_return_thunk,
1073 "missing return thunk: %pS-%pS: %*ph",
1074 addr, dest, 5, addr))
15e67227
PZ
1075 continue;
1076
6becb502 1077 DPRINTK(RET, "return thunk at: %pS (%px) len: %d to: %pS",
15e67227
PZ
1078 addr, addr, insn.length,
1079 addr + insn.length + insn.immediate.value);
1080
1081 len = patch_return(addr, &insn, bytes);
1082 if (len == insn.length) {
1d7e707a 1083 DUMP_BYTES(RET, ((u8*)addr), len, "%px: orig: ", addr);
6becb502 1084 DUMP_BYTES(RET, ((u8*)bytes), len, "%px: repl: ", addr);
1d7e707a 1085 text_poke_early(addr, bytes, len);
15e67227
PZ
1086 }
1087 }
1088}
5d703825 1089#else /* !CONFIG_MITIGATION_RETHUNK: */
1d7e707a 1090void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
5d703825 1091#endif /* !CONFIG_MITIGATION_RETHUNK */
f43b9876 1092
aefb2f2e 1093#else /* !CONFIG_MITIGATION_RETPOLINE || !CONFIG_OBJTOOL */
75085009 1094
1d7e707a
MRM
1095void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
1096void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
75085009 1097
5d703825 1098#endif /* !CONFIG_MITIGATION_RETPOLINE || !CONFIG_OBJTOOL */
75085009 1099
ed53a0d9
PZ
1100#ifdef CONFIG_X86_KERNEL_IBT
1101
72e213a7
PZ
1102__noendbr bool is_endbr(u32 *val)
1103{
1104 u32 endbr;
1105
1106 __get_kernel_nofault(&endbr, val, u32, Efault);
1107 return __is_endbr(endbr);
1108
1109Efault:
1110 return false;
1111}
1112
500a41ac
PZ
1113#ifdef CONFIG_FINEIBT
1114
1115static __noendbr bool exact_endbr(u32 *val)
1116{
1117 u32 endbr;
1118
1119 __get_kernel_nofault(&endbr, val, u32, Efault);
1120 return endbr == gen_endbr();
1121
1122Efault:
1123 return false;
1124}
1125
1126#endif
1127
1d7e707a 1128static void poison_cfi(void *addr);
9831c625 1129
c4239a72 1130static void __init_or_module poison_endbr(void *addr)
931ab636 1131{
72e213a7 1132 u32 poison = gen_endbr_poison();
931ab636 1133
c4239a72 1134 if (WARN_ON_ONCE(!is_endbr(addr)))
931ab636 1135 return;
931ab636 1136
6becb502 1137 DPRINTK(ENDBR, "ENDBR at: %pS (%px)", addr, addr);
931ab636
PZ
1138
1139 /*
1140 * When we have IBT, the lack of ENDBR will trigger #CP
1141 */
6becb502
PZ
1142 DUMP_BYTES(ENDBR, ((u8*)addr), 4, "%px: orig: ", addr);
1143 DUMP_BYTES(ENDBR, ((u8*)&poison), 4, "%px: repl: ", addr);
1d7e707a 1144 text_poke_early(addr, &poison, 4);
931ab636
PZ
1145}
1146
ed53a0d9
PZ
1147/*
1148 * Generated by: objtool --ibt
9831c625
PZ
1149 *
1150 * Seal the functions for indirect calls by clobbering the ENDBR instructions
1151 * and the kCFI hash value.
ed53a0d9 1152 */
1d7e707a 1153void __init_or_module noinline apply_seal_endbr(s32 *start, s32 *end)
ed53a0d9
PZ
1154{
1155 s32 *s;
1156
1157 for (s = start; s < end; s++) {
ed53a0d9
PZ
1158 void *addr = (void *)s + *s;
1159
c4239a72 1160 poison_endbr(addr);
931ab636 1161 if (IS_ENABLED(CONFIG_FINEIBT))
1d7e707a 1162 poison_cfi(addr - 16);
931ab636
PZ
1163 }
1164}
1165
5d703825 1166#else /* !CONFIG_X86_KERNEL_IBT: */
931ab636 1167
1d7e707a 1168void __init_or_module apply_seal_endbr(s32 *start, s32 *end) { }
931ab636 1169
5d703825 1170#endif /* !CONFIG_X86_KERNEL_IBT */
931ab636 1171
d6f635bc 1172#ifdef CONFIG_CFI_AUTO_DEFAULT
5d703825 1173# define __CFI_DEFAULT CFI_AUTO
4f9087f1 1174#elif defined(CONFIG_CFI_CLANG)
5d703825 1175# define __CFI_DEFAULT CFI_KCFI
4f9087f1 1176#else
5d703825 1177# define __CFI_DEFAULT CFI_OFF
4f9087f1 1178#endif
082c4c81 1179
4f9087f1 1180enum cfi_mode cfi_mode __ro_after_init = __CFI_DEFAULT;
73e8079b
PZ
1181
1182#ifdef CONFIG_FINEIBT_BHI
0c92385d 1183bool cfi_bhi __ro_after_init = false;
73e8079b 1184#endif
4f9087f1
PZ
1185
1186#ifdef CONFIG_CFI_CLANG
1187struct bpf_insn;
1188
1189/* Must match bpf_func_t / DEFINE_BPF_PROG_RUN() */
1190extern unsigned int __bpf_prog_runX(const void *ctx,
1191 const struct bpf_insn *insn);
1192
582077c9 1193KCFI_REFERENCE(__bpf_prog_runX);
4f9087f1
PZ
1194
1195/* u32 __ro_after_init cfi_bpf_hash = __kcfi_typeid___bpf_prog_runX; */
1196asm (
1197" .pushsection .data..ro_after_init,\"aw\",@progbits \n"
1198" .type cfi_bpf_hash,@object \n"
1199" .globl cfi_bpf_hash \n"
1200" .p2align 2, 0x0 \n"
1201"cfi_bpf_hash: \n"
1202" .long __kcfi_typeid___bpf_prog_runX \n"
1203" .size cfi_bpf_hash, 4 \n"
1204" .popsection \n"
1205);
e72d88d1
PZ
1206
1207/* Must match bpf_callback_t */
1208extern u64 __bpf_callback_fn(u64, u64, u64, u64, u64);
1209
582077c9 1210KCFI_REFERENCE(__bpf_callback_fn);
e72d88d1
PZ
1211
1212/* u32 __ro_after_init cfi_bpf_subprog_hash = __kcfi_typeid___bpf_callback_fn; */
1213asm (
1214" .pushsection .data..ro_after_init,\"aw\",@progbits \n"
1215" .type cfi_bpf_subprog_hash,@object \n"
1216" .globl cfi_bpf_subprog_hash \n"
1217" .p2align 2, 0x0 \n"
1218"cfi_bpf_subprog_hash: \n"
1219" .long __kcfi_typeid___bpf_callback_fn \n"
1220" .size cfi_bpf_subprog_hash, 4 \n"
1221" .popsection \n"
1222);
2cd3e377
PZ
1223
1224u32 cfi_get_func_hash(void *func)
1225{
1226 u32 hash;
1227
1228 func -= cfi_get_offset();
1229 switch (cfi_mode) {
1230 case CFI_FINEIBT:
1231 func += 7;
1232 break;
1233 case CFI_KCFI:
1234 func += 1;
1235 break;
1236 default:
1237 return 0;
1238 }
1239
1240 if (get_kernel_nofault(hash, func))
1241 return 0;
1242
1243 return hash;
1244}
0c92385d
PZ
1245
1246int cfi_get_func_arity(void *func)
1247{
1248 bhi_thunk *target;
1249 s32 disp;
1250
1251 if (cfi_mode != CFI_FINEIBT && !cfi_bhi)
1252 return 0;
1253
1254 if (get_kernel_nofault(disp, func - 4))
1255 return 0;
1256
1257 target = func + disp;
1258 return target - __bhi_args;
1259}
4f9087f1
PZ
1260#endif
1261
1262#ifdef CONFIG_FINEIBT
082c4c81 1263
0c3e806e
PZ
1264static bool cfi_rand __ro_after_init = true;
1265static u32 cfi_seed __ro_after_init;
1266
1267/*
1268 * Re-hash the CFI hash with a boot-time seed while making sure the result is
1269 * not a valid ENDBR instruction.
1270 */
1271static u32 cfi_rehash(u32 hash)
1272{
1273 hash ^= cfi_seed;
72e213a7 1274 while (unlikely(__is_endbr(hash) || __is_endbr(-hash))) {
0c3e806e
PZ
1275 bool lsb = hash & 1;
1276 hash >>= 1;
1277 if (lsb)
1278 hash ^= 0x80200003;
1279 }
1280 return hash;
1281}
082c4c81
PZ
1282
1283static __init int cfi_parse_cmdline(char *str)
1284{
1285 if (!str)
1286 return -EINVAL;
1287
1288 while (str) {
1289 char *next = strchr(str, ',');
1290 if (next) {
1291 *next = 0;
1292 next++;
1293 }
1294
1295 if (!strcmp(str, "auto")) {
d6f635bc 1296 cfi_mode = CFI_AUTO;
082c4c81
PZ
1297 } else if (!strcmp(str, "off")) {
1298 cfi_mode = CFI_OFF;
0c3e806e 1299 cfi_rand = false;
082c4c81
PZ
1300 } else if (!strcmp(str, "kcfi")) {
1301 cfi_mode = CFI_KCFI;
1302 } else if (!strcmp(str, "fineibt")) {
1303 cfi_mode = CFI_FINEIBT;
0c3e806e
PZ
1304 } else if (!strcmp(str, "norand")) {
1305 cfi_rand = false;
9a54fb31
PZ
1306 } else if (!strcmp(str, "warn")) {
1307 pr_alert("CFI mismatch non-fatal!\n");
1308 cfi_warn = true;
97e59672
PZ
1309 } else if (!strcmp(str, "paranoid")) {
1310 if (cfi_mode == CFI_FINEIBT) {
1311 cfi_paranoid = true;
1312 } else {
1313 pr_err("Ignoring paranoid; depends on fineibt.\n");
1314 }
0c92385d 1315 } else if (!strcmp(str, "bhi")) {
73e8079b 1316#ifdef CONFIG_FINEIBT_BHI
0c92385d
PZ
1317 if (cfi_mode == CFI_FINEIBT) {
1318 cfi_bhi = true;
1319 } else {
1320 pr_err("Ignoring bhi; depends on fineibt.\n");
1321 }
73e8079b
PZ
1322#else
1323 pr_err("Ignoring bhi; depends on FINEIBT_BHI=y.\n");
1324#endif
082c4c81
PZ
1325 } else {
1326 pr_err("Ignoring unknown cfi option (%s).", str);
1327 }
1328
1329 str = next;
1330 }
1331
1332 return 0;
1333}
1334early_param("cfi", cfi_parse_cmdline);
1335
931ab636
PZ
1336/*
1337 * kCFI FineIBT
1338 *
1339 * __cfi_\func: __cfi_\func:
1340 * movl $0x12345678,%eax // 5 endbr64 // 4
1341 * nop subl $0x12345678,%r10d // 7
06926c6c
PZ
1342 * nop jne __cfi_\func+6 // 2
1343 * nop nop3 // 3
1344 * nop
931ab636
PZ
1345 * nop
1346 * nop
1347 * nop
1348 * nop
1349 * nop
1350 * nop
1351 * nop
1352 *
1353 *
1354 * caller: caller:
1355 * movl $(-0x12345678),%r10d // 6 movl $0x12345678,%r10d // 6
06926c6c 1356 * addl $-15(%r11),%r10d // 4 lea -0x10(%r11),%r11 // 4
931ab636
PZ
1357 * je 1f // 2 nop4 // 4
1358 * ud2 // 2
06926c6c 1359 * 1: cs call __x86_indirect_thunk_r11 // 6 call *%r11; nop3; // 6
931ab636
PZ
1360 *
1361 */
1362
06926c6c
PZ
1363/*
1364 * <fineibt_preamble_start>:
1365 * 0: f3 0f 1e fa endbr64
1366 * 4: 41 81 <ea> 78 56 34 12 sub $0x12345678, %r10d
1367 * b: 75 f9 jne 6 <fineibt_preamble_start+0x6>
1368 * d: 0f 1f 00 nopl (%rax)
1369 *
1370 * Note that the JNE target is the 0xEA byte inside the SUB, this decodes as
1371 * (bad) on x86_64 and raises #UD.
1372 */
1373asm( ".pushsection .rodata \n"
1374 "fineibt_preamble_start: \n"
1375 " endbr64 \n"
1376 " subl $0x12345678, %r10d \n"
0c92385d 1377 "fineibt_preamble_bhi: \n"
06926c6c
PZ
1378 " jne fineibt_preamble_start+6 \n"
1379 ASM_NOP3
1380 "fineibt_preamble_end: \n"
931ab636
PZ
1381 ".popsection\n"
1382);
1383
1384extern u8 fineibt_preamble_start[];
0c92385d 1385extern u8 fineibt_preamble_bhi[];
931ab636
PZ
1386extern u8 fineibt_preamble_end[];
1387
1388#define fineibt_preamble_size (fineibt_preamble_end - fineibt_preamble_start)
0c92385d 1389#define fineibt_preamble_bhi (fineibt_preamble_bhi - fineibt_preamble_start)
06926c6c 1390#define fineibt_preamble_ud 6
931ab636
PZ
1391#define fineibt_preamble_hash 7
1392
06926c6c
PZ
1393/*
1394 * <fineibt_caller_start>:
1395 * 0: 41 ba 78 56 34 12 mov $0x12345678, %r10d
1396 * 6: 4d 8d 5b f0 lea -0x10(%r11), %r11
1397 * a: 0f 1f 40 00 nopl 0x0(%rax)
1398 */
931ab636
PZ
1399asm( ".pushsection .rodata \n"
1400 "fineibt_caller_start: \n"
1401 " movl $0x12345678, %r10d \n"
06926c6c 1402 " lea -0x10(%r11), %r11 \n"
931ab636
PZ
1403 ASM_NOP4
1404 "fineibt_caller_end: \n"
1405 ".popsection \n"
1406);
1407
1408extern u8 fineibt_caller_start[];
1409extern u8 fineibt_caller_end[];
1410
1411#define fineibt_caller_size (fineibt_caller_end - fineibt_caller_start)
1412#define fineibt_caller_hash 2
1413
1414#define fineibt_caller_jmp (fineibt_caller_size - 2)
1415
97e59672
PZ
1416/*
1417 * Since FineIBT does hash validation on the callee side it is prone to
1418 * circumvention attacks where a 'naked' ENDBR instruction exists that
1419 * is not part of the fineibt_preamble sequence.
1420 *
1421 * Notably the x86 entry points must be ENDBR and equally cannot be
1422 * fineibt_preamble.
1423 *
1424 * The fineibt_paranoid caller sequence adds additional caller side
1425 * hash validation. This stops such circumvention attacks dead, but at the cost
1426 * of adding a load.
1427 *
1428 * <fineibt_paranoid_start>:
1429 * 0: 41 ba 78 56 34 12 mov $0x12345678, %r10d
1430 * 6: 45 3b 53 f7 cmp -0x9(%r11), %r10d
1431 * a: 4d 8d 5b <f0> lea -0x10(%r11), %r11
1432 * e: 75 fd jne d <fineibt_paranoid_start+0xd>
1433 * 10: 41 ff d3 call *%r11
1434 * 13: 90 nop
1435 *
1436 * Notably LEA does not modify flags and can be reordered with the CMP,
1437 * avoiding a dependency. Again, using a non-taken (backwards) branch
1438 * for the failure case, abusing LEA's immediate 0xf0 as LOCK prefix for the
1439 * Jcc.d8, causing #UD.
1440 */
1441asm( ".pushsection .rodata \n"
1442 "fineibt_paranoid_start: \n"
1443 " movl $0x12345678, %r10d \n"
1444 " cmpl -9(%r11), %r10d \n"
1445 " lea -0x10(%r11), %r11 \n"
1446 " jne fineibt_paranoid_start+0xd \n"
1447 "fineibt_paranoid_ind: \n"
1448 " call *%r11 \n"
1449 " nop \n"
1450 "fineibt_paranoid_end: \n"
1451 ".popsection \n"
1452);
1453
1454extern u8 fineibt_paranoid_start[];
1455extern u8 fineibt_paranoid_ind[];
1456extern u8 fineibt_paranoid_end[];
1457
1458#define fineibt_paranoid_size (fineibt_paranoid_end - fineibt_paranoid_start)
1459#define fineibt_paranoid_ind (fineibt_paranoid_ind - fineibt_paranoid_start)
1460#define fineibt_paranoid_ud 0xd
1461
0c92385d 1462static u32 decode_preamble_hash(void *addr, int *reg)
931ab636
PZ
1463{
1464 u8 *p = addr;
1465
0c92385d
PZ
1466 /* b8+reg 78 56 34 12 movl $0x12345678,\reg */
1467 if (p[0] >= 0xb8 && p[0] < 0xc0) {
1468 if (reg)
1469 *reg = p[0] - 0xb8;
931ab636 1470 return *(u32 *)(addr + 1);
0c92385d 1471 }
931ab636
PZ
1472
1473 return 0; /* invalid hash value */
1474}
1475
1476static u32 decode_caller_hash(void *addr)
1477{
1478 u8 *p = addr;
1479
0c92385d 1480 /* 41 ba 88 a9 cb ed mov $(-0x12345678),%r10d */
931ab636
PZ
1481 if (p[0] == 0x41 && p[1] == 0xba)
1482 return -*(u32 *)(addr + 2);
1483
0c92385d 1484 /* e8 0c 88 a9 cb ed jmp.d8 +12 */
931ab636
PZ
1485 if (p[0] == JMP8_INSN_OPCODE && p[1] == fineibt_caller_jmp)
1486 return -*(u32 *)(addr + 2);
1487
1488 return 0; /* invalid hash value */
1489}
1490
1491/* .retpoline_sites */
1d7e707a 1492static int cfi_disable_callers(s32 *start, s32 *end)
931ab636
PZ
1493{
1494 /*
1495 * Disable kCFI by patching in a JMP.d8, this leaves the hash immediate
1496 * in tact for later usage. Also see decode_caller_hash() and
1497 * cfi_rewrite_callers().
1498 */
1499 const u8 jmp[] = { JMP8_INSN_OPCODE, fineibt_caller_jmp };
1500 s32 *s;
ed53a0d9 1501
931ab636
PZ
1502 for (s = start; s < end; s++) {
1503 void *addr = (void *)s + *s;
1504 u32 hash;
1505
1506 addr -= fineibt_caller_size;
1d7e707a 1507 hash = decode_caller_hash(addr);
931ab636 1508 if (!hash) /* nocfi callers */
ed53a0d9
PZ
1509 continue;
1510
1d7e707a 1511 text_poke_early(addr, jmp, 2);
931ab636 1512 }
ed53a0d9 1513
931ab636
PZ
1514 return 0;
1515}
1516
1d7e707a 1517static int cfi_enable_callers(s32 *start, s32 *end)
0c3e806e
PZ
1518{
1519 /*
1520 * Re-enable kCFI, undo what cfi_disable_callers() did.
1521 */
1522 const u8 mov[] = { 0x41, 0xba };
1523 s32 *s;
1524
1525 for (s = start; s < end; s++) {
1526 void *addr = (void *)s + *s;
1527 u32 hash;
1528
1529 addr -= fineibt_caller_size;
1d7e707a 1530 hash = decode_caller_hash(addr);
0c3e806e 1531 if (!hash) /* nocfi callers */
ed53a0d9
PZ
1532 continue;
1533
1d7e707a 1534 text_poke_early(addr, mov, 2);
0c3e806e 1535 }
ed53a0d9 1536
0c3e806e
PZ
1537 return 0;
1538}
1539
931ab636 1540/* .cfi_sites */
1d7e707a 1541static int cfi_rand_preamble(s32 *start, s32 *end)
0c3e806e
PZ
1542{
1543 s32 *s;
1544
1545 for (s = start; s < end; s++) {
1546 void *addr = (void *)s + *s;
1547 u32 hash;
1548
0c92385d 1549 hash = decode_preamble_hash(addr, NULL);
0c3e806e
PZ
1550 if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1551 addr, addr, 5, addr))
1552 return -EINVAL;
1553
1554 hash = cfi_rehash(hash);
1d7e707a 1555 text_poke_early(addr + 1, &hash, 4);
0c3e806e
PZ
1556 }
1557
1558 return 0;
1559}
1560
dfebe736
PZ
1561static void cfi_fineibt_bhi_preamble(void *addr, int arity)
1562{
1563 if (!arity)
1564 return;
1565
1566 if (!cfi_warn && arity == 1) {
1567 /*
1568 * Crazy scheme to allow arity-1 inline:
1569 *
1570 * __cfi_foo:
1571 * 0: f3 0f 1e fa endbr64
1572 * 4: 41 81 <ea> 78 56 34 12 sub 0x12345678, %r10d
1573 * b: 49 0f 45 fa cmovne %r10, %rdi
1574 * f: 75 f5 jne __cfi_foo+6
1575 * 11: 0f 1f 00 nopl (%rax)
1576 *
1577 * Code that direct calls to foo()+0, decodes the tail end as:
1578 *
1579 * foo:
1580 * 0: f5 cmc
1581 * 1: 0f 1f 00 nopl (%rax)
1582 *
1583 * which clobbers CF, but does not affect anything ABI
1584 * wise.
1585 *
1586 * Notably, this scheme is incompatible with permissive CFI
1587 * because the CMOVcc is unconditional and RDI will have been
1588 * clobbered.
1589 */
1590 const u8 magic[9] = {
1591 0x49, 0x0f, 0x45, 0xfa,
1592 0x75, 0xf5,
1593 BYTES_NOP3,
1594 };
1595
1596 text_poke_early(addr + fineibt_preamble_bhi, magic, 9);
1597
1598 return;
1599 }
1600
1601 text_poke_early(addr + fineibt_preamble_bhi,
1602 text_gen_insn(CALL_INSN_OPCODE,
1603 addr + fineibt_preamble_bhi,
1604 __bhi_args[arity]),
1605 CALL_INSN_SIZE);
1606}
1607
1d7e707a 1608static int cfi_rewrite_preamble(s32 *start, s32 *end)
931ab636
PZ
1609{
1610 s32 *s;
1611
1612 for (s = start; s < end; s++) {
1613 void *addr = (void *)s + *s;
0c92385d 1614 int arity;
931ab636
PZ
1615 u32 hash;
1616
c4239a72
PZ
1617 /*
1618 * When the function doesn't start with ENDBR the compiler will
1619 * have determined there are no indirect calls to it and we
1620 * don't need no CFI either.
1621 */
1622 if (!is_endbr(addr + 16))
1623 continue;
1624
0c92385d 1625 hash = decode_preamble_hash(addr, &arity);
931ab636
PZ
1626 if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1627 addr, addr, 5, addr))
1628 return -EINVAL;
1629
1d7e707a
MRM
1630 text_poke_early(addr, fineibt_preamble_start, fineibt_preamble_size);
1631 WARN_ON(*(u32 *)(addr + fineibt_preamble_hash) != 0x12345678);
1632 text_poke_early(addr + fineibt_preamble_hash, &hash, 4);
0c92385d
PZ
1633
1634 WARN_ONCE(!IS_ENABLED(CONFIG_FINEIBT_BHI) && arity,
1635 "kCFI preamble has wrong register at: %pS %*ph\n",
1636 addr, 5, addr);
1637
dfebe736
PZ
1638 if (cfi_bhi)
1639 cfi_fineibt_bhi_preamble(addr, arity);
ed53a0d9 1640 }
931ab636
PZ
1641
1642 return 0;
1643}
1644
1d7e707a 1645static void cfi_rewrite_endbr(s32 *start, s32 *end)
04505bbb
PZ
1646{
1647 s32 *s;
1648
1649 for (s = start; s < end; s++) {
1650 void *addr = (void *)s + *s;
1651
dfebe736 1652 if (!exact_endbr(addr + 16))
c4239a72
PZ
1653 continue;
1654
1655 poison_endbr(addr + 16);
04505bbb
PZ
1656 }
1657}
1658
931ab636 1659/* .retpoline_sites */
1d7e707a 1660static int cfi_rand_callers(s32 *start, s32 *end)
0c3e806e
PZ
1661{
1662 s32 *s;
1663
1664 for (s = start; s < end; s++) {
1665 void *addr = (void *)s + *s;
1666 u32 hash;
1667
1668 addr -= fineibt_caller_size;
1d7e707a 1669 hash = decode_caller_hash(addr);
0c3e806e
PZ
1670 if (hash) {
1671 hash = -cfi_rehash(hash);
1d7e707a 1672 text_poke_early(addr + 2, &hash, 4);
0c3e806e
PZ
1673 }
1674 }
1675
1676 return 0;
1677}
1678
e52c1dc7
PZ
1679static int emit_paranoid_trampoline(void *addr, struct insn *insn, int reg, u8 *bytes)
1680{
1681 u8 *thunk = (void *)__x86_indirect_its_thunk_array[reg] - 2;
1682
1683#ifdef CONFIG_MITIGATION_ITS
1684 u8 *tmp = its_allocate_thunk(reg);
1685 if (tmp)
1686 thunk = tmp;
1687#endif
1688
1689 return __emit_trampoline(addr, insn, bytes, thunk, thunk);
1690}
1691
1d7e707a 1692static int cfi_rewrite_callers(s32 *start, s32 *end)
931ab636
PZ
1693{
1694 s32 *s;
1695
97e59672
PZ
1696 BUG_ON(fineibt_paranoid_size != 20);
1697
931ab636
PZ
1698 for (s = start; s < end; s++) {
1699 void *addr = (void *)s + *s;
97e59672
PZ
1700 struct insn insn;
1701 u8 bytes[20];
931ab636 1702 u32 hash;
97e59672
PZ
1703 int ret;
1704 u8 op;
931ab636
PZ
1705
1706 addr -= fineibt_caller_size;
1d7e707a 1707 hash = decode_caller_hash(addr);
97e59672
PZ
1708 if (!hash)
1709 continue;
1710
1711 if (!cfi_paranoid) {
1d7e707a
MRM
1712 text_poke_early(addr, fineibt_caller_start, fineibt_caller_size);
1713 WARN_ON(*(u32 *)(addr + fineibt_caller_hash) != 0x12345678);
1714 text_poke_early(addr + fineibt_caller_hash, &hash, 4);
97e59672
PZ
1715 /* rely on apply_retpolines() */
1716 continue;
1717 }
1718
1719 /* cfi_paranoid */
1720 ret = insn_decode_kernel(&insn, addr + fineibt_caller_size);
1721 if (WARN_ON_ONCE(ret < 0))
1722 continue;
1723
1724 op = insn.opcode.bytes[0];
1725 if (op != CALL_INSN_OPCODE && op != JMP32_INSN_OPCODE) {
1726 WARN_ON_ONCE(1);
1727 continue;
931ab636 1728 }
97e59672
PZ
1729
1730 memcpy(bytes, fineibt_paranoid_start, fineibt_paranoid_size);
1731 memcpy(bytes + fineibt_caller_hash, &hash, 4);
1732
e52c1dc7
PZ
1733 if (cpu_wants_indirect_its_thunk_at((unsigned long)addr + fineibt_paranoid_ind, 11)) {
1734 emit_paranoid_trampoline(addr + fineibt_caller_size,
1735 &insn, 11, bytes + fineibt_caller_size);
1736 } else {
1737 ret = emit_indirect(op, 11, bytes + fineibt_paranoid_ind);
1738 if (WARN_ON_ONCE(ret != 3))
1739 continue;
1740 }
97e59672
PZ
1741
1742 text_poke_early(addr, bytes, fineibt_paranoid_size);
931ab636
PZ
1743 }
1744
1745 return 0;
1746}
1747
1748static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1d7e707a 1749 s32 *start_cfi, s32 *end_cfi, bool builtin)
931ab636
PZ
1750{
1751 int ret;
1752
1753 if (WARN_ONCE(fineibt_preamble_size != 16,
1754 "FineIBT preamble wrong size: %ld", fineibt_preamble_size))
1755 return;
1756
d6f635bc 1757 if (cfi_mode == CFI_AUTO) {
082c4c81 1758 cfi_mode = CFI_KCFI;
97e59672
PZ
1759 if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT)) {
1760 /*
1761 * FRED has much saner context on exception entry and
1762 * is less easy to take advantage of.
1763 */
1764 if (!cpu_feature_enabled(X86_FEATURE_FRED))
1765 cfi_paranoid = true;
082c4c81 1766 cfi_mode = CFI_FINEIBT;
97e59672 1767 }
082c4c81
PZ
1768 }
1769
0c3e806e
PZ
1770 /*
1771 * Rewrite the callers to not use the __cfi_ stubs, such that we might
1772 * rewrite them. This disables all CFI. If this succeeds but any of the
1773 * later stages fails, we're without CFI.
1774 */
1d7e707a 1775 ret = cfi_disable_callers(start_retpoline, end_retpoline);
0c3e806e
PZ
1776 if (ret)
1777 goto err;
1778
1779 if (cfi_rand) {
4f9087f1 1780 if (builtin) {
0c3e806e 1781 cfi_seed = get_random_u32();
4f9087f1 1782 cfi_bpf_hash = cfi_rehash(cfi_bpf_hash);
e72d88d1 1783 cfi_bpf_subprog_hash = cfi_rehash(cfi_bpf_subprog_hash);
4f9087f1 1784 }
0c3e806e 1785
1d7e707a 1786 ret = cfi_rand_preamble(start_cfi, end_cfi);
082c4c81
PZ
1787 if (ret)
1788 goto err;
1789
1d7e707a 1790 ret = cfi_rand_callers(start_retpoline, end_retpoline);
0c3e806e
PZ
1791 if (ret)
1792 goto err;
ed53a0d9 1793 }
0c3e806e
PZ
1794
1795 switch (cfi_mode) {
1796 case CFI_OFF:
082c4c81
PZ
1797 if (builtin)
1798 pr_info("Disabling CFI\n");
931ab636
PZ
1799 return;
1800
082c4c81 1801 case CFI_KCFI:
1d7e707a 1802 ret = cfi_enable_callers(start_retpoline, end_retpoline);
0c3e806e
PZ
1803 if (ret)
1804 goto err;
1805
082c4c81
PZ
1806 if (builtin)
1807 pr_info("Using kCFI\n");
1808 return;
931ab636 1809
082c4c81 1810 case CFI_FINEIBT:
04505bbb 1811 /* place the FineIBT preamble at func()-16 */
1d7e707a 1812 ret = cfi_rewrite_preamble(start_cfi, end_cfi);
082c4c81
PZ
1813 if (ret)
1814 goto err;
931ab636 1815
04505bbb 1816 /* rewrite the callers to target func()-16 */
1d7e707a 1817 ret = cfi_rewrite_callers(start_retpoline, end_retpoline);
082c4c81
PZ
1818 if (ret)
1819 goto err;
931ab636 1820
04505bbb 1821 /* now that nobody targets func()+0, remove ENDBR there */
1d7e707a 1822 cfi_rewrite_endbr(start_cfi, end_cfi);
04505bbb 1823
97e59672 1824 if (builtin) {
0c92385d
PZ
1825 pr_info("Using %sFineIBT%s CFI\n",
1826 cfi_paranoid ? "paranoid " : "",
1827 cfi_bhi ? "+BHI" : "");
97e59672 1828 }
082c4c81 1829 return;
931ab636 1830
082c4c81
PZ
1831 default:
1832 break;
1833 }
931ab636
PZ
1834
1835err:
1836 pr_err("Something went horribly wrong trying to rewrite the CFI implementation.\n");
ed53a0d9
PZ
1837}
1838
9831c625
PZ
1839static inline void poison_hash(void *addr)
1840{
1841 *(u32 *)addr = 0;
1842}
1843
1d7e707a 1844static void poison_cfi(void *addr)
9831c625 1845{
c4239a72
PZ
1846 /*
1847 * Compilers manage to be inconsistent with ENDBR vs __cfi prefixes,
1848 * some (static) functions for which they can determine the address
1849 * is never taken do not get a __cfi prefix, but *DO* get an ENDBR.
1850 *
1851 * As such, these functions will get sealed, but we need to be careful
1852 * to not unconditionally scribble the previous function.
1853 */
9831c625
PZ
1854 switch (cfi_mode) {
1855 case CFI_FINEIBT:
c4239a72
PZ
1856 /*
1857 * FineIBT prefix should start with an ENDBR.
1858 */
1859 if (!is_endbr(addr))
1860 break;
1861
9831c625
PZ
1862 /*
1863 * __cfi_\func:
1864 * osp nopl (%rax)
1865 * subl $0, %r10d
1866 * jz 1f
1867 * ud2
1868 * 1: nop
1869 */
c4239a72 1870 poison_endbr(addr);
1d7e707a 1871 poison_hash(addr + fineibt_preamble_hash);
9831c625
PZ
1872 break;
1873
1874 case CFI_KCFI:
c4239a72
PZ
1875 /*
1876 * kCFI prefix should start with a valid hash.
1877 */
0c92385d 1878 if (!decode_preamble_hash(addr, NULL))
c4239a72
PZ
1879 break;
1880
9831c625
PZ
1881 /*
1882 * __cfi_\func:
1883 * movl $0, %eax
1884 * .skip 11, 0x90
1885 */
1d7e707a 1886 poison_hash(addr + 1);
9831c625
PZ
1887 break;
1888
1889 default:
1890 break;
1891 }
1892}
1893
882b86fd 1894/*
06926c6c
PZ
1895 * When regs->ip points to a 0xEA byte in the FineIBT preamble,
1896 * return true and fill out target and type.
882b86fd
PZ
1897 *
1898 * We check the preamble by checking for the ENDBR instruction relative to the
06926c6c 1899 * 0xEA instruction.
882b86fd 1900 */
97e59672 1901static bool decode_fineibt_preamble(struct pt_regs *regs, unsigned long *target, u32 *type)
882b86fd 1902{
06926c6c 1903 unsigned long addr = regs->ip - fineibt_preamble_ud;
500a41ac 1904 u32 hash;
882b86fd 1905
500a41ac 1906 if (!exact_endbr((void *)addr))
882b86fd
PZ
1907 return false;
1908
1909 *target = addr + fineibt_preamble_size;
1910
1911 __get_kernel_nofault(&hash, addr + fineibt_preamble_hash, u32, Efault);
1912 *type = (u32)regs->r10 + hash;
1913
06926c6c
PZ
1914 /*
1915 * Since regs->ip points to the middle of an instruction; it cannot
1916 * continue with the normal fixup.
1917 */
1918 regs->ip = *target;
1919
882b86fd
PZ
1920 return true;
1921
1922Efault:
1923 return false;
1924}
1925
0c92385d
PZ
1926/*
1927 * regs->ip points to one of the UD2 in __bhi_args[].
1928 */
1929static bool decode_fineibt_bhi(struct pt_regs *regs, unsigned long *target, u32 *type)
1930{
1931 unsigned long addr;
1932 u32 hash;
1933
1934 if (!cfi_bhi)
1935 return false;
1936
1937 if (regs->ip < (unsigned long)__bhi_args ||
1938 regs->ip >= (unsigned long)__bhi_args_end)
1939 return false;
1940
1941 /*
1942 * Fetch the return address from the stack, this points to the
1943 * FineIBT preamble. Since the CALL instruction is in the 5 last
1944 * bytes of the preamble, the return address is in fact the target
1945 * address.
1946 */
1947 __get_kernel_nofault(&addr, regs->sp, unsigned long, Efault);
1948 *target = addr;
1949
1950 addr -= fineibt_preamble_size;
1951 if (!exact_endbr((void *)addr))
1952 return false;
1953
1954 __get_kernel_nofault(&hash, addr + fineibt_preamble_hash, u32, Efault);
1955 *type = (u32)regs->r10 + hash;
1956
1957 /*
1958 * The UD2 sites are constructed with a RET immediately following,
1959 * as such the non-fatal case can use the regular fixup.
1960 */
1961 return true;
1962
1963Efault:
1964 return false;
1965}
1966
e52c1dc7
PZ
1967static bool is_paranoid_thunk(unsigned long addr)
1968{
1969 u32 thunk;
1970
1971 __get_kernel_nofault(&thunk, (u32 *)addr, u32, Efault);
1972 return (thunk & 0x00FFFFFF) == 0xfd75ea;
1973
1974Efault:
1975 return false;
1976}
1977
97e59672
PZ
1978/*
1979 * regs->ip points to a LOCK Jcc.d8 instruction from the fineibt_paranoid_start[]
e52c1dc7
PZ
1980 * sequence, or to an invalid instruction (0xea) + Jcc.d8 for cfi_paranoid + ITS
1981 * thunk.
97e59672
PZ
1982 */
1983static bool decode_fineibt_paranoid(struct pt_regs *regs, unsigned long *target, u32 *type)
1984{
1985 unsigned long addr = regs->ip - fineibt_paranoid_ud;
97e59672 1986
e52c1dc7 1987 if (!cfi_paranoid)
97e59672
PZ
1988 return false;
1989
e52c1dc7
PZ
1990 if (is_cfi_trap(addr + fineibt_caller_size - LEN_UD2)) {
1991 *target = regs->r11 + fineibt_preamble_size;
1992 *type = regs->r10;
1993
1994 /*
1995 * Since the trapping instruction is the exact, but LOCK prefixed,
1996 * Jcc.d8 that got us here, the normal fixup will work.
1997 */
1998 return true;
1999 }
97e59672
PZ
2000
2001 /*
e52c1dc7
PZ
2002 * The cfi_paranoid + ITS thunk combination results in:
2003 *
2004 * 0: 41 ba 78 56 34 12 mov $0x12345678, %r10d
2005 * 6: 45 3b 53 f7 cmp -0x9(%r11), %r10d
2006 * a: 4d 8d 5b f0 lea -0x10(%r11), %r11
2007 * e: 2e e8 XX XX XX XX cs call __x86_indirect_paranoid_thunk_r11
2008 *
2009 * Where the paranoid_thunk looks like:
2010 *
2011 * 1d: <ea> (bad)
2012 * __x86_indirect_paranoid_thunk_r11:
2013 * 1e: 75 fd jne 1d
2014 * __x86_indirect_its_thunk_r11:
2015 * 20: 41 ff eb jmp *%r11
2016 * 23: cc int3
2017 *
97e59672 2018 */
e52c1dc7
PZ
2019 if (is_paranoid_thunk(regs->ip)) {
2020 *target = regs->r11 + fineibt_preamble_size;
2021 *type = regs->r10;
2022
2023 regs->ip = *target;
2024 return true;
2025 }
97e59672 2026
97e59672
PZ
2027 return false;
2028}
2029
2030bool decode_fineibt_insn(struct pt_regs *regs, unsigned long *target, u32 *type)
2031{
2032 if (decode_fineibt_paranoid(regs, target, type))
2033 return true;
2034
0c92385d
PZ
2035 if (decode_fineibt_bhi(regs, target, type))
2036 return true;
2037
97e59672
PZ
2038 return decode_fineibt_preamble(regs, target, type);
2039}
2040
5d703825 2041#else /* !CONFIG_FINEIBT: */
ed53a0d9 2042
931ab636 2043static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1d7e707a 2044 s32 *start_cfi, s32 *end_cfi, bool builtin)
931ab636
PZ
2045{
2046}
ed53a0d9 2047
535d0ae3 2048#ifdef CONFIG_X86_KERNEL_IBT
1d7e707a 2049static void poison_cfi(void *addr) { }
535d0ae3 2050#endif
9831c625 2051
5d703825 2052#endif /* !CONFIG_FINEIBT */
931ab636
PZ
2053
2054void apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1d7e707a 2055 s32 *start_cfi, s32 *end_cfi)
931ab636
PZ
2056{
2057 return __apply_fineibt(start_retpoline, end_retpoline,
1d7e707a
MRM
2058 start_cfi, end_cfi,
2059 /* .builtin = */ false);
931ab636 2060}
ed53a0d9 2061
8ec4d41f 2062#ifdef CONFIG_SMP
5967ed87
JB
2063static void alternatives_smp_lock(const s32 *start, const s32 *end,
2064 u8 *text, u8 *text_end)
9a0b5817 2065{
5967ed87 2066 const s32 *poff;
9a0b5817 2067
5967ed87
JB
2068 for (poff = start; poff < end; poff++) {
2069 u8 *ptr = (u8 *)poff + *poff;
2070
2071 if (!*poff || ptr < text || ptr >= text_end)
9a0b5817 2072 continue;
f88f07e0 2073 /* turn DS segment override prefix into lock prefix */
d9c5841e
PA
2074 if (*ptr == 0x3e)
2075 text_poke(ptr, ((unsigned char []){0xf0}), 1);
4b8073e4 2076 }
9a0b5817
GH
2077}
2078
5967ed87
JB
2079static void alternatives_smp_unlock(const s32 *start, const s32 *end,
2080 u8 *text, u8 *text_end)
9a0b5817 2081{
5967ed87 2082 const s32 *poff;
9a0b5817 2083
5967ed87
JB
2084 for (poff = start; poff < end; poff++) {
2085 u8 *ptr = (u8 *)poff + *poff;
2086
2087 if (!*poff || ptr < text || ptr >= text_end)
9a0b5817 2088 continue;
f88f07e0 2089 /* turn lock prefix into DS segment override prefix */
d9c5841e
PA
2090 if (*ptr == 0xf0)
2091 text_poke(ptr, ((unsigned char []){0x3E}), 1);
4b8073e4 2092 }
9a0b5817
GH
2093}
2094
2095struct smp_alt_module {
2096 /* what is this ??? */
2097 struct module *mod;
2098 char *name;
2099
2100 /* ptrs to lock prefixes */
5967ed87
JB
2101 const s32 *locks;
2102 const s32 *locks_end;
9a0b5817
GH
2103
2104 /* .text segment, needed to avoid patching init code ;) */
2105 u8 *text;
2106 u8 *text_end;
2107
2108 struct list_head next;
2109};
2110static LIST_HEAD(smp_alt_modules);
e846d139 2111static bool uniproc_patched = false; /* protected by text_mutex */
9a0b5817 2112
8b5a10fc
JB
2113void __init_or_module alternatives_smp_module_add(struct module *mod,
2114 char *name,
2115 void *locks, void *locks_end,
2116 void *text, void *text_end)
9a0b5817
GH
2117{
2118 struct smp_alt_module *smp;
9a0b5817 2119
e846d139 2120 mutex_lock(&text_mutex);
816afe4f
RR
2121 if (!uniproc_patched)
2122 goto unlock;
b7fb4af0 2123
816afe4f
RR
2124 if (num_possible_cpus() == 1)
2125 /* Don't bother remembering, we'll never have to undo it. */
2126 goto smp_unlock;
9a0b5817
GH
2127
2128 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
2129 if (NULL == smp)
816afe4f
RR
2130 /* we'll run the (safe but slow) SMP code then ... */
2131 goto unlock;
9a0b5817
GH
2132
2133 smp->mod = mod;
2134 smp->name = name;
2135 smp->locks = locks;
2136 smp->locks_end = locks_end;
2137 smp->text = text;
2138 smp->text_end = text_end;
6becb502 2139 DPRINTK(SMP, "locks %p -> %p, text %p -> %p, name %s\n",
db477a33 2140 smp->locks, smp->locks_end,
9a0b5817
GH
2141 smp->text, smp->text_end, smp->name);
2142
9a0b5817 2143 list_add_tail(&smp->next, &smp_alt_modules);
816afe4f
RR
2144smp_unlock:
2145 alternatives_smp_unlock(locks, locks_end, text, text_end);
2146unlock:
e846d139 2147 mutex_unlock(&text_mutex);
9a0b5817
GH
2148}
2149
8b5a10fc 2150void __init_or_module alternatives_smp_module_del(struct module *mod)
9a0b5817
GH
2151{
2152 struct smp_alt_module *item;
9a0b5817 2153
e846d139 2154 mutex_lock(&text_mutex);
9a0b5817
GH
2155 list_for_each_entry(item, &smp_alt_modules, next) {
2156 if (mod != item->mod)
2157 continue;
2158 list_del(&item->next);
9a0b5817 2159 kfree(item);
816afe4f 2160 break;
9a0b5817 2161 }
e846d139 2162 mutex_unlock(&text_mutex);
9a0b5817
GH
2163}
2164
816afe4f 2165void alternatives_enable_smp(void)
9a0b5817
GH
2166{
2167 struct smp_alt_module *mod;
9a0b5817 2168
816afe4f
RR
2169 /* Why bother if there are no other CPUs? */
2170 BUG_ON(num_possible_cpus() == 1);
9a0b5817 2171
e846d139 2172 mutex_lock(&text_mutex);
ca74a6f8 2173
816afe4f 2174 if (uniproc_patched) {
c767a54b 2175 pr_info("switching to SMP code\n");
816afe4f 2176 BUG_ON(num_online_cpus() != 1);
53756d37
JF
2177 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
2178 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
9a0b5817
GH
2179 list_for_each_entry(mod, &smp_alt_modules, next)
2180 alternatives_smp_lock(mod->locks, mod->locks_end,
2181 mod->text, mod->text_end);
816afe4f 2182 uniproc_patched = false;
9a0b5817 2183 }
e846d139 2184 mutex_unlock(&text_mutex);
9a0b5817
GH
2185}
2186
e846d139
ZC
2187/*
2188 * Return 1 if the address range is reserved for SMP-alternatives.
2189 * Must hold text_mutex.
2190 */
2cfa1978
MH
2191int alternatives_text_reserved(void *start, void *end)
2192{
2193 struct smp_alt_module *mod;
5967ed87 2194 const s32 *poff;
076dc4a6
MH
2195 u8 *text_start = start;
2196 u8 *text_end = end;
2cfa1978 2197
e846d139
ZC
2198 lockdep_assert_held(&text_mutex);
2199
2cfa1978 2200 list_for_each_entry(mod, &smp_alt_modules, next) {
076dc4a6 2201 if (mod->text > text_end || mod->text_end < text_start)
2cfa1978 2202 continue;
5967ed87
JB
2203 for (poff = mod->locks; poff < mod->locks_end; poff++) {
2204 const u8 *ptr = (const u8 *)poff + *poff;
2205
2206 if (text_start <= ptr && text_end > ptr)
2cfa1978 2207 return 1;
5967ed87 2208 }
2cfa1978
MH
2209 }
2210
2211 return 0;
2212}
48c7a250 2213#endif /* CONFIG_SMP */
8ec4d41f 2214
7457c0da
PZ
2215/*
2216 * Self-test for the INT3 based CALL emulation code.
2217 *
2218 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
2219 * properly and that there is a stack gap between the INT3 frame and the
2220 * previous context. Without this gap doing a virtual PUSH on the interrupted
2221 * stack would corrupt the INT3 IRET frame.
2222 *
2223 * See entry_{32,64}.S for more details.
2224 */
ecc60610
PZ
2225
2226/*
2227 * We define the int3_magic() function in assembly to control the calling
2228 * convention such that we can 'call' it from assembly.
2229 */
2230
2231extern void int3_magic(unsigned int *ptr); /* defined in asm */
2232
2233asm (
2234" .pushsection .init.text, \"ax\", @progbits\n"
2235" .type int3_magic, @function\n"
2236"int3_magic:\n"
3e3f0695 2237 ANNOTATE_NOENDBR
ecc60610 2238" movl $1, (%" _ASM_ARG1 ")\n"
b17c2baa 2239 ASM_RET
ecc60610
PZ
2240" .size int3_magic, .-int3_magic\n"
2241" .popsection\n"
2242);
7457c0da 2243
99c95c5d 2244extern void int3_selftest_ip(void); /* defined in asm below */
7457c0da
PZ
2245
2246static int __init
2247int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
2248{
3e3f0695 2249 unsigned long selftest = (unsigned long)&int3_selftest_ip;
7457c0da
PZ
2250 struct die_args *args = data;
2251 struct pt_regs *regs = args->regs;
2252
3e3f0695
PZ
2253 OPTIMIZER_HIDE_VAR(selftest);
2254
7457c0da
PZ
2255 if (!regs || user_mode(regs))
2256 return NOTIFY_DONE;
2257
2258 if (val != DIE_INT3)
2259 return NOTIFY_DONE;
2260
3e3f0695 2261 if (regs->ip - INT3_INSN_SIZE != selftest)
7457c0da
PZ
2262 return NOTIFY_DONE;
2263
2264 int3_emulate_call(regs, (unsigned long)&int3_magic);
2265 return NOTIFY_STOP;
2266}
2267
99c95c5d
PZ
2268/* Must be noinline to ensure uniqueness of int3_selftest_ip. */
2269static noinline void __init int3_selftest(void)
7457c0da
PZ
2270{
2271 static __initdata struct notifier_block int3_exception_nb = {
2272 .notifier_call = int3_exception_notify,
2273 .priority = INT_MAX-1, /* last */
2274 };
2275 unsigned int val = 0;
2276
2277 BUG_ON(register_die_notifier(&int3_exception_nb));
2278
2279 /*
2280 * Basically: int3_magic(&val); but really complicated :-)
2281 *
99c95c5d
PZ
2282 * INT3 padded with NOP to CALL_INSN_SIZE. The int3_exception_nb
2283 * notifier above will emulate CALL for us.
7457c0da 2284 */
3e3f0695
PZ
2285 asm volatile ("int3_selftest_ip:\n\t"
2286 ANNOTATE_NOENDBR
2287 " int3; nop; nop; nop; nop\n\t"
ecc60610
PZ
2288 : ASM_CALL_CONSTRAINT
2289 : __ASM_SEL_RAW(a, D) (&val)
2290 : "memory");
7457c0da
PZ
2291
2292 BUG_ON(val != 1);
2293
2294 unregister_die_notifier(&int3_exception_nb);
2295}
2296
270a69c4
PZ
2297static __initdata int __alt_reloc_selftest_addr;
2298
1a3e4b4d 2299extern void __init __alt_reloc_selftest(void *arg);
270a69c4
PZ
2300__visible noinline void __init __alt_reloc_selftest(void *arg)
2301{
2302 WARN_ON(arg != &__alt_reloc_selftest_addr);
2303}
2304
2305static noinline void __init alt_reloc_selftest(void)
2306{
2307 /*
023f42dd 2308 * Tests text_poke_apply_relocation().
270a69c4
PZ
2309 *
2310 * This has a relative immediate (CALL) in a place other than the first
2311 * instruction and additionally on x86_64 we get a RIP-relative LEA:
2312 *
2313 * lea 0x0(%rip),%rdi # 5d0: R_X86_64_PC32 .init.data+0x5566c
2314 * call +0 # 5d5: R_X86_64_PLT32 __alt_reloc_selftest-0x4
2315 *
2316 * Getting this wrong will either crash and burn or tickle the WARN
2317 * above.
2318 */
2319 asm_inline volatile (
2320 ALTERNATIVE("", "lea %[mem], %%" _ASM_ARG1 "; call __alt_reloc_selftest;", X86_FEATURE_ALWAYS)
0d3db1f1 2321 : ASM_CALL_CONSTRAINT
270a69c4
PZ
2322 : [mem] "m" (__alt_reloc_selftest_addr)
2323 : _ASM_ARG1
2324 );
2325}
2326
9a0b5817
GH
2327void __init alternative_instructions(void)
2328{
ebebe307
PG
2329 u64 ibt;
2330
7457c0da
PZ
2331 int3_selftest();
2332
2333 /*
2334 * The patching is not fully atomic, so try to avoid local
2335 * interruptions that might execute the to be patched code.
2336 * Other CPUs are not running.
2337 */
8f4e956b 2338 stop_nmi();
123aa76e
AK
2339
2340 /*
2341 * Don't stop machine check exceptions while patching.
2342 * MCEs only happen when something got corrupted and in this
2343 * case we must do something about the corruption.
32b1cbe3 2344 * Ignoring it is worse than an unlikely patching race.
123aa76e
AK
2345 * Also machine checks tend to be broadcast and if one CPU
2346 * goes into machine check the others follow quickly, so we don't
2347 * expect a machine check to cause undue problems during to code
2348 * patching.
2349 */
8f4e956b 2350
4e629211 2351 /*
f7af6977
JG
2352 * Make sure to set (artificial) features depending on used paravirt
2353 * functions which can later influence alternative patching.
4e629211
JG
2354 */
2355 paravirt_set_cap();
2356
ebebe307
PG
2357 /* Keep CET-IBT disabled until caller/callee are patched */
2358 ibt = ibt_save(/*disable*/ true);
2359
931ab636 2360 __apply_fineibt(__retpoline_sites, __retpoline_sites_end,
1d7e707a 2361 __cfi_sites, __cfi_sites_end, true);
931ab636 2362
75085009
PZ
2363 /*
2364 * Rewrite the retpolines, must be done before alternatives since
2365 * those can rewrite the retpoline thunks.
2366 */
1d7e707a
MRM
2367 apply_retpolines(__retpoline_sites, __retpoline_sites_end);
2368 apply_returns(__return_sites, __return_sites_end);
75085009 2369
a82b2645
PZI
2370 its_fini_core();
2371
e81dc127 2372 /*
ab9fea59
PZ
2373 * Adjust all CALL instructions to point to func()-10, including
2374 * those in .altinstr_replacement.
e81dc127
TG
2375 */
2376 callthunks_patch_builtin_calls();
2377
ab9fea59
PZ
2378 apply_alternatives(__alt_instructions, __alt_instructions_end);
2379
be0fffa5
PZ
2380 /*
2381 * Seal all functions that do not have their address taken.
2382 */
1d7e707a 2383 apply_seal_endbr(__ibt_endbr_seal, __ibt_endbr_seal_end);
ed53a0d9 2384
ebebe307
PG
2385 ibt_restore(ibt);
2386
8ec4d41f 2387#ifdef CONFIG_SMP
816afe4f
RR
2388 /* Patch to UP if other cpus not imminent. */
2389 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
2390 uniproc_patched = true;
9a0b5817
GH
2391 alternatives_smp_module_add(NULL, "core kernel",
2392 __smp_locks, __smp_locks_end,
2393 _text, _etext);
9a0b5817 2394 }
8f4e956b 2395
7457c0da 2396 if (!uniproc_patched || num_possible_cpus() == 1) {
f68fd5f4
FW
2397 free_init_pages("SMP alternatives",
2398 (unsigned long)__smp_locks,
2399 (unsigned long)__smp_locks_end);
7457c0da 2400 }
816afe4f
RR
2401#endif
2402
8f4e956b 2403 restart_nmi();
5e907bb0 2404 alternatives_patched = 1;
270a69c4
PZ
2405
2406 alt_reloc_selftest();
9a0b5817 2407}
19d36ccd 2408
e587cadd
MD
2409/**
2410 * text_poke_early - Update instructions on a live kernel at boot time
2411 * @addr: address to modify
2412 * @opcode: source of the copy
2413 * @len: length to copy
2414 *
19d36ccd
AK
2415 * When you use this code to patch more than one byte of an instruction
2416 * you need to make sure that other CPUs cannot execute this code in parallel.
e587cadd 2417 * Also no thread must be currently preempted in the middle of these
32b1cbe3
MA
2418 * instructions. And on the local CPU you need to be protected against NMI or
2419 * MCE handlers seeing an inconsistent instruction while you patch.
19d36ccd 2420 */
0a203df5
NA
2421void __init_or_module text_poke_early(void *addr, const void *opcode,
2422 size_t len)
19d36ccd 2423{
e587cadd 2424 unsigned long flags;
f2c65fb3
NA
2425
2426 if (boot_cpu_has(X86_FEATURE_NX) &&
2427 is_module_text_address((unsigned long)addr)) {
2428 /*
2429 * Modules text is marked initially as non-executable, so the
2430 * code cannot be running and speculative code-fetches are
2431 * prevented. Just change the code.
2432 */
2433 memcpy(addr, opcode, len);
2434 } else {
2435 local_irq_save(flags);
2436 memcpy(addr, opcode, len);
f2c65fb3 2437 sync_core();
3ea1704a 2438 local_irq_restore(flags);
f2c65fb3
NA
2439
2440 /*
2441 * Could also do a CLFLUSH here to speed up CPU recovery; but
2442 * that causes hangs on some VIA CPUs.
2443 */
2444 }
e587cadd
MD
2445}
2446
a5c832e0 2447__ro_after_init struct mm_struct *text_poke_mm;
da364fc5 2448__ro_after_init unsigned long text_poke_mm_addr;
209954cb 2449
aadd1b67
SL
2450static void text_poke_memcpy(void *dst, const void *src, size_t len)
2451{
2452 memcpy(dst, src, len);
2453}
2454
2455static void text_poke_memset(void *dst, const void *src, size_t len)
2456{
2457 int c = *(const int *)src;
2458
2459 memset(dst, c, len);
2460}
2461
2462typedef void text_poke_f(void *dst, const void *src, size_t len);
2463
2464static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t len)
e587cadd 2465{
b3fd8e83
NA
2466 bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
2467 struct page *pages[2] = {NULL};
f5afa2e8 2468 struct mm_struct *prev_mm;
78ff7fae 2469 unsigned long flags;
b3fd8e83
NA
2470 pte_t pte, *ptep;
2471 spinlock_t *ptl;
2472 pgprot_t pgprot;
e587cadd 2473
6fffacb3 2474 /*
b3fd8e83
NA
2475 * While boot memory allocator is running we cannot use struct pages as
2476 * they are not yet initialized. There is no way to recover.
6fffacb3
PT
2477 */
2478 BUG_ON(!after_bootmem);
2479
b7b66baa
MD
2480 if (!core_kernel_text((unsigned long)addr)) {
2481 pages[0] = vmalloc_to_page(addr);
b3fd8e83
NA
2482 if (cross_page_boundary)
2483 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
15a601eb 2484 } else {
b7b66baa 2485 pages[0] = virt_to_page(addr);
00c6b2d5 2486 WARN_ON(!PageReserved(pages[0]));
b3fd8e83
NA
2487 if (cross_page_boundary)
2488 pages[1] = virt_to_page(addr + PAGE_SIZE);
e587cadd 2489 }
b3fd8e83
NA
2490 /*
2491 * If something went wrong, crash and burn since recovery paths are not
2492 * implemented.
2493 */
2494 BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
2495
b3fd8e83
NA
2496 /*
2497 * Map the page without the global bit, as TLB flushing is done with
2498 * flush_tlb_mm_range(), which is intended for non-global PTEs.
2499 */
2500 pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
2501
2502 /*
2503 * The lock is not really needed, but this allows to avoid open-coding.
2504 */
da364fc5 2505 ptep = get_locked_pte(text_poke_mm, text_poke_mm_addr, &ptl);
b3fd8e83
NA
2506
2507 /*
2508 * This must not fail; preallocated in poking_init().
2509 */
2510 VM_BUG_ON(!ptep);
2511
a6d996cb
SAS
2512 local_irq_save(flags);
2513
b3fd8e83 2514 pte = mk_pte(pages[0], pgprot);
da364fc5 2515 set_pte_at(text_poke_mm, text_poke_mm_addr, ptep, pte);
b3fd8e83
NA
2516
2517 if (cross_page_boundary) {
2518 pte = mk_pte(pages[1], pgprot);
da364fc5 2519 set_pte_at(text_poke_mm, text_poke_mm_addr + PAGE_SIZE, ptep + 1, pte);
b3fd8e83
NA
2520 }
2521
2522 /*
2523 * Loading the temporary mm behaves as a compiler barrier, which
2524 * guarantees that the PTE will be set at the time memcpy() is done.
2525 */
f5afa2e8 2526 prev_mm = use_temporary_mm(text_poke_mm);
b3fd8e83
NA
2527
2528 kasan_disable_current();
da364fc5 2529 func((u8 *)text_poke_mm_addr + offset_in_page(addr), src, len);
b3fd8e83
NA
2530 kasan_enable_current();
2531
2532 /*
2533 * Ensure that the PTE is only cleared after the instructions of memcpy
2534 * were issued by using a compiler barrier.
2535 */
2536 barrier();
2537
da364fc5 2538 pte_clear(text_poke_mm, text_poke_mm_addr, ptep);
b3fd8e83 2539 if (cross_page_boundary)
da364fc5 2540 pte_clear(text_poke_mm, text_poke_mm_addr + PAGE_SIZE, ptep + 1);
b3fd8e83
NA
2541
2542 /*
2543 * Loading the previous page-table hierarchy requires a serializing
2544 * instruction that already allows the core to see the updated version.
2545 * Xen-PV is assumed to serialize execution in a similar manner.
2546 */
4873f494 2547 unuse_temporary_mm(prev_mm);
b3fd8e83
NA
2548
2549 /*
2550 * Flushing the TLB might involve IPIs, which would require enabled
2551 * IRQs, but not if the mm is not used, as it is in this point.
2552 */
da364fc5 2553 flush_tlb_mm_range(text_poke_mm, text_poke_mm_addr, text_poke_mm_addr +
b3fd8e83
NA
2554 (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
2555 PAGE_SHIFT, false);
2556
aadd1b67
SL
2557 if (func == text_poke_memcpy) {
2558 /*
2559 * If the text does not match what we just wrote then something is
2560 * fundamentally screwy; there's nothing we can really do about that.
2561 */
2562 BUG_ON(memcmp(addr, src, len));
2563 }
b3fd8e83 2564
7cf49427 2565 local_irq_restore(flags);
a6d996cb 2566 pte_unmap_unlock(ptep, ptl);
e587cadd 2567 return addr;
19d36ccd 2568}
3d55cc8a 2569
e836673c
NA
2570/**
2571 * text_poke - Update instructions on a live kernel
2572 * @addr: address to modify
2573 * @opcode: source of the copy
2574 * @len: length to copy
2575 *
2576 * Only atomic text poke/set should be allowed when not doing early patching.
2577 * It means the size must be writable atomically and the address must be aligned
2578 * in a way that permits an atomic write. It also makes sure we fit on a single
2579 * page.
3950746d
NA
2580 *
2581 * Note that the caller must ensure that if the modified code is part of a
2582 * module, the module would not be removed during poking. This can be achieved
2583 * by registering a module notifier, and ordering module removal and patching
54aa699e 2584 * through a mutex.
e836673c
NA
2585 */
2586void *text_poke(void *addr, const void *opcode, size_t len)
2587{
2588 lockdep_assert_held(&text_mutex);
2589
aadd1b67 2590 return __text_poke(text_poke_memcpy, addr, opcode, len);
e836673c
NA
2591}
2592
2593/**
2594 * text_poke_kgdb - Update instructions on a live kernel by kgdb
2595 * @addr: address to modify
2596 * @opcode: source of the copy
2597 * @len: length to copy
2598 *
2599 * Only atomic text poke/set should be allowed when not doing early patching.
2600 * It means the size must be writable atomically and the address must be aligned
2601 * in a way that permits an atomic write. It also makes sure we fit on a single
2602 * page.
2603 *
2604 * Context: should only be used by kgdb, which ensures no other core is running,
2605 * despite the fact it does not hold the text_mutex.
2606 */
2607void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
2608{
aadd1b67 2609 return __text_poke(text_poke_memcpy, addr, opcode, len);
e836673c
NA
2610}
2611
fe54d079
TG
2612void *text_poke_copy_locked(void *addr, const void *opcode, size_t len,
2613 bool core_ok)
0e06b403
SL
2614{
2615 unsigned long start = (unsigned long)addr;
2616 size_t patched = 0;
2617
fe54d079 2618 if (WARN_ON_ONCE(!core_ok && core_kernel_text(start)))
0e06b403
SL
2619 return NULL;
2620
0e06b403
SL
2621 while (patched < len) {
2622 unsigned long ptr = start + patched;
2623 size_t s;
2624
2625 s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
2626
aadd1b67
SL
2627 __text_poke(text_poke_memcpy, (void *)ptr, opcode + patched, s);
2628 patched += s;
2629 }
fe54d079
TG
2630 return addr;
2631}
2632
2633/**
2634 * text_poke_copy - Copy instructions into (an unused part of) RX memory
2635 * @addr: address to modify
2636 * @opcode: source of the copy
2637 * @len: length to copy, could be more than 2x PAGE_SIZE
2638 *
2639 * Not safe against concurrent execution; useful for JITs to dump
2640 * new code blocks into unused regions of RX memory. Can be used in
2641 * conjunction with synchronize_rcu_tasks() to wait for existing
2642 * execution to quiesce after having made sure no existing functions
2643 * pointers are live.
2644 */
2645void *text_poke_copy(void *addr, const void *opcode, size_t len)
2646{
2647 mutex_lock(&text_mutex);
2648 addr = text_poke_copy_locked(addr, opcode, len, false);
aadd1b67
SL
2649 mutex_unlock(&text_mutex);
2650 return addr;
2651}
2652
2653/**
2654 * text_poke_set - memset into (an unused part of) RX memory
2655 * @addr: address to modify
2656 * @c: the byte to fill the area with
2657 * @len: length to copy, could be more than 2x PAGE_SIZE
2658 *
2659 * This is useful to overwrite unused regions of RX memory with illegal
2660 * instructions.
2661 */
2662void *text_poke_set(void *addr, int c, size_t len)
2663{
2664 unsigned long start = (unsigned long)addr;
2665 size_t patched = 0;
2666
2667 if (WARN_ON_ONCE(core_kernel_text(start)))
2668 return NULL;
2669
2670 mutex_lock(&text_mutex);
2671 while (patched < len) {
2672 unsigned long ptr = start + patched;
2673 size_t s;
2674
2675 s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
2676
2677 __text_poke(text_poke_memset, (void *)ptr, (void *)&c, s);
0e06b403
SL
2678 patched += s;
2679 }
2680 mutex_unlock(&text_mutex);
2681 return addr;
2682}
2683
fd4363ff
JK
2684static void do_sync_core(void *info)
2685{
2686 sync_core();
2687}
2688
6e4955a9 2689void smp_text_poke_sync_each_cpu(void)
5c02ece8
PZ
2690{
2691 on_each_cpu(do_sync_core, NULL, 1);
2692}
2693
ac0ee0a9
PZ
2694/*
2695 * NOTE: crazy scheme to allow patching Jcc.d32 but not increase the size of
2696 * this thing. When len == 6 everything is prefixed with 0x0f and we map
2697 * opcode to Jcc.d8, using len to distinguish.
2698 */
a81d43c4 2699struct smp_text_poke_loc {
26c44b77
PZ
2700 /* addr := _stext + rel_addr */
2701 s32 rel_addr;
2702 s32 disp;
2703 u8 len;
18cbc8be 2704 u8 opcode;
3c8454df 2705 const u8 text[TEXT_POKE_MAX_OPCODE_SIZE];
23a76739 2706 /* see smp_text_poke_batch_finish() */
d769811c 2707 u8 old;
18cbc8be
PZ
2708};
2709
8036fbe5 2710#define TEXT_POKE_ARRAY_MAX (PAGE_SIZE / sizeof(struct smp_text_poke_loc))
6e7dc03a
IM
2711
2712static struct smp_text_poke_array {
8036fbe5 2713 struct smp_text_poke_loc vec[TEXT_POKE_ARRAY_MAX];
6e4955a9 2714 int nr_entries;
6e7dc03a
IM
2715} text_poke_array;
2716
0494b16b
IM
2717static DEFINE_PER_CPU(atomic_t, text_poke_array_refs);
2718
4f953471
IM
2719/*
2720 * These four __always_inline annotations imply noinstr, necessary
2721 * due to smp_text_poke_int3_handler() being noinstr:
2722 */
2723
b6a25841 2724static __always_inline bool try_get_text_poke_array(void)
1f676247 2725{
28fb7909 2726 atomic_t *refs = this_cpu_ptr(&text_poke_array_refs);
1f676247 2727
4334336e 2728 if (!raw_atomic_inc_not_zero(refs))
b6a25841 2729 return false;
1f676247 2730
b6a25841 2731 return true;
1f676247
PZ
2732}
2733
3916eec5 2734static __always_inline void put_text_poke_array(void)
1f676247 2735{
28fb7909 2736 atomic_t *refs = this_cpu_ptr(&text_poke_array_refs);
efd608fa 2737
1f676247 2738 smp_mb__before_atomic();
4334336e 2739 raw_atomic_dec(refs);
1f676247 2740}
c0213b0a 2741
22b96623 2742static __always_inline void *text_poke_addr(const struct smp_text_poke_loc *tpl)
4531ef6a 2743{
22b96623 2744 return _stext + tpl->rel_addr;
4531ef6a
PZ
2745}
2746
3e6f4757 2747static __always_inline int patch_cmp(const void *tpl_a, const void *tpl_b)
c0213b0a 2748{
3e6f4757 2749 if (tpl_a < text_poke_addr(tpl_b))
c0213b0a 2750 return -1;
3e6f4757 2751 if (tpl_a > text_poke_addr(tpl_b))
c0213b0a
DBO
2752 return 1;
2753 return 0;
2754}
fd4363ff 2755
5236b6a0 2756noinstr int smp_text_poke_int3_handler(struct pt_regs *regs)
fd4363ff 2757{
22b96623 2758 struct smp_text_poke_loc *tpl;
26c44b77 2759 int ret = 0;
c0213b0a 2760 void *ip;
1f676247
PZ
2761
2762 if (user_mode(regs))
2763 return 0;
c0213b0a 2764
01651324
PZ
2765 /*
2766 * Having observed our INT3 instruction, we now must observe
0494b16b 2767 * text_poke_array with non-zero refcount:
01651324 2768 *
28fb7909 2769 * text_poke_array_refs = 1 INT3
4334336e 2770 * WMB RMB
28fb7909 2771 * write INT3 if (text_poke_array_refs != 0)
01651324 2772 */
fd4363ff
JK
2773 smp_rmb();
2774
b6a25841 2775 if (!try_get_text_poke_array())
17f41571 2776 return 0;
476ad071 2777
c0213b0a 2778 /*
23a76739 2779 * Discount the INT3. See smp_text_poke_batch_finish().
c0213b0a 2780 */
c3d6324f 2781 ip = (void *) regs->ip - INT3_INSN_SIZE;
c0213b0a
DBO
2782
2783 /*
2784 * Skip the binary search if there is a single member in the vector.
2785 */
8e35752f 2786 if (unlikely(text_poke_array.nr_entries > 1)) {
22b96623 2787 tpl = __inline_bsearch(ip, text_poke_array.vec, text_poke_array.nr_entries,
a81d43c4 2788 sizeof(struct smp_text_poke_loc),
f64366ef 2789 patch_cmp);
22b96623 2790 if (!tpl)
1f676247 2791 goto out_put;
c0213b0a 2792 } else {
22b96623
IM
2793 tpl = text_poke_array.vec;
2794 if (text_poke_addr(tpl) != ip)
1f676247 2795 goto out_put;
c0213b0a
DBO
2796 }
2797
22b96623 2798 ip += tpl->len;
c3d6324f 2799
22b96623 2800 switch (tpl->opcode) {
c3d6324f
PZ
2801 case INT3_INSN_OPCODE:
2802 /*
2803 * Someone poked an explicit INT3, they'll want to handle it,
2804 * do not consume.
2805 */
1f676247 2806 goto out_put;
c3d6324f 2807
c43a43e4
PZ
2808 case RET_INSN_OPCODE:
2809 int3_emulate_ret(regs);
2810 break;
2811
c3d6324f 2812 case CALL_INSN_OPCODE:
22b96623 2813 int3_emulate_call(regs, (long)ip + tpl->disp);
c3d6324f
PZ
2814 break;
2815
2816 case JMP32_INSN_OPCODE:
2817 case JMP8_INSN_OPCODE:
22b96623 2818 int3_emulate_jmp(regs, (long)ip + tpl->disp);
c3d6324f
PZ
2819 break;
2820
ac0ee0a9 2821 case 0x70 ... 0x7f: /* Jcc */
22b96623 2822 int3_emulate_jcc(regs, tpl->opcode & 0xf, (long)ip, tpl->disp);
ac0ee0a9
PZ
2823 break;
2824
c3d6324f
PZ
2825 default:
2826 BUG();
2827 }
17f41571 2828
1f676247
PZ
2829 ret = 1;
2830
2831out_put:
3916eec5 2832 put_text_poke_array();
1f676247 2833 return ret;
fd4363ff 2834}
17f41571 2835
fd4363ff 2836/**
23a76739 2837 * smp_text_poke_batch_finish() -- update instructions on live kernel on SMP
fd4363ff 2838 *
dac0d754
IM
2839 * Input state:
2840 * text_poke_array.vec: vector of instructions to patch
2841 * text_poke_array.nr_entries: number of entries in the vector
2842 *
2843 * Modify multi-byte instructions by using INT3 breakpoints on SMP.
2844 * We completely avoid using stop_machine() here, and achieve the
2845 * synchronization using INT3 breakpoints and SMP cross-calls.
fd4363ff
JK
2846 *
2847 * The way it is done:
c3d6324f 2848 * - For each entry in the vector:
dac0d754
IM
2849 * - add an INT3 trap to the address that will be patched
2850 * - SMP sync all CPUs
c0213b0a
DBO
2851 * - For each entry in the vector:
2852 * - update all but the first byte of the patched range
dac0d754 2853 * - SMP sync all CPUs
c0213b0a 2854 * - For each entry in the vector:
dac0d754 2855 * - replace the first byte (INT3) by the first byte of the
c0213b0a 2856 * replacing opcode
dac0d754 2857 * - SMP sync all CPUs
fd4363ff 2858 */
23a76739 2859void smp_text_poke_batch_finish(void)
fd4363ff 2860{
c3d6324f 2861 unsigned char int3 = INT3_INSN_OPCODE;
c0213b0a 2862 unsigned int i;
c3d6324f 2863 int do_sync;
9222f606 2864
23a76739
NB
2865 if (!text_poke_array.nr_entries)
2866 return;
2867
9222f606
JK
2868 lockdep_assert_held(&text_mutex);
2869
efd608fa 2870 /*
46f3d9d3 2871 * Corresponds to the implicit memory barrier in try_get_text_poke_array() to
0494b16b 2872 * ensure reading a non-zero refcount provides up to date text_poke_array data.
efd608fa 2873 */
4334336e 2874 for_each_possible_cpu(i)
28fb7909 2875 atomic_set_release(per_cpu_ptr(&text_poke_array_refs, i), 1);
c0213b0a 2876
9350a629
SRG
2877 /*
2878 * Function tracing can enable thousands of places that need to be
2879 * updated. This can take quite some time, and with full kernel debugging
2880 * enabled, this could cause the softlockup watchdog to trigger.
2881 * This function gets called every 256 entries added to be patched.
2882 * Call cond_resched() here to make sure that other tasks can get scheduled
2883 * while processing all the functions being patched.
2884 */
2885 cond_resched();
2886
fd4363ff 2887 /*
dac0d754 2888 * Corresponding read barrier in INT3 notifier for making sure the
74e8e2bf 2889 * text_poke_array.nr_entries and handler are correctly ordered wrt. patching.
fd4363ff
JK
2890 */
2891 smp_wmb();
2892
c0213b0a 2893 /*
dac0d754 2894 * First step: add a INT3 trap to the address that will be patched.
c0213b0a 2895 */
74e8e2bf
IM
2896 for (i = 0; i < text_poke_array.nr_entries; i++) {
2897 text_poke_array.vec[i].old = *(u8 *)text_poke_addr(&text_poke_array.vec[i]);
2898 text_poke(text_poke_addr(&text_poke_array.vec[i]), &int3, INT3_INSN_SIZE);
d769811c 2899 }
fd4363ff 2900
6e4955a9 2901 smp_text_poke_sync_each_cpu();
fd4363ff 2902
c0213b0a
DBO
2903 /*
2904 * Second step: update all but the first byte of the patched range.
2905 */
74e8e2bf 2906 for (do_sync = 0, i = 0; i < text_poke_array.nr_entries; i++) {
3c8454df
IM
2907 u8 old[TEXT_POKE_MAX_OPCODE_SIZE+1] = { text_poke_array.vec[i].old, };
2908 u8 _new[TEXT_POKE_MAX_OPCODE_SIZE+1];
74e8e2bf
IM
2909 const u8 *new = text_poke_array.vec[i].text;
2910 int len = text_poke_array.vec[i].len;
97e6c977 2911
76ffa720 2912 if (len - INT3_INSN_SIZE > 0) {
d769811c 2913 memcpy(old + INT3_INSN_SIZE,
74e8e2bf 2914 text_poke_addr(&text_poke_array.vec[i]) + INT3_INSN_SIZE,
d769811c 2915 len - INT3_INSN_SIZE);
ac0ee0a9
PZ
2916
2917 if (len == 6) {
2918 _new[0] = 0x0f;
2919 memcpy(_new + 1, new, 5);
2920 new = _new;
2921 }
2922
74e8e2bf 2923 text_poke(text_poke_addr(&text_poke_array.vec[i]) + INT3_INSN_SIZE,
ac0ee0a9 2924 new + INT3_INSN_SIZE,
76ffa720 2925 len - INT3_INSN_SIZE);
ac0ee0a9 2926
c3d6324f 2927 do_sync++;
c0213b0a 2928 }
d769811c
AH
2929
2930 /*
2931 * Emit a perf event to record the text poke, primarily to
2932 * support Intel PT decoding which must walk the executable code
2933 * to reconstruct the trace. The flow up to here is:
2934 * - write INT3 byte
2935 * - IPI-SYNC
2936 * - write instruction tail
2937 * At this point the actual control flow will be through the
2938 * INT3 and handler and not hit the old or new instruction.
2939 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
2940 * can still be decoded. Subsequently:
2941 * - emit RECORD_TEXT_POKE with the new instruction
2942 * - IPI-SYNC
2943 * - write first byte
2944 * - IPI-SYNC
2945 * So before the text poke event timestamp, the decoder will see
2946 * either the old instruction flow or FUP/TIP of INT3. After the
2947 * text poke event timestamp, the decoder will see either the
2948 * new instruction flow or FUP/TIP of INT3. Thus decoders can
2949 * use the timestamp as the point at which to modify the
2950 * executable code.
2951 * The old instruction is recorded so that the event can be
2952 * processed forwards or backwards.
2953 */
74e8e2bf 2954 perf_event_text_poke(text_poke_addr(&text_poke_array.vec[i]), old, len, new, len);
c0213b0a
DBO
2955 }
2956
c3d6324f 2957 if (do_sync) {
fd4363ff
JK
2958 /*
2959 * According to Intel, this core syncing is very likely
2960 * not necessary and we'd be safe even without it. But
2961 * better safe than sorry (plus there's not only Intel).
2962 */
6e4955a9 2963 smp_text_poke_sync_each_cpu();
fd4363ff
JK
2964 }
2965
c0213b0a 2966 /*
dac0d754 2967 * Third step: replace the first byte (INT3) by the first byte of the
c0213b0a
DBO
2968 * replacing opcode.
2969 */
74e8e2bf
IM
2970 for (do_sync = 0, i = 0; i < text_poke_array.nr_entries; i++) {
2971 u8 byte = text_poke_array.vec[i].text[0];
ac0ee0a9 2972
74e8e2bf 2973 if (text_poke_array.vec[i].len == 6)
ac0ee0a9
PZ
2974 byte = 0x0f;
2975
2976 if (byte == INT3_INSN_OPCODE)
c3d6324f
PZ
2977 continue;
2978
74e8e2bf 2979 text_poke(text_poke_addr(&text_poke_array.vec[i]), &byte, INT3_INSN_SIZE);
c3d6324f
PZ
2980 do_sync++;
2981 }
2982
2983 if (do_sync)
6e4955a9 2984 smp_text_poke_sync_each_cpu();
fd4363ff 2985
01651324 2986 /*
efd608fa 2987 * Remove and wait for refs to be zero.
d60e4b24
PZ
2988 *
2989 * Notably, if after step-3 above the INT3 got removed, then the
6e4955a9 2990 * smp_text_poke_sync_each_cpu() will have serialized against any running INT3
d60e4b24
PZ
2991 * handlers and the below spin-wait will not happen.
2992 *
2993 * IOW. unless the replacement instruction is INT3, this case goes
2994 * unused.
01651324 2995 */
4334336e 2996 for_each_possible_cpu(i) {
28fb7909 2997 atomic_t *refs = per_cpu_ptr(&text_poke_array_refs, i);
4334336e
ED
2998
2999 if (unlikely(!atomic_dec_and_test(refs)))
3000 atomic_cond_read_acquire(refs, !VAL);
3001 }
7fbadb50
IM
3002
3003 /* They are all completed: */
3004 text_poke_array.nr_entries = 0;
fd4363ff
JK
3005}
3006
0e351aec 3007static void __smp_text_poke_batch_add(void *addr, const void *opcode, size_t len, const void *emulate)
c3d6324f 3008{
22b96623 3009 struct smp_text_poke_loc *tpl;
c3d6324f 3010 struct insn insn;
ac0ee0a9 3011 int ret, i = 0;
c3d6324f 3012
22b96623 3013 tpl = &text_poke_array.vec[text_poke_array.nr_entries++];
0e351aec 3014
ac0ee0a9
PZ
3015 if (len == 6)
3016 i = 1;
22b96623 3017 memcpy((void *)tpl->text, opcode+i, len-i);
c3d6324f
PZ
3018 if (!emulate)
3019 emulate = opcode;
3020
52fa82c2 3021 ret = insn_decode_kernel(&insn, emulate);
63c66cde 3022 BUG_ON(ret < 0);
c3d6324f 3023
22b96623
IM
3024 tpl->rel_addr = addr - (void *)_stext;
3025 tpl->len = len;
3026 tpl->opcode = insn.opcode.bytes[0];
c3d6324f 3027
ac0ee0a9
PZ
3028 if (is_jcc32(&insn)) {
3029 /*
3030 * Map Jcc.d32 onto Jcc.d8 and use len to distinguish.
3031 */
22b96623 3032 tpl->opcode = insn.opcode.bytes[1] - 0x10;
ac0ee0a9
PZ
3033 }
3034
22b96623 3035 switch (tpl->opcode) {
26c44b77
PZ
3036 case RET_INSN_OPCODE:
3037 case JMP32_INSN_OPCODE:
3038 case JMP8_INSN_OPCODE:
3039 /*
3040 * Control flow instructions without implied execution of the
3041 * next instruction can be padded with INT3.
3042 */
3043 for (i = insn.length; i < len; i++)
22b96623 3044 BUG_ON(tpl->text[i] != INT3_INSN_OPCODE);
26c44b77
PZ
3045 break;
3046
3047 default:
3048 BUG_ON(len != insn.length);
64267734 3049 }
26c44b77 3050
22b96623 3051 switch (tpl->opcode) {
c3d6324f 3052 case INT3_INSN_OPCODE:
c43a43e4 3053 case RET_INSN_OPCODE:
c3d6324f
PZ
3054 break;
3055
3056 case CALL_INSN_OPCODE:
3057 case JMP32_INSN_OPCODE:
3058 case JMP8_INSN_OPCODE:
ac0ee0a9 3059 case 0x70 ... 0x7f: /* Jcc */
22b96623 3060 tpl->disp = insn.immediate.value;
c3d6324f
PZ
3061 break;
3062
3063 default: /* assume NOP */
3064 switch (len) {
3065 case 2: /* NOP2 -- emulate as JMP8+0 */
a89dfde3 3066 BUG_ON(memcmp(emulate, x86_nops[len], len));
22b96623
IM
3067 tpl->opcode = JMP8_INSN_OPCODE;
3068 tpl->disp = 0;
c3d6324f
PZ
3069 break;
3070
3071 case 5: /* NOP5 -- emulate as JMP32+0 */
a89dfde3 3072 BUG_ON(memcmp(emulate, x86_nops[len], len));
22b96623
IM
3073 tpl->opcode = JMP32_INSN_OPCODE;
3074 tpl->disp = 0;
c3d6324f
PZ
3075 break;
3076
3077 default: /* unknown instruction */
3078 BUG();
3079 }
3080 break;
3081 }
3082}
3083
18cbc8be 3084/*
6e7dc03a 3085 * We hard rely on the text_poke_array.vec being ordered; ensure this is so by flushing
18cbc8be
PZ
3086 * early if needed.
3087 */
2d0cf10a 3088static bool text_poke_addr_ordered(void *addr)
18cbc8be 3089{
eaa24c91
IM
3090 WARN_ON_ONCE(!addr);
3091
6e7dc03a 3092 if (!text_poke_array.nr_entries)
2d0cf10a 3093 return true;
18cbc8be 3094
2d0cf10a
IM
3095 /*
3096 * If the last current entry's address is higher than the
3097 * new entry's address we'd like to add, then ordering
3098 * is violated and we must first flush all pending patching
3099 * requests:
3100 */
0e67e587 3101 if (text_poke_addr(text_poke_array.vec + text_poke_array.nr_entries-1) > addr)
2d0cf10a 3102 return false;
18cbc8be 3103
2d0cf10a 3104 return true;
18cbc8be
PZ
3105}
3106
cca34739
IM
3107/**
3108 * smp_text_poke_batch_add() -- update instruction on live kernel on SMP, batched
3109 * @addr: address to patch
3110 * @opcode: opcode of new instruction
3111 * @len: length to copy
3112 * @emulate: instruction to be emulated
3113 *
3114 * Add a new instruction to the current queue of to-be-patched instructions
3115 * the kernel maintains. The patching request will not be executed immediately,
3116 * but becomes part of an array of patching requests, optimized for batched
3117 * execution. All pending patching requests will be executed on the next
3118 * smp_text_poke_batch_finish() call.
3119 */
732c7c33 3120void __ref smp_text_poke_batch_add(void *addr, const void *opcode, size_t len, const void *emulate)
18cbc8be 3121{
2c373ca0 3122 if (text_poke_array.nr_entries == TEXT_POKE_ARRAY_MAX || !text_poke_addr_ordered(addr))
23a76739 3123 smp_text_poke_batch_finish();
0e351aec 3124 __smp_text_poke_batch_add(addr, opcode, len, emulate);
18cbc8be
PZ
3125}
3126
c0213b0a 3127/**
9647ce46 3128 * smp_text_poke_single() -- update instruction on live kernel on SMP immediately
c0213b0a
DBO
3129 * @addr: address to patch
3130 * @opcode: opcode of new instruction
3131 * @len: length to copy
72ebb5ff 3132 * @emulate: instruction to be emulated
c0213b0a
DBO
3133 *
3134 * Update a single instruction with the vector in the stack, avoiding
3135 * dynamically allocated memory. This function should be used when it is
9647ce46
IM
3136 * not possible to allocate memory for a vector. The single instruction
3137 * is patched in immediately.
c0213b0a 3138 */
9586ae48 3139void __ref smp_text_poke_single(void *addr, const void *opcode, size_t len, const void *emulate)
c0213b0a 3140{
2aebf5ee 3141 smp_text_poke_batch_add(addr, opcode, len, emulate);
c8976ade 3142 smp_text_poke_batch_finish();
c0213b0a 3143}