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