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