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