]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - arch/x86/kernel/alternative.c
x86/alternative: Try inline spectre_v2=retpoline,amd
[mirror_ubuntu-jammy-kernel.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
9a0b5817 4#include <linux/module.h>
f6a57033 5#include <linux/sched.h>
d769811c 6#include <linux/perf_event.h>
2f1dafe5 7#include <linux/mutex.h>
9a0b5817 8#include <linux/list.h>
8b5a10fc 9#include <linux/stringify.h>
ca15ca40 10#include <linux/highmem.h>
19d36ccd
AK
11#include <linux/mm.h>
12#include <linux/vmalloc.h>
3945dab4 13#include <linux/memory.h>
3d55cc8a 14#include <linux/stop_machine.h>
5a0e3ad6 15#include <linux/slab.h>
fd4363ff 16#include <linux/kdebug.h>
c13324a5 17#include <linux/kprobes.h>
b3fd8e83 18#include <linux/mmu_context.h>
c0213b0a 19#include <linux/bsearch.h>
9998a983 20#include <linux/sync_core.h>
35de5b06 21#include <asm/text-patching.h>
9a0b5817
GH
22#include <asm/alternative.h>
23#include <asm/sections.h>
8f4e956b
AK
24#include <asm/mce.h>
25#include <asm/nmi.h>
e587cadd 26#include <asm/cacheflush.h>
78ff7fae 27#include <asm/tlbflush.h>
3a125539 28#include <asm/insn.h>
e587cadd 29#include <asm/io.h>
78ff7fae 30#include <asm/fixmap.h>
4e629211 31#include <asm/paravirt.h>
81211f23 32#include <asm/asm-prototypes.h>
9a0b5817 33
5e907bb0
IM
34int __read_mostly alternatives_patched;
35
36EXPORT_SYMBOL_GPL(alternatives_patched);
37
ab144f5e
AK
38#define MAX_PATCH_LEN (255-1)
39
8b5a10fc 40static int __initdata_or_module debug_alternative;
b7fb4af0 41
d167a518
GH
42static int __init debug_alt(char *str)
43{
44 debug_alternative = 1;
45 return 1;
46}
d167a518
GH
47__setup("debug-alternative", debug_alt);
48
09488165
JB
49static int noreplace_smp;
50
b7fb4af0
JF
51static int __init setup_noreplace_smp(char *str)
52{
53 noreplace_smp = 1;
54 return 1;
55}
56__setup("noreplace-smp", setup_noreplace_smp);
57
db477a33
BP
58#define DPRINTK(fmt, args...) \
59do { \
60 if (debug_alternative) \
1b2e335e 61 printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args); \
c767a54b 62} while (0)
d167a518 63
48c7a250
BP
64#define DUMP_BYTES(buf, len, fmt, args...) \
65do { \
66 if (unlikely(debug_alternative)) { \
67 int j; \
68 \
69 if (!(len)) \
70 break; \
71 \
1b2e335e 72 printk(KERN_DEBUG pr_fmt(fmt), ##args); \
48c7a250
BP
73 for (j = 0; j < (len) - 1; j++) \
74 printk(KERN_CONT "%02hhx ", buf[j]); \
75 printk(KERN_CONT "%02hhx\n", buf[j]); \
76 } \
77} while (0)
78
64e1f587 79static const unsigned char x86nops[] =
dc326fca 80{
a89dfde3
PZ
81 BYTES_NOP1,
82 BYTES_NOP2,
83 BYTES_NOP3,
84 BYTES_NOP4,
85 BYTES_NOP5,
86 BYTES_NOP6,
87 BYTES_NOP7,
88 BYTES_NOP8,
9a0b5817 89};
d167a518 90
a89dfde3 91const unsigned char * const x86_nops[ASM_NOP_MAX+1] =
dc326fca 92{
32c464f5 93 NULL,
a89dfde3
PZ
94 x86nops,
95 x86nops + 1,
96 x86nops + 1 + 2,
97 x86nops + 1 + 2 + 3,
98 x86nops + 1 + 2 + 3 + 4,
99 x86nops + 1 + 2 + 3 + 4 + 5,
100 x86nops + 1 + 2 + 3 + 4 + 5 + 6,
101 x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
32c464f5 102};
9a0b5817 103
ab144f5e 104/* Use this to add nops to a buffer, then text_poke the whole buffer. */
8b5a10fc 105static void __init_or_module add_nops(void *insns, unsigned int len)
139ec7c4 106{
139ec7c4
RR
107 while (len > 0) {
108 unsigned int noplen = len;
109 if (noplen > ASM_NOP_MAX)
110 noplen = ASM_NOP_MAX;
a89dfde3 111 memcpy(insns, x86_nops[noplen], noplen);
139ec7c4
RR
112 insns += noplen;
113 len -= noplen;
114 }
115}
116
81211f23 117extern s32 __retpoline_sites[], __retpoline_sites_end[];
d167a518 118extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
5967ed87 119extern s32 __smp_locks[], __smp_locks_end[];
0a203df5 120void text_poke_early(void *addr, const void *opcode, size_t len);
d167a518 121
48c7a250
BP
122/*
123 * Are we looking at a near JMP with a 1 or 4-byte displacement.
124 */
125static inline bool is_jmp(const u8 opcode)
126{
127 return opcode == 0xeb || opcode == 0xe9;
128}
129
130static void __init_or_module
1fc654cf 131recompute_jump(struct alt_instr *a, u8 *orig_insn, u8 *repl_insn, u8 *insn_buff)
48c7a250
BP
132{
133 u8 *next_rip, *tgt_rip;
134 s32 n_dspl, o_dspl;
135 int repl_len;
136
137 if (a->replacementlen != 5)
138 return;
139
1fc654cf 140 o_dspl = *(s32 *)(insn_buff + 1);
48c7a250
BP
141
142 /* next_rip of the replacement JMP */
143 next_rip = repl_insn + a->replacementlen;
144 /* target rip of the replacement JMP */
145 tgt_rip = next_rip + o_dspl;
146 n_dspl = tgt_rip - orig_insn;
147
0e6c16c6 148 DPRINTK("target RIP: %px, new_displ: 0x%x", tgt_rip, n_dspl);
48c7a250
BP
149
150 if (tgt_rip - orig_insn >= 0) {
151 if (n_dspl - 2 <= 127)
152 goto two_byte_jmp;
153 else
154 goto five_byte_jmp;
155 /* negative offset */
156 } else {
157 if (((n_dspl - 2) & 0xff) == (n_dspl - 2))
158 goto two_byte_jmp;
159 else
160 goto five_byte_jmp;
161 }
162
163two_byte_jmp:
164 n_dspl -= 2;
165
1fc654cf
IM
166 insn_buff[0] = 0xeb;
167 insn_buff[1] = (s8)n_dspl;
168 add_nops(insn_buff + 2, 3);
48c7a250
BP
169
170 repl_len = 2;
171 goto done;
172
173five_byte_jmp:
174 n_dspl -= 5;
175
1fc654cf
IM
176 insn_buff[0] = 0xe9;
177 *(s32 *)&insn_buff[1] = n_dspl;
48c7a250
BP
178
179 repl_len = 5;
180
181done:
182
183 DPRINTK("final displ: 0x%08x, JMP 0x%lx",
184 n_dspl, (unsigned long)orig_insn + n_dspl + repl_len);
185}
186
2b31e8ed
BP
187/*
188 * optimize_nops_range() - Optimize a sequence of single byte NOPs (0x90)
189 *
190 * @instr: instruction byte stream
191 * @instrlen: length of the above
192 * @off: offset within @instr where the first NOP has been detected
193 *
194 * Return: number of NOPs found (and replaced).
195 */
196static __always_inline int optimize_nops_range(u8 *instr, u8 instrlen, int off)
197{
198 unsigned long flags;
199 int i = off, nnops;
200
201 while (i < instrlen) {
202 if (instr[i] != 0x90)
203 break;
204
205 i++;
206 }
207
208 nnops = i - off;
209
210 if (nnops <= 1)
211 return nnops;
212
213 local_irq_save(flags);
214 add_nops(instr + off, nnops);
215 local_irq_restore(flags);
216
217 DUMP_BYTES(instr, instrlen, "%px: [%d:%d) optimized NOPs: ", instr, off, i);
218
219 return nnops;
220}
221
34bfab0e
BP
222/*
223 * "noinline" to cause control flow change and thus invalidate I$ and
224 * cause refetch after modification.
225 */
81211f23 226static void __init_or_module noinline optimize_nops(u8 *instr, size_t len)
4fd4b6e5 227{
23c1ad53 228 struct insn insn;
2b31e8ed 229 int i = 0;
66c117d7 230
23c1ad53 231 /*
2b31e8ed
BP
232 * Jump over the non-NOP insns and optimize single-byte NOPs into bigger
233 * ones.
23c1ad53
PZ
234 */
235 for (;;) {
236 if (insn_decode_kernel(&insn, &instr[i]))
237 return;
238
2b31e8ed
BP
239 /*
240 * See if this and any potentially following NOPs can be
241 * optimized.
242 */
23c1ad53 243 if (insn.length == 1 && insn.opcode.bytes[0] == 0x90)
81211f23 244 i += optimize_nops_range(instr, len, i);
2b31e8ed
BP
245 else
246 i += insn.length;
23c1ad53 247
81211f23 248 if (i >= len)
612e8e93
BP
249 return;
250 }
4fd4b6e5
BP
251}
252
db477a33
BP
253/*
254 * Replace instructions with better alternatives for this CPU type. This runs
255 * before SMP is initialized to avoid SMP problems with self modifying code.
256 * This implies that asymmetric systems where APs have less capabilities than
257 * the boot processor are not handled. Tough. Make sure you disable such
258 * features by hand.
34bfab0e
BP
259 *
260 * Marked "noinline" to cause control flow change and thus insn cache
261 * to refetch changed I$ lines.
db477a33 262 */
34bfab0e
BP
263void __init_or_module noinline apply_alternatives(struct alt_instr *start,
264 struct alt_instr *end)
9a0b5817 265{
9a0b5817 266 struct alt_instr *a;
59e97e4d 267 u8 *instr, *replacement;
1fc654cf 268 u8 insn_buff[MAX_PATCH_LEN];
9a0b5817 269
0e6c16c6 270 DPRINTK("alt table %px, -> %px", start, end);
50973133
FY
271 /*
272 * The scan order should be from start to end. A later scanned
db477a33 273 * alternative code can overwrite previously scanned alternative code.
50973133
FY
274 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
275 * patch code.
276 *
277 * So be careful if you want to change the scan order to any other
278 * order.
279 */
9a0b5817 280 for (a = start; a < end; a++) {
1fc654cf 281 int insn_buff_sz = 0;
dda7bb76
JG
282 /* Mask away "NOT" flag bit for feature to test. */
283 u16 feature = a->cpuid & ~ALTINSTR_FLAG_INV;
48c7a250 284
59e97e4d
AL
285 instr = (u8 *)&a->instr_offset + a->instr_offset;
286 replacement = (u8 *)&a->repl_offset + a->repl_offset;
1fc654cf 287 BUG_ON(a->instrlen > sizeof(insn_buff));
dda7bb76
JG
288 BUG_ON(feature >= (NCAPINTS + NBUGINTS) * 32);
289
290 /*
291 * Patch if either:
292 * - feature is present
293 * - feature not present but ALTINSTR_FLAG_INV is set to mean,
294 * patch if feature is *NOT* present.
295 */
23c1ad53
PZ
296 if (!boot_cpu_has(feature) == !(a->cpuid & ALTINSTR_FLAG_INV))
297 goto next;
59e97e4d 298
23c1ad53 299 DPRINTK("feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)",
dda7bb76
JG
300 (a->cpuid & ALTINSTR_FLAG_INV) ? "!" : "",
301 feature >> 5,
302 feature & 0x1f,
c1d4e419 303 instr, instr, a->instrlen,
23c1ad53 304 replacement, a->replacementlen);
db477a33 305
7ee0e638
BP
306 DUMP_BYTES(instr, a->instrlen, "%px: old_insn: ", instr);
307 DUMP_BYTES(replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
48c7a250 308
1fc654cf
IM
309 memcpy(insn_buff, replacement, a->replacementlen);
310 insn_buff_sz = a->replacementlen;
59e97e4d 311
fc152d22
MJ
312 /*
313 * 0xe8 is a relative jump; fix the offset.
314 *
315 * Instruction length is checked before the opcode to avoid
316 * accessing uninitialized bytes for zero-length replacements.
317 */
1fc654cf
IM
318 if (a->replacementlen == 5 && *insn_buff == 0xe8) {
319 *(s32 *)(insn_buff + 1) += replacement - instr;
48c7a250 320 DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
1fc654cf
IM
321 *(s32 *)(insn_buff + 1),
322 (unsigned long)instr + *(s32 *)(insn_buff + 1) + 5);
db477a33 323 }
59e97e4d 324
48c7a250 325 if (a->replacementlen && is_jmp(replacement[0]))
1fc654cf 326 recompute_jump(a, instr, replacement, insn_buff);
48c7a250 327
23c1ad53
PZ
328 for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
329 insn_buff[insn_buff_sz] = 0x90;
330
1fc654cf 331 DUMP_BYTES(insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
59e97e4d 332
1fc654cf 333 text_poke_early(instr, insn_buff, insn_buff_sz);
23c1ad53
PZ
334
335next:
81211f23 336 optimize_nops(instr, a->instrlen);
9a0b5817
GH
337 }
338}
339
81211f23
PZ
340#if defined(CONFIG_RETPOLINE) && defined(CONFIG_STACK_VALIDATION)
341
342/*
343 * CALL/JMP *%\reg
344 */
345static int emit_indirect(int op, int reg, u8 *bytes)
346{
347 int i = 0;
348 u8 modrm;
349
350 switch (op) {
351 case CALL_INSN_OPCODE:
352 modrm = 0x10; /* Reg = 2; CALL r/m */
353 break;
354
355 case JMP32_INSN_OPCODE:
356 modrm = 0x20; /* Reg = 4; JMP r/m */
357 break;
358
359 default:
360 WARN_ON_ONCE(1);
361 return -1;
362 }
363
364 if (reg >= 8) {
365 bytes[i++] = 0x41; /* REX.B prefix */
366 reg -= 8;
367 }
368
369 modrm |= 0xc0; /* Mod = 3 */
370 modrm += reg;
371
372 bytes[i++] = 0xff; /* opcode */
373 bytes[i++] = modrm;
374
375 return i;
376}
377
378/*
379 * Rewrite the compiler generated retpoline thunk calls.
380 *
381 * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
382 * indirect instructions, avoiding the extra indirection.
383 *
384 * For example, convert:
385 *
386 * CALL __x86_indirect_thunk_\reg
387 *
388 * into:
389 *
390 * CALL *%\reg
391 *
bbc7848b 392 * It also tries to inline spectre_v2=retpoline,amd when size permits.
81211f23
PZ
393 */
394static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
395{
396 retpoline_thunk_t *target;
d97c5899
PZ
397 int reg, ret, i = 0;
398 u8 op, cc;
81211f23
PZ
399
400 target = addr + insn->length + insn->immediate.value;
401 reg = target - __x86_indirect_thunk_array;
402
403 if (WARN_ON_ONCE(reg & ~0xf))
404 return -1;
405
406 /* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
407 BUG_ON(reg == 4);
408
bbc7848b
PZ
409 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
410 !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE))
81211f23
PZ
411 return -1;
412
d97c5899
PZ
413 op = insn->opcode.bytes[0];
414
415 /*
416 * Convert:
417 *
418 * Jcc.d32 __x86_indirect_thunk_\reg
419 *
420 * into:
421 *
422 * Jncc.d8 1f
bbc7848b 423 * [ LFENCE ]
d97c5899 424 * JMP *%\reg
bbc7848b 425 * [ NOP ]
d97c5899
PZ
426 * 1:
427 */
428 /* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
429 if (op == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80) {
430 cc = insn->opcode.bytes[1] & 0xf;
431 cc ^= 1; /* invert condition */
432
433 bytes[i++] = 0x70 + cc; /* Jcc.d8 */
434 bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
435
436 /* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
437 op = JMP32_INSN_OPCODE;
438 }
439
bbc7848b
PZ
440 /*
441 * For RETPOLINE_AMD: prepend the indirect CALL/JMP with an LFENCE.
442 */
443 if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
444 bytes[i++] = 0x0f;
445 bytes[i++] = 0xae;
446 bytes[i++] = 0xe8; /* LFENCE */
447 }
448
d97c5899
PZ
449 ret = emit_indirect(op, reg, bytes + i);
450 if (ret < 0)
451 return ret;
452 i += ret;
81211f23
PZ
453
454 for (; i < insn->length;)
455 bytes[i++] = BYTES_NOP1;
456
457 return i;
458}
459
460/*
461 * Generated by 'objtool --retpoline'.
462 */
463void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
464{
465 s32 *s;
466
467 for (s = start; s < end; s++) {
468 void *addr = (void *)s + *s;
469 struct insn insn;
470 int len, ret;
471 u8 bytes[16];
472 u8 op1, op2;
473
474 ret = insn_decode_kernel(&insn, addr);
475 if (WARN_ON_ONCE(ret < 0))
476 continue;
477
478 op1 = insn.opcode.bytes[0];
479 op2 = insn.opcode.bytes[1];
480
481 switch (op1) {
482 case CALL_INSN_OPCODE:
483 case JMP32_INSN_OPCODE:
484 break;
485
d97c5899
PZ
486 case 0x0f: /* escape */
487 if (op2 >= 0x80 && op2 <= 0x8f)
488 break;
489 fallthrough;
81211f23
PZ
490 default:
491 WARN_ON_ONCE(1);
492 continue;
493 }
494
495 len = patch_retpoline(addr, &insn, bytes);
496 if (len == insn.length) {
497 optimize_nops(bytes, len);
498 text_poke_early(addr, bytes, len);
499 }
500 }
501}
502
503#else /* !RETPOLINES || !CONFIG_STACK_VALIDATION */
504
505void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
506
507#endif /* CONFIG_RETPOLINE && CONFIG_STACK_VALIDATION */
508
8ec4d41f 509#ifdef CONFIG_SMP
5967ed87
JB
510static void alternatives_smp_lock(const s32 *start, const s32 *end,
511 u8 *text, u8 *text_end)
9a0b5817 512{
5967ed87 513 const s32 *poff;
9a0b5817 514
5967ed87
JB
515 for (poff = start; poff < end; poff++) {
516 u8 *ptr = (u8 *)poff + *poff;
517
518 if (!*poff || ptr < text || ptr >= text_end)
9a0b5817 519 continue;
f88f07e0 520 /* turn DS segment override prefix into lock prefix */
d9c5841e
PA
521 if (*ptr == 0x3e)
522 text_poke(ptr, ((unsigned char []){0xf0}), 1);
4b8073e4 523 }
9a0b5817
GH
524}
525
5967ed87
JB
526static void alternatives_smp_unlock(const s32 *start, const s32 *end,
527 u8 *text, u8 *text_end)
9a0b5817 528{
5967ed87 529 const s32 *poff;
9a0b5817 530
5967ed87
JB
531 for (poff = start; poff < end; poff++) {
532 u8 *ptr = (u8 *)poff + *poff;
533
534 if (!*poff || ptr < text || ptr >= text_end)
9a0b5817 535 continue;
f88f07e0 536 /* turn lock prefix into DS segment override prefix */
d9c5841e
PA
537 if (*ptr == 0xf0)
538 text_poke(ptr, ((unsigned char []){0x3E}), 1);
4b8073e4 539 }
9a0b5817
GH
540}
541
542struct smp_alt_module {
543 /* what is this ??? */
544 struct module *mod;
545 char *name;
546
547 /* ptrs to lock prefixes */
5967ed87
JB
548 const s32 *locks;
549 const s32 *locks_end;
9a0b5817
GH
550
551 /* .text segment, needed to avoid patching init code ;) */
552 u8 *text;
553 u8 *text_end;
554
555 struct list_head next;
556};
557static LIST_HEAD(smp_alt_modules);
e846d139 558static bool uniproc_patched = false; /* protected by text_mutex */
9a0b5817 559
8b5a10fc
JB
560void __init_or_module alternatives_smp_module_add(struct module *mod,
561 char *name,
562 void *locks, void *locks_end,
563 void *text, void *text_end)
9a0b5817
GH
564{
565 struct smp_alt_module *smp;
9a0b5817 566
e846d139 567 mutex_lock(&text_mutex);
816afe4f
RR
568 if (!uniproc_patched)
569 goto unlock;
b7fb4af0 570
816afe4f
RR
571 if (num_possible_cpus() == 1)
572 /* Don't bother remembering, we'll never have to undo it. */
573 goto smp_unlock;
9a0b5817
GH
574
575 smp = kzalloc(sizeof(*smp), GFP_KERNEL);
576 if (NULL == smp)
816afe4f
RR
577 /* we'll run the (safe but slow) SMP code then ... */
578 goto unlock;
9a0b5817
GH
579
580 smp->mod = mod;
581 smp->name = name;
582 smp->locks = locks;
583 smp->locks_end = locks_end;
584 smp->text = text;
585 smp->text_end = text_end;
db477a33
BP
586 DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
587 smp->locks, smp->locks_end,
9a0b5817
GH
588 smp->text, smp->text_end, smp->name);
589
9a0b5817 590 list_add_tail(&smp->next, &smp_alt_modules);
816afe4f
RR
591smp_unlock:
592 alternatives_smp_unlock(locks, locks_end, text, text_end);
593unlock:
e846d139 594 mutex_unlock(&text_mutex);
9a0b5817
GH
595}
596
8b5a10fc 597void __init_or_module alternatives_smp_module_del(struct module *mod)
9a0b5817
GH
598{
599 struct smp_alt_module *item;
9a0b5817 600
e846d139 601 mutex_lock(&text_mutex);
9a0b5817
GH
602 list_for_each_entry(item, &smp_alt_modules, next) {
603 if (mod != item->mod)
604 continue;
605 list_del(&item->next);
9a0b5817 606 kfree(item);
816afe4f 607 break;
9a0b5817 608 }
e846d139 609 mutex_unlock(&text_mutex);
9a0b5817
GH
610}
611
816afe4f 612void alternatives_enable_smp(void)
9a0b5817
GH
613{
614 struct smp_alt_module *mod;
9a0b5817 615
816afe4f
RR
616 /* Why bother if there are no other CPUs? */
617 BUG_ON(num_possible_cpus() == 1);
9a0b5817 618
e846d139 619 mutex_lock(&text_mutex);
ca74a6f8 620
816afe4f 621 if (uniproc_patched) {
c767a54b 622 pr_info("switching to SMP code\n");
816afe4f 623 BUG_ON(num_online_cpus() != 1);
53756d37
JF
624 clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
625 clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
9a0b5817
GH
626 list_for_each_entry(mod, &smp_alt_modules, next)
627 alternatives_smp_lock(mod->locks, mod->locks_end,
628 mod->text, mod->text_end);
816afe4f 629 uniproc_patched = false;
9a0b5817 630 }
e846d139 631 mutex_unlock(&text_mutex);
9a0b5817
GH
632}
633
e846d139
ZC
634/*
635 * Return 1 if the address range is reserved for SMP-alternatives.
636 * Must hold text_mutex.
637 */
2cfa1978
MH
638int alternatives_text_reserved(void *start, void *end)
639{
640 struct smp_alt_module *mod;
5967ed87 641 const s32 *poff;
076dc4a6
MH
642 u8 *text_start = start;
643 u8 *text_end = end;
2cfa1978 644
e846d139
ZC
645 lockdep_assert_held(&text_mutex);
646
2cfa1978 647 list_for_each_entry(mod, &smp_alt_modules, next) {
076dc4a6 648 if (mod->text > text_end || mod->text_end < text_start)
2cfa1978 649 continue;
5967ed87
JB
650 for (poff = mod->locks; poff < mod->locks_end; poff++) {
651 const u8 *ptr = (const u8 *)poff + *poff;
652
653 if (text_start <= ptr && text_end > ptr)
2cfa1978 654 return 1;
5967ed87 655 }
2cfa1978
MH
656 }
657
658 return 0;
659}
48c7a250 660#endif /* CONFIG_SMP */
8ec4d41f 661
139ec7c4 662#ifdef CONFIG_PARAVIRT
8b5a10fc
JB
663void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
664 struct paravirt_patch_site *end)
139ec7c4 665{
98de032b 666 struct paravirt_patch_site *p;
1fc654cf 667 char insn_buff[MAX_PATCH_LEN];
139ec7c4
RR
668
669 for (p = start; p < end; p++) {
670 unsigned int used;
671
ab144f5e 672 BUG_ON(p->len > MAX_PATCH_LEN);
d34fda4a 673 /* prep the buffer with the original instructions */
1fc654cf 674 memcpy(insn_buff, p->instr, p->len);
054ac8ad 675 used = paravirt_patch(p->type, insn_buff, (unsigned long)p->instr, p->len);
7f63c41c 676
63f70270
JF
677 BUG_ON(used > p->len);
678
139ec7c4 679 /* Pad the rest with nops */
1fc654cf
IM
680 add_nops(insn_buff + used, p->len - used);
681 text_poke_early(p->instr, insn_buff, p->len);
139ec7c4 682 }
139ec7c4 683}
98de032b 684extern struct paravirt_patch_site __start_parainstructions[],
139ec7c4
RR
685 __stop_parainstructions[];
686#endif /* CONFIG_PARAVIRT */
687
7457c0da
PZ
688/*
689 * Self-test for the INT3 based CALL emulation code.
690 *
691 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
692 * properly and that there is a stack gap between the INT3 frame and the
693 * previous context. Without this gap doing a virtual PUSH on the interrupted
694 * stack would corrupt the INT3 IRET frame.
695 *
696 * See entry_{32,64}.S for more details.
697 */
ecc60610
PZ
698
699/*
700 * We define the int3_magic() function in assembly to control the calling
701 * convention such that we can 'call' it from assembly.
702 */
703
704extern void int3_magic(unsigned int *ptr); /* defined in asm */
705
706asm (
707" .pushsection .init.text, \"ax\", @progbits\n"
708" .type int3_magic, @function\n"
709"int3_magic:\n"
710" movl $1, (%" _ASM_ARG1 ")\n"
711" ret\n"
712" .size int3_magic, .-int3_magic\n"
713" .popsection\n"
714);
7457c0da
PZ
715
716extern __initdata unsigned long int3_selftest_ip; /* defined in asm below */
717
718static int __init
719int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
720{
721 struct die_args *args = data;
722 struct pt_regs *regs = args->regs;
723
724 if (!regs || user_mode(regs))
725 return NOTIFY_DONE;
726
727 if (val != DIE_INT3)
728 return NOTIFY_DONE;
729
730 if (regs->ip - INT3_INSN_SIZE != int3_selftest_ip)
731 return NOTIFY_DONE;
732
733 int3_emulate_call(regs, (unsigned long)&int3_magic);
734 return NOTIFY_STOP;
735}
736
737static void __init int3_selftest(void)
738{
739 static __initdata struct notifier_block int3_exception_nb = {
740 .notifier_call = int3_exception_notify,
741 .priority = INT_MAX-1, /* last */
742 };
743 unsigned int val = 0;
744
745 BUG_ON(register_die_notifier(&int3_exception_nb));
746
747 /*
748 * Basically: int3_magic(&val); but really complicated :-)
749 *
750 * Stick the address of the INT3 instruction into int3_selftest_ip,
751 * then trigger the INT3, padded with NOPs to match a CALL instruction
752 * length.
753 */
754 asm volatile ("1: int3; nop; nop; nop; nop\n\t"
755 ".pushsection .init.data,\"aw\"\n\t"
756 ".align " __ASM_SEL(4, 8) "\n\t"
757 ".type int3_selftest_ip, @object\n\t"
758 ".size int3_selftest_ip, " __ASM_SEL(4, 8) "\n\t"
759 "int3_selftest_ip:\n\t"
760 __ASM_SEL(.long, .quad) " 1b\n\t"
761 ".popsection\n\t"
ecc60610
PZ
762 : ASM_CALL_CONSTRAINT
763 : __ASM_SEL_RAW(a, D) (&val)
764 : "memory");
7457c0da
PZ
765
766 BUG_ON(val != 1);
767
768 unregister_die_notifier(&int3_exception_nb);
769}
770
9a0b5817
GH
771void __init alternative_instructions(void)
772{
7457c0da
PZ
773 int3_selftest();
774
775 /*
776 * The patching is not fully atomic, so try to avoid local
777 * interruptions that might execute the to be patched code.
778 * Other CPUs are not running.
779 */
8f4e956b 780 stop_nmi();
123aa76e
AK
781
782 /*
783 * Don't stop machine check exceptions while patching.
784 * MCEs only happen when something got corrupted and in this
785 * case we must do something about the corruption.
32b1cbe3 786 * Ignoring it is worse than an unlikely patching race.
123aa76e
AK
787 * Also machine checks tend to be broadcast and if one CPU
788 * goes into machine check the others follow quickly, so we don't
789 * expect a machine check to cause undue problems during to code
790 * patching.
791 */
8f4e956b 792
4e629211
JG
793 /*
794 * Paravirt patching and alternative patching can be combined to
795 * replace a function call with a short direct code sequence (e.g.
796 * by setting a constant return value instead of doing that in an
797 * external function).
798 * In order to make this work the following sequence is required:
799 * 1. set (artificial) features depending on used paravirt
800 * functions which can later influence alternative patching
801 * 2. apply paravirt patching (generally replacing an indirect
802 * function call with a direct one)
803 * 3. apply alternative patching (e.g. replacing a direct function
804 * call with a custom code sequence)
805 * Doing paravirt patching after alternative patching would clobber
806 * the optimization of the custom code with a function call again.
807 */
808 paravirt_set_cap();
809
810 /*
811 * First patch paravirt functions, such that we overwrite the indirect
812 * call with the direct call.
813 */
814 apply_paravirt(__parainstructions, __parainstructions_end);
815
81211f23
PZ
816 /*
817 * Rewrite the retpolines, must be done before alternatives since
818 * those can rewrite the retpoline thunks.
819 */
820 apply_retpolines(__retpoline_sites, __retpoline_sites_end);
821
4e629211
JG
822 /*
823 * Then patch alternatives, such that those paravirt calls that are in
824 * alternatives can be overwritten by their immediate fragments.
825 */
9a0b5817
GH
826 apply_alternatives(__alt_instructions, __alt_instructions_end);
827
8ec4d41f 828#ifdef CONFIG_SMP
816afe4f
RR
829 /* Patch to UP if other cpus not imminent. */
830 if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
831 uniproc_patched = true;
9a0b5817
GH
832 alternatives_smp_module_add(NULL, "core kernel",
833 __smp_locks, __smp_locks_end,
834 _text, _etext);
9a0b5817 835 }
8f4e956b 836
7457c0da 837 if (!uniproc_patched || num_possible_cpus() == 1) {
f68fd5f4
FW
838 free_init_pages("SMP alternatives",
839 (unsigned long)__smp_locks,
840 (unsigned long)__smp_locks_end);
7457c0da 841 }
816afe4f
RR
842#endif
843
8f4e956b 844 restart_nmi();
5e907bb0 845 alternatives_patched = 1;
9a0b5817 846}
19d36ccd 847
e587cadd
MD
848/**
849 * text_poke_early - Update instructions on a live kernel at boot time
850 * @addr: address to modify
851 * @opcode: source of the copy
852 * @len: length to copy
853 *
19d36ccd
AK
854 * When you use this code to patch more than one byte of an instruction
855 * you need to make sure that other CPUs cannot execute this code in parallel.
e587cadd 856 * Also no thread must be currently preempted in the middle of these
32b1cbe3
MA
857 * instructions. And on the local CPU you need to be protected against NMI or
858 * MCE handlers seeing an inconsistent instruction while you patch.
19d36ccd 859 */
0a203df5
NA
860void __init_or_module text_poke_early(void *addr, const void *opcode,
861 size_t len)
19d36ccd 862{
e587cadd 863 unsigned long flags;
f2c65fb3
NA
864
865 if (boot_cpu_has(X86_FEATURE_NX) &&
866 is_module_text_address((unsigned long)addr)) {
867 /*
868 * Modules text is marked initially as non-executable, so the
869 * code cannot be running and speculative code-fetches are
870 * prevented. Just change the code.
871 */
872 memcpy(addr, opcode, len);
873 } else {
874 local_irq_save(flags);
875 memcpy(addr, opcode, len);
876 local_irq_restore(flags);
877 sync_core();
878
879 /*
880 * Could also do a CLFLUSH here to speed up CPU recovery; but
881 * that causes hangs on some VIA CPUs.
882 */
883 }
e587cadd
MD
884}
885
9020d395
TG
886typedef struct {
887 struct mm_struct *mm;
888} temp_mm_state_t;
889
890/*
891 * Using a temporary mm allows to set temporary mappings that are not accessible
892 * by other CPUs. Such mappings are needed to perform sensitive memory writes
893 * that override the kernel memory protections (e.g., W^X), without exposing the
894 * temporary page-table mappings that are required for these write operations to
895 * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
896 * mapping is torn down.
897 *
898 * Context: The temporary mm needs to be used exclusively by a single core. To
899 * harden security IRQs must be disabled while the temporary mm is
900 * loaded, thereby preventing interrupt handler bugs from overriding
901 * the kernel memory protection.
902 */
903static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
904{
905 temp_mm_state_t temp_state;
906
907 lockdep_assert_irqs_disabled();
abee7c49
JG
908
909 /*
910 * Make sure not to be in TLB lazy mode, as otherwise we'll end up
911 * with a stale address space WITHOUT being in lazy mode after
912 * restoring the previous mm.
913 */
2f4305b1 914 if (this_cpu_read(cpu_tlbstate_shared.is_lazy))
abee7c49
JG
915 leave_mm(smp_processor_id());
916
9020d395
TG
917 temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
918 switch_mm_irqs_off(NULL, mm, current);
919
920 /*
921 * If breakpoints are enabled, disable them while the temporary mm is
922 * used. Userspace might set up watchpoints on addresses that are used
923 * in the temporary mm, which would lead to wrong signals being sent or
924 * crashes.
925 *
926 * Note that breakpoints are not disabled selectively, which also causes
927 * kernel breakpoints (e.g., perf's) to be disabled. This might be
928 * undesirable, but still seems reasonable as the code that runs in the
929 * temporary mm should be short.
930 */
931 if (hw_breakpoint_active())
932 hw_breakpoint_disable();
933
934 return temp_state;
935}
936
937static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
938{
939 lockdep_assert_irqs_disabled();
940 switch_mm_irqs_off(NULL, prev_state.mm, current);
941
942 /*
943 * Restore the breakpoints if they were disabled before the temporary mm
944 * was loaded.
945 */
946 if (hw_breakpoint_active())
947 hw_breakpoint_restore();
948}
949
4fc19708
NA
950__ro_after_init struct mm_struct *poking_mm;
951__ro_after_init unsigned long poking_addr;
952
e836673c 953static void *__text_poke(void *addr, const void *opcode, size_t len)
e587cadd 954{
b3fd8e83
NA
955 bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
956 struct page *pages[2] = {NULL};
957 temp_mm_state_t prev;
78ff7fae 958 unsigned long flags;
b3fd8e83
NA
959 pte_t pte, *ptep;
960 spinlock_t *ptl;
961 pgprot_t pgprot;
e587cadd 962
6fffacb3 963 /*
b3fd8e83
NA
964 * While boot memory allocator is running we cannot use struct pages as
965 * they are not yet initialized. There is no way to recover.
6fffacb3
PT
966 */
967 BUG_ON(!after_bootmem);
968
b7b66baa
MD
969 if (!core_kernel_text((unsigned long)addr)) {
970 pages[0] = vmalloc_to_page(addr);
b3fd8e83
NA
971 if (cross_page_boundary)
972 pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
15a601eb 973 } else {
b7b66baa 974 pages[0] = virt_to_page(addr);
00c6b2d5 975 WARN_ON(!PageReserved(pages[0]));
b3fd8e83
NA
976 if (cross_page_boundary)
977 pages[1] = virt_to_page(addr + PAGE_SIZE);
e587cadd 978 }
b3fd8e83
NA
979 /*
980 * If something went wrong, crash and burn since recovery paths are not
981 * implemented.
982 */
983 BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
984
b3fd8e83
NA
985 /*
986 * Map the page without the global bit, as TLB flushing is done with
987 * flush_tlb_mm_range(), which is intended for non-global PTEs.
988 */
989 pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
990
991 /*
992 * The lock is not really needed, but this allows to avoid open-coding.
993 */
994 ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
995
996 /*
997 * This must not fail; preallocated in poking_init().
998 */
999 VM_BUG_ON(!ptep);
1000
a6d996cb
SAS
1001 local_irq_save(flags);
1002
b3fd8e83
NA
1003 pte = mk_pte(pages[0], pgprot);
1004 set_pte_at(poking_mm, poking_addr, ptep, pte);
1005
1006 if (cross_page_boundary) {
1007 pte = mk_pte(pages[1], pgprot);
1008 set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
1009 }
1010
1011 /*
1012 * Loading the temporary mm behaves as a compiler barrier, which
1013 * guarantees that the PTE will be set at the time memcpy() is done.
1014 */
1015 prev = use_temporary_mm(poking_mm);
1016
1017 kasan_disable_current();
1018 memcpy((u8 *)poking_addr + offset_in_page(addr), opcode, len);
1019 kasan_enable_current();
1020
1021 /*
1022 * Ensure that the PTE is only cleared after the instructions of memcpy
1023 * were issued by using a compiler barrier.
1024 */
1025 barrier();
1026
1027 pte_clear(poking_mm, poking_addr, ptep);
1028 if (cross_page_boundary)
1029 pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
1030
1031 /*
1032 * Loading the previous page-table hierarchy requires a serializing
1033 * instruction that already allows the core to see the updated version.
1034 * Xen-PV is assumed to serialize execution in a similar manner.
1035 */
1036 unuse_temporary_mm(prev);
1037
1038 /*
1039 * Flushing the TLB might involve IPIs, which would require enabled
1040 * IRQs, but not if the mm is not used, as it is in this point.
1041 */
1042 flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
1043 (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
1044 PAGE_SHIFT, false);
1045
1046 /*
1047 * If the text does not match what we just wrote then something is
1048 * fundamentally screwy; there's nothing we can really do about that.
1049 */
1050 BUG_ON(memcmp(addr, opcode, len));
1051
7cf49427 1052 local_irq_restore(flags);
a6d996cb 1053 pte_unmap_unlock(ptep, ptl);
e587cadd 1054 return addr;
19d36ccd 1055}
3d55cc8a 1056
e836673c
NA
1057/**
1058 * text_poke - Update instructions on a live kernel
1059 * @addr: address to modify
1060 * @opcode: source of the copy
1061 * @len: length to copy
1062 *
1063 * Only atomic text poke/set should be allowed when not doing early patching.
1064 * It means the size must be writable atomically and the address must be aligned
1065 * in a way that permits an atomic write. It also makes sure we fit on a single
1066 * page.
3950746d
NA
1067 *
1068 * Note that the caller must ensure that if the modified code is part of a
1069 * module, the module would not be removed during poking. This can be achieved
1070 * by registering a module notifier, and ordering module removal and patching
1071 * trough a mutex.
e836673c
NA
1072 */
1073void *text_poke(void *addr, const void *opcode, size_t len)
1074{
1075 lockdep_assert_held(&text_mutex);
1076
1077 return __text_poke(addr, opcode, len);
1078}
1079
1080/**
1081 * text_poke_kgdb - Update instructions on a live kernel by kgdb
1082 * @addr: address to modify
1083 * @opcode: source of the copy
1084 * @len: length to copy
1085 *
1086 * Only atomic text poke/set should be allowed when not doing early patching.
1087 * It means the size must be writable atomically and the address must be aligned
1088 * in a way that permits an atomic write. It also makes sure we fit on a single
1089 * page.
1090 *
1091 * Context: should only be used by kgdb, which ensures no other core is running,
1092 * despite the fact it does not hold the text_mutex.
1093 */
1094void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
1095{
1096 return __text_poke(addr, opcode, len);
1097}
1098
fd4363ff
JK
1099static void do_sync_core(void *info)
1100{
1101 sync_core();
1102}
1103
5c02ece8
PZ
1104void text_poke_sync(void)
1105{
1106 on_each_cpu(do_sync_core, NULL, 1);
1107}
1108
18cbc8be 1109struct text_poke_loc {
4531ef6a 1110 s32 rel_addr; /* addr := _stext + rel_addr */
18cbc8be
PZ
1111 s32 rel32;
1112 u8 opcode;
1113 const u8 text[POKE_MAX_OPCODE_SIZE];
d769811c 1114 u8 old;
18cbc8be
PZ
1115};
1116
1f676247 1117struct bp_patching_desc {
c0213b0a
DBO
1118 struct text_poke_loc *vec;
1119 int nr_entries;
1f676247
PZ
1120 atomic_t refs;
1121};
1122
1123static struct bp_patching_desc *bp_desc;
1124
4979fb53
TG
1125static __always_inline
1126struct bp_patching_desc *try_get_desc(struct bp_patching_desc **descp)
1f676247 1127{
ef882bfe 1128 struct bp_patching_desc *desc = __READ_ONCE(*descp); /* rcu_dereference */
1f676247 1129
ef882bfe 1130 if (!desc || !arch_atomic_inc_not_zero(&desc->refs))
1f676247
PZ
1131 return NULL;
1132
1133 return desc;
1134}
1135
4979fb53 1136static __always_inline void put_desc(struct bp_patching_desc *desc)
1f676247
PZ
1137{
1138 smp_mb__before_atomic();
ef882bfe 1139 arch_atomic_dec(&desc->refs);
1f676247 1140}
c0213b0a 1141
4979fb53 1142static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
4531ef6a
PZ
1143{
1144 return _stext + tp->rel_addr;
1145}
1146
f64366ef 1147static __always_inline int patch_cmp(const void *key, const void *elt)
c0213b0a
DBO
1148{
1149 struct text_poke_loc *tp = (struct text_poke_loc *) elt;
1150
4531ef6a 1151 if (key < text_poke_addr(tp))
c0213b0a 1152 return -1;
4531ef6a 1153 if (key > text_poke_addr(tp))
c0213b0a
DBO
1154 return 1;
1155 return 0;
1156}
fd4363ff 1157
7f6fa101 1158noinstr int poke_int3_handler(struct pt_regs *regs)
fd4363ff 1159{
1f676247 1160 struct bp_patching_desc *desc;
c0213b0a 1161 struct text_poke_loc *tp;
1f676247 1162 int len, ret = 0;
c0213b0a 1163 void *ip;
1f676247
PZ
1164
1165 if (user_mode(regs))
1166 return 0;
c0213b0a 1167
01651324
PZ
1168 /*
1169 * Having observed our INT3 instruction, we now must observe
1f676247 1170 * bp_desc:
01651324 1171 *
1f676247 1172 * bp_desc = desc INT3
c3d6324f 1173 * WMB RMB
1f676247 1174 * write INT3 if (desc)
01651324 1175 */
fd4363ff
JK
1176 smp_rmb();
1177
1f676247
PZ
1178 desc = try_get_desc(&bp_desc);
1179 if (!desc)
17f41571 1180 return 0;
fd4363ff 1181
c0213b0a 1182 /*
c3d6324f 1183 * Discount the INT3. See text_poke_bp_batch().
c0213b0a 1184 */
c3d6324f 1185 ip = (void *) regs->ip - INT3_INSN_SIZE;
c0213b0a
DBO
1186
1187 /*
1188 * Skip the binary search if there is a single member in the vector.
1189 */
1f676247 1190 if (unlikely(desc->nr_entries > 1)) {
f64366ef
PZ
1191 tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
1192 sizeof(struct text_poke_loc),
1193 patch_cmp);
c0213b0a 1194 if (!tp)
1f676247 1195 goto out_put;
c0213b0a 1196 } else {
1f676247 1197 tp = desc->vec;
4531ef6a 1198 if (text_poke_addr(tp) != ip)
1f676247 1199 goto out_put;
c0213b0a
DBO
1200 }
1201
97e6c977
PZ
1202 len = text_opcode_size(tp->opcode);
1203 ip += len;
c3d6324f
PZ
1204
1205 switch (tp->opcode) {
1206 case INT3_INSN_OPCODE:
1207 /*
1208 * Someone poked an explicit INT3, they'll want to handle it,
1209 * do not consume.
1210 */
1f676247 1211 goto out_put;
c3d6324f 1212
c43a43e4
PZ
1213 case RET_INSN_OPCODE:
1214 int3_emulate_ret(regs);
1215 break;
1216
c3d6324f
PZ
1217 case CALL_INSN_OPCODE:
1218 int3_emulate_call(regs, (long)ip + tp->rel32);
1219 break;
1220
1221 case JMP32_INSN_OPCODE:
1222 case JMP8_INSN_OPCODE:
1223 int3_emulate_jmp(regs, (long)ip + tp->rel32);
1224 break;
1225
1226 default:
1227 BUG();
1228 }
17f41571 1229
1f676247
PZ
1230 ret = 1;
1231
1232out_put:
1233 put_desc(desc);
1234 return ret;
fd4363ff 1235}
17f41571 1236
18cbc8be
PZ
1237#define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
1238static struct text_poke_loc tp_vec[TP_VEC_MAX];
1239static int tp_vec_nr;
1240
fd4363ff 1241/**
c0213b0a
DBO
1242 * text_poke_bp_batch() -- update instructions on live kernel on SMP
1243 * @tp: vector of instructions to patch
1244 * @nr_entries: number of entries in the vector
fd4363ff
JK
1245 *
1246 * Modify multi-byte instruction by using int3 breakpoint on SMP.
ea8596bb
MH
1247 * We completely avoid stop_machine() here, and achieve the
1248 * synchronization using int3 breakpoint.
fd4363ff
JK
1249 *
1250 * The way it is done:
c3d6324f 1251 * - For each entry in the vector:
c0213b0a 1252 * - add a int3 trap to the address that will be patched
fd4363ff 1253 * - sync cores
c0213b0a
DBO
1254 * - For each entry in the vector:
1255 * - update all but the first byte of the patched range
fd4363ff 1256 * - sync cores
c0213b0a
DBO
1257 * - For each entry in the vector:
1258 * - replace the first byte (int3) by the first byte of
1259 * replacing opcode
fd4363ff 1260 * - sync cores
fd4363ff 1261 */
18cbc8be 1262static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
fd4363ff 1263{
1f676247
PZ
1264 struct bp_patching_desc desc = {
1265 .vec = tp,
1266 .nr_entries = nr_entries,
1267 .refs = ATOMIC_INIT(1),
1268 };
c3d6324f 1269 unsigned char int3 = INT3_INSN_OPCODE;
c0213b0a 1270 unsigned int i;
c3d6324f 1271 int do_sync;
9222f606
JK
1272
1273 lockdep_assert_held(&text_mutex);
1274
1f676247 1275 smp_store_release(&bp_desc, &desc); /* rcu_assign_pointer */
c0213b0a 1276
fd4363ff 1277 /*
01651324 1278 * Corresponding read barrier in int3 notifier for making sure the
c0213b0a 1279 * nr_entries and handler are correctly ordered wrt. patching.
fd4363ff
JK
1280 */
1281 smp_wmb();
1282
c0213b0a
DBO
1283 /*
1284 * First step: add a int3 trap to the address that will be patched.
1285 */
d769811c
AH
1286 for (i = 0; i < nr_entries; i++) {
1287 tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
76ffa720 1288 text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
d769811c 1289 }
fd4363ff 1290
5c02ece8 1291 text_poke_sync();
fd4363ff 1292
c0213b0a
DBO
1293 /*
1294 * Second step: update all but the first byte of the patched range.
1295 */
c3d6324f 1296 for (do_sync = 0, i = 0; i < nr_entries; i++) {
d769811c 1297 u8 old[POKE_MAX_OPCODE_SIZE] = { tp[i].old, };
97e6c977
PZ
1298 int len = text_opcode_size(tp[i].opcode);
1299
76ffa720 1300 if (len - INT3_INSN_SIZE > 0) {
d769811c
AH
1301 memcpy(old + INT3_INSN_SIZE,
1302 text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1303 len - INT3_INSN_SIZE);
76ffa720
PZ
1304 text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1305 (const char *)tp[i].text + INT3_INSN_SIZE,
1306 len - INT3_INSN_SIZE);
c3d6324f 1307 do_sync++;
c0213b0a 1308 }
d769811c
AH
1309
1310 /*
1311 * Emit a perf event to record the text poke, primarily to
1312 * support Intel PT decoding which must walk the executable code
1313 * to reconstruct the trace. The flow up to here is:
1314 * - write INT3 byte
1315 * - IPI-SYNC
1316 * - write instruction tail
1317 * At this point the actual control flow will be through the
1318 * INT3 and handler and not hit the old or new instruction.
1319 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
1320 * can still be decoded. Subsequently:
1321 * - emit RECORD_TEXT_POKE with the new instruction
1322 * - IPI-SYNC
1323 * - write first byte
1324 * - IPI-SYNC
1325 * So before the text poke event timestamp, the decoder will see
1326 * either the old instruction flow or FUP/TIP of INT3. After the
1327 * text poke event timestamp, the decoder will see either the
1328 * new instruction flow or FUP/TIP of INT3. Thus decoders can
1329 * use the timestamp as the point at which to modify the
1330 * executable code.
1331 * The old instruction is recorded so that the event can be
1332 * processed forwards or backwards.
1333 */
1334 perf_event_text_poke(text_poke_addr(&tp[i]), old, len,
1335 tp[i].text, len);
c0213b0a
DBO
1336 }
1337
c3d6324f 1338 if (do_sync) {
fd4363ff
JK
1339 /*
1340 * According to Intel, this core syncing is very likely
1341 * not necessary and we'd be safe even without it. But
1342 * better safe than sorry (plus there's not only Intel).
1343 */
5c02ece8 1344 text_poke_sync();
fd4363ff
JK
1345 }
1346
c0213b0a
DBO
1347 /*
1348 * Third step: replace the first byte (int3) by the first byte of
1349 * replacing opcode.
1350 */
c3d6324f
PZ
1351 for (do_sync = 0, i = 0; i < nr_entries; i++) {
1352 if (tp[i].text[0] == INT3_INSN_OPCODE)
1353 continue;
1354
76ffa720 1355 text_poke(text_poke_addr(&tp[i]), tp[i].text, INT3_INSN_SIZE);
c3d6324f
PZ
1356 do_sync++;
1357 }
1358
1359 if (do_sync)
5c02ece8 1360 text_poke_sync();
fd4363ff 1361
01651324 1362 /*
1f676247
PZ
1363 * Remove and synchronize_rcu(), except we have a very primitive
1364 * refcount based completion.
01651324 1365 */
1f676247
PZ
1366 WRITE_ONCE(bp_desc, NULL); /* RCU_INIT_POINTER */
1367 if (!atomic_dec_and_test(&desc.refs))
1368 atomic_cond_read_acquire(&desc.refs, !VAL);
fd4363ff
JK
1369}
1370
244febbe
QH
1371static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
1372 const void *opcode, size_t len, const void *emulate)
c3d6324f
PZ
1373{
1374 struct insn insn;
63c66cde 1375 int ret;
c3d6324f 1376
18cbc8be 1377 memcpy((void *)tp->text, opcode, len);
c3d6324f
PZ
1378 if (!emulate)
1379 emulate = opcode;
1380
52fa82c2 1381 ret = insn_decode_kernel(&insn, emulate);
c3d6324f 1382
63c66cde 1383 BUG_ON(ret < 0);
c3d6324f
PZ
1384 BUG_ON(len != insn.length);
1385
4531ef6a 1386 tp->rel_addr = addr - (void *)_stext;
c3d6324f
PZ
1387 tp->opcode = insn.opcode.bytes[0];
1388
1389 switch (tp->opcode) {
1390 case INT3_INSN_OPCODE:
c43a43e4 1391 case RET_INSN_OPCODE:
c3d6324f
PZ
1392 break;
1393
1394 case CALL_INSN_OPCODE:
1395 case JMP32_INSN_OPCODE:
1396 case JMP8_INSN_OPCODE:
1397 tp->rel32 = insn.immediate.value;
1398 break;
1399
1400 default: /* assume NOP */
1401 switch (len) {
1402 case 2: /* NOP2 -- emulate as JMP8+0 */
a89dfde3 1403 BUG_ON(memcmp(emulate, x86_nops[len], len));
c3d6324f
PZ
1404 tp->opcode = JMP8_INSN_OPCODE;
1405 tp->rel32 = 0;
1406 break;
1407
1408 case 5: /* NOP5 -- emulate as JMP32+0 */
a89dfde3 1409 BUG_ON(memcmp(emulate, x86_nops[len], len));
c3d6324f
PZ
1410 tp->opcode = JMP32_INSN_OPCODE;
1411 tp->rel32 = 0;
1412 break;
1413
1414 default: /* unknown instruction */
1415 BUG();
1416 }
1417 break;
1418 }
1419}
1420
18cbc8be
PZ
1421/*
1422 * We hard rely on the tp_vec being ordered; ensure this is so by flushing
1423 * early if needed.
1424 */
1425static bool tp_order_fail(void *addr)
1426{
1427 struct text_poke_loc *tp;
1428
1429 if (!tp_vec_nr)
1430 return false;
1431
1432 if (!addr) /* force */
1433 return true;
1434
1435 tp = &tp_vec[tp_vec_nr - 1];
4531ef6a 1436 if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
18cbc8be
PZ
1437 return true;
1438
1439 return false;
1440}
1441
1442static void text_poke_flush(void *addr)
1443{
1444 if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
1445 text_poke_bp_batch(tp_vec, tp_vec_nr);
1446 tp_vec_nr = 0;
1447 }
1448}
1449
1450void text_poke_finish(void)
1451{
1452 text_poke_flush(NULL);
1453}
1454
768ae440 1455void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
18cbc8be
PZ
1456{
1457 struct text_poke_loc *tp;
1458
768ae440
PZ
1459 if (unlikely(system_state == SYSTEM_BOOTING)) {
1460 text_poke_early(addr, opcode, len);
1461 return;
1462 }
1463
18cbc8be
PZ
1464 text_poke_flush(addr);
1465
1466 tp = &tp_vec[tp_vec_nr++];
1467 text_poke_loc_init(tp, addr, opcode, len, emulate);
1468}
1469
c0213b0a
DBO
1470/**
1471 * text_poke_bp() -- update instructions on live kernel on SMP
1472 * @addr: address to patch
1473 * @opcode: opcode of new instruction
1474 * @len: length to copy
72ebb5ff 1475 * @emulate: instruction to be emulated
c0213b0a
DBO
1476 *
1477 * Update a single instruction with the vector in the stack, avoiding
1478 * dynamically allocated memory. This function should be used when it is
1479 * not possible to allocate memory.
1480 */
768ae440 1481void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
c0213b0a 1482{
c3d6324f 1483 struct text_poke_loc tp;
c0213b0a 1484
768ae440
PZ
1485 if (unlikely(system_state == SYSTEM_BOOTING)) {
1486 text_poke_early(addr, opcode, len);
1487 return;
1488 }
1489
c3d6324f 1490 text_poke_loc_init(&tp, addr, opcode, len, emulate);
c0213b0a
DBO
1491 text_poke_bp_batch(&tp, 1);
1492}