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