xref: /linux/arch/x86/kernel/alternative.c (revision 59e6295fac26b8e85c1ea859cdd89fa1e47519d7)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #define pr_fmt(fmt) "SMP alternatives: " fmt
3 
4 #include <linux/mmu_context.h>
5 #include <linux/perf_event.h>
6 #include <linux/vmalloc.h>
7 #include <linux/memory.h>
8 #include <linux/execmem.h>
9 
10 #include <asm/text-patching.h>
11 #include <asm/insn.h>
12 #include <asm/insn-eval.h>
13 #include <asm/ibt.h>
14 #include <asm/set_memory.h>
15 #include <asm/nmi.h>
16 
17 int __read_mostly alternatives_patched;
18 
19 EXPORT_SYMBOL_GPL(alternatives_patched);
20 
21 #define MAX_PATCH_LEN (255-1)
22 
23 #define DA_ALL		(~0)
24 #define DA_ALT		0x01
25 #define DA_RET		0x02
26 #define DA_RETPOLINE	0x04
27 #define DA_ENDBR	0x08
28 #define DA_SMP		0x10
29 
30 static unsigned int debug_alternative;
31 
32 static int __init debug_alt(char *str)
33 {
34 	if (str && *str == '=')
35 		str++;
36 
37 	if (!str || kstrtouint(str, 0, &debug_alternative))
38 		debug_alternative = DA_ALL;
39 
40 	return 1;
41 }
42 __setup("debug-alternative", debug_alt);
43 
44 #define DPRINTK(type, fmt, args...)					\
45 do {									\
46 	if (debug_alternative & DA_##type)				\
47 		printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args);		\
48 } while (0)
49 
50 #define DUMP_BYTES(type, buf, len, fmt, args...)			\
51 do {									\
52 	if (unlikely(debug_alternative & DA_##type)) {			\
53 		int j;							\
54 									\
55 		if (!(len))						\
56 			break;						\
57 									\
58 		printk(KERN_DEBUG pr_fmt(fmt), ##args);			\
59 		for (j = 0; j < (len) - 1; j++)				\
60 			printk(KERN_CONT "%02hhx ", buf[j]);		\
61 		printk(KERN_CONT "%02hhx\n", buf[j]);			\
62 	}								\
63 } while (0)
64 
65 static const unsigned char x86nops[] =
66 {
67 	BYTES_NOP1,
68 	BYTES_NOP2,
69 	BYTES_NOP3,
70 	BYTES_NOP4,
71 	BYTES_NOP5,
72 	BYTES_NOP6,
73 	BYTES_NOP7,
74 	BYTES_NOP8,
75 #ifdef CONFIG_64BIT
76 	BYTES_NOP9,
77 	BYTES_NOP10,
78 	BYTES_NOP11,
79 #endif
80 };
81 
82 const unsigned char * const x86_nops[ASM_NOP_MAX+1] =
83 {
84 	NULL,
85 	x86nops,
86 	x86nops + 1,
87 	x86nops + 1 + 2,
88 	x86nops + 1 + 2 + 3,
89 	x86nops + 1 + 2 + 3 + 4,
90 	x86nops + 1 + 2 + 3 + 4 + 5,
91 	x86nops + 1 + 2 + 3 + 4 + 5 + 6,
92 	x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
93 #ifdef CONFIG_64BIT
94 	x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
95 	x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,
96 	x86nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,
97 #endif
98 };
99 
100 #ifdef CONFIG_FINEIBT
101 static bool cfi_paranoid __ro_after_init;
102 #endif
103 
104 #ifdef CONFIG_MITIGATION_ITS
105 
106 #ifdef CONFIG_MODULES
107 static struct module *its_mod;
108 #endif
109 static void *its_page;
110 static unsigned int its_offset;
111 struct its_array its_pages;
112 
113 static void *__its_alloc(struct its_array *pages)
114 {
115 	void *page __free(execmem) = execmem_alloc_rw(EXECMEM_MODULE_TEXT, PAGE_SIZE);
116 	if (!page)
117 		return NULL;
118 
119 	void *tmp = krealloc(pages->pages, (pages->num+1) * sizeof(void *),
120 			     GFP_KERNEL);
121 	if (!tmp)
122 		return NULL;
123 
124 	pages->pages = tmp;
125 	pages->pages[pages->num++] = page;
126 
127 	return no_free_ptr(page);
128 }
129 
130 /* Initialize a thunk with the "jmp *reg; int3" instructions. */
131 static void *its_init_thunk(void *thunk, int reg)
132 {
133 	u8 *bytes = thunk;
134 	int offset = 0;
135 	int i = 0;
136 
137 #ifdef CONFIG_FINEIBT
138 	if (cfi_paranoid) {
139 		/*
140 		 * When ITS uses indirect branch thunk the fineibt_paranoid
141 		 * caller sequence doesn't fit in the caller site. So put the
142 		 * remaining part of the sequence (UDB + JNE) into the ITS
143 		 * thunk.
144 		 */
145 		bytes[i++] = 0xd6; /* UDB */
146 		bytes[i++] = 0x75; /* JNE */
147 		bytes[i++] = 0xfd;
148 
149 		offset = 1;
150 	}
151 #endif
152 
153 	if (reg >= 8) {
154 		bytes[i++] = 0x41; /* REX.B prefix */
155 		reg -= 8;
156 	}
157 	bytes[i++] = 0xff;
158 	bytes[i++] = 0xe0 + reg; /* JMP *reg */
159 	bytes[i++] = 0xcc;
160 
161 	return thunk + offset;
162 }
163 
164 static void its_pages_protect(struct its_array *pages)
165 {
166 	for (int i = 0; i < pages->num; i++) {
167 		void *page = pages->pages[i];
168 		execmem_restore_rox(page, PAGE_SIZE);
169 	}
170 }
171 
172 static void its_fini_core(void)
173 {
174 	if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX))
175 		its_pages_protect(&its_pages);
176 	kfree(its_pages.pages);
177 }
178 
179 #ifdef CONFIG_MODULES
180 void its_init_mod(struct module *mod)
181 {
182 	if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
183 		return;
184 
185 	mutex_lock(&text_mutex);
186 	its_mod = mod;
187 	its_page = NULL;
188 }
189 
190 void its_fini_mod(struct module *mod)
191 {
192 	if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
193 		return;
194 
195 	WARN_ON_ONCE(its_mod != mod);
196 
197 	its_mod = NULL;
198 	its_page = NULL;
199 	mutex_unlock(&text_mutex);
200 
201 	if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX))
202 		its_pages_protect(&mod->arch.its_pages);
203 }
204 
205 void its_free_mod(struct module *mod)
206 {
207 	if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
208 		return;
209 
210 	for (int i = 0; i < mod->arch.its_pages.num; i++) {
211 		void *page = mod->arch.its_pages.pages[i];
212 		execmem_free(page);
213 	}
214 	kfree(mod->arch.its_pages.pages);
215 }
216 #endif /* CONFIG_MODULES */
217 
218 static void *its_alloc(void)
219 {
220 	struct its_array *pages = &its_pages;
221 	void *page;
222 
223 #ifdef CONFIG_MODULES
224 	if (its_mod)
225 		pages = &its_mod->arch.its_pages;
226 #endif
227 
228 	page = __its_alloc(pages);
229 	if (!page)
230 		return NULL;
231 
232 	if (pages == &its_pages)
233 		set_memory_x((unsigned long)page, 1);
234 
235 	return page;
236 }
237 
238 static void *its_allocate_thunk(int reg)
239 {
240 	int size = 3 + (reg / 8);
241 	void *thunk;
242 
243 #ifdef CONFIG_FINEIBT
244 	/*
245 	 * The ITS thunk contains an indirect jump and an int3 instruction so
246 	 * its size is 3 or 4 bytes depending on the register used. If CFI
247 	 * paranoid is used then 3 extra bytes are added in the ITS thunk to
248 	 * complete the fineibt_paranoid caller sequence.
249 	 */
250 	if (cfi_paranoid)
251 		size += 3;
252 #endif
253 
254 	if (!its_page || (its_offset + size - 1) >= PAGE_SIZE) {
255 		its_page = its_alloc();
256 		if (!its_page) {
257 			pr_err("ITS page allocation failed\n");
258 			return NULL;
259 		}
260 		memset(its_page, INT3_INSN_OPCODE, PAGE_SIZE);
261 		its_offset = 32;
262 	}
263 
264 	/*
265 	 * If the indirect branch instruction will be in the lower half
266 	 * of a cacheline, then update the offset to reach the upper half.
267 	 */
268 	if ((its_offset + size - 1) % 64 < 32)
269 		its_offset = ((its_offset - 1) | 0x3F) + 33;
270 
271 	thunk = its_page + its_offset;
272 	its_offset += size;
273 
274 	return its_init_thunk(thunk, reg);
275 }
276 
277 u8 *its_static_thunk(int reg)
278 {
279 	u8 *thunk = __x86_indirect_its_thunk_array[reg];
280 
281 #ifdef CONFIG_FINEIBT
282 	/* Paranoid thunk starts 2 bytes before */
283 	if (cfi_paranoid)
284 		return thunk - 2;
285 #endif
286 	return thunk;
287 }
288 
289 #else
290 static inline void its_fini_core(void) {}
291 #endif /* CONFIG_MITIGATION_ITS */
292 
293 /*
294  * Nomenclature for variable names to simplify and clarify this code and ease
295  * any potential staring at it:
296  *
297  * @instr: source address of the original instructions in the kernel text as
298  * generated by the compiler.
299  *
300  * @buf: temporary buffer on which the patching operates. This buffer is
301  * eventually text-poked into the kernel image.
302  *
303  * @replacement/@repl: pointer to the opcodes which are replacing @instr, located
304  * in the .altinstr_replacement section.
305  */
306 
307 /*
308  * Fill the buffer with a single effective instruction of size @len.
309  *
310  * In order not to issue an ORC stack depth tracking CFI entry (Call Frame Info)
311  * for every single-byte NOP, try to generate the maximally available NOP of
312  * size <= ASM_NOP_MAX such that only a single CFI entry is generated (vs one for
313  * each single-byte NOPs). If @len to fill out is > ASM_NOP_MAX, pad with INT3 and
314  * *jump* over instead of executing long and daft NOPs.
315  */
316 static void add_nop(u8 *buf, unsigned int len)
317 {
318 	u8 *target = buf + len;
319 
320 	if (!len)
321 		return;
322 
323 	if (len <= ASM_NOP_MAX) {
324 		memcpy(buf, x86_nops[len], len);
325 		return;
326 	}
327 
328 	if (len < 128) {
329 		__text_gen_insn(buf, JMP8_INSN_OPCODE, buf, target, JMP8_INSN_SIZE);
330 		buf += JMP8_INSN_SIZE;
331 	} else {
332 		__text_gen_insn(buf, JMP32_INSN_OPCODE, buf, target, JMP32_INSN_SIZE);
333 		buf += JMP32_INSN_SIZE;
334 	}
335 
336 	for (;buf < target; buf++)
337 		*buf = INT3_INSN_OPCODE;
338 }
339 
340 /*
341  * Find the offset of the first non-NOP instruction starting at @offset
342  * but no further than @len.
343  */
344 static int skip_nops(u8 *buf, int offset, int len)
345 {
346 	struct insn insn;
347 
348 	for (; offset < len; offset += insn.length) {
349 		if (insn_decode_kernel(&insn, &buf[offset]))
350 			break;
351 
352 		if (!insn_is_nop(&insn))
353 			break;
354 	}
355 
356 	return offset;
357 }
358 
359 /*
360  * "noinline" to cause control flow change and thus invalidate I$ and
361  * cause refetch after modification.
362  */
363 static void noinline optimize_nops(const u8 * const instr, u8 *buf, size_t len)
364 {
365 	for (int next, i = 0; i < len; i = next) {
366 		struct insn insn;
367 
368 		if (insn_decode_kernel(&insn, &buf[i]))
369 			return;
370 
371 		next = i + insn.length;
372 
373 		if (insn_is_nop(&insn)) {
374 			int nop = i;
375 
376 			/* Has the NOP already been optimized? */
377 			if (i + insn.length == len)
378 				return;
379 
380 			next = skip_nops(buf, next, len);
381 
382 			add_nop(buf + nop, next - nop);
383 			DUMP_BYTES(ALT, buf, len, "%px: [%d:%d) optimized NOPs: ", instr, nop, next);
384 		}
385 	}
386 }
387 
388 /*
389  * In this context, "source" is where the instructions are placed in the
390  * section .altinstr_replacement, for example during kernel build by the
391  * toolchain.
392  * "Destination" is where the instructions are being patched in by this
393  * machinery.
394  *
395  * The source offset is:
396  *
397  *   src_imm = target - src_next_ip                  (1)
398  *
399  * and the target offset is:
400  *
401  *   dst_imm = target - dst_next_ip                  (2)
402  *
403  * so rework (1) as an expression for target like:
404  *
405  *   target = src_imm + src_next_ip                  (1a)
406  *
407  * and substitute in (2) to get:
408  *
409  *   dst_imm = (src_imm + src_next_ip) - dst_next_ip (3)
410  *
411  * Now, since the instruction stream is 'identical' at src and dst (it
412  * is being copied after all) it can be stated that:
413  *
414  *   src_next_ip = src + ip_offset
415  *   dst_next_ip = dst + ip_offset                   (4)
416  *
417  * Substitute (4) in (3) and observe ip_offset being cancelled out to
418  * obtain:
419  *
420  *   dst_imm = src_imm + (src + ip_offset) - (dst + ip_offset)
421  *           = src_imm + src - dst + ip_offset - ip_offset
422  *           = src_imm + src - dst                   (5)
423  *
424  * IOW, only the relative displacement of the code block matters.
425  */
426 
427 #define apply_reloc_n(n_, p_, d_)				\
428 	do {							\
429 		s32 v = *(s##n_ *)(p_);				\
430 		v += (d_);					\
431 		BUG_ON((v >> 31) != (v >> (n_-1)));		\
432 		*(s##n_ *)(p_) = (s##n_)v;			\
433 	} while (0)
434 
435 
436 static __always_inline
437 void apply_reloc(int n, void *ptr, uintptr_t diff)
438 {
439 	switch (n) {
440 	case 1: apply_reloc_n(8, ptr, diff); break;
441 	case 2: apply_reloc_n(16, ptr, diff); break;
442 	case 4: apply_reloc_n(32, ptr, diff); break;
443 	default: BUG();
444 	}
445 }
446 
447 static __always_inline
448 bool need_reloc(unsigned long offset, u8 *src, size_t src_len)
449 {
450 	u8 *target = src + offset;
451 	/*
452 	 * If the target is inside the patched block, it's relative to the
453 	 * block itself and does not need relocation.
454 	 */
455 	return (target < src || target > src + src_len);
456 }
457 
458 static void __apply_relocation(u8 *buf, const u8 * const instr, size_t instrlen, u8 *repl, size_t repl_len)
459 {
460 	for (int next, i = 0; i < instrlen; i = next) {
461 		struct insn insn;
462 
463 		if (WARN_ON_ONCE(insn_decode_kernel(&insn, &buf[i])))
464 			return;
465 
466 		next = i + insn.length;
467 
468 		switch (insn.opcode.bytes[0]) {
469 		case 0x0f:
470 			if (insn.opcode.bytes[1] < 0x80 ||
471 			    insn.opcode.bytes[1] > 0x8f)
472 				break;
473 
474 			fallthrough;	/* Jcc.d32 */
475 		case 0x70 ... 0x7f:	/* Jcc.d8 */
476 		case JMP8_INSN_OPCODE:
477 		case JMP32_INSN_OPCODE:
478 		case CALL_INSN_OPCODE:
479 			if (need_reloc(next + insn.immediate.value, repl, repl_len)) {
480 				apply_reloc(insn.immediate.nbytes,
481 					    buf + i + insn_offset_immediate(&insn),
482 					    repl - instr);
483 			}
484 
485 			/*
486 			 * Where possible, convert JMP.d32 into JMP.d8.
487 			 */
488 			if (insn.opcode.bytes[0] == JMP32_INSN_OPCODE) {
489 				s32 imm = insn.immediate.value;
490 				imm += repl - instr;
491 				imm += JMP32_INSN_SIZE - JMP8_INSN_SIZE;
492 				if ((imm >> 31) == (imm >> 7)) {
493 					buf[i+0] = JMP8_INSN_OPCODE;
494 					buf[i+1] = (s8)imm;
495 
496 					memset(&buf[i+2], INT3_INSN_OPCODE, insn.length - 2);
497 				}
498 			}
499 			break;
500 		}
501 
502 		if (insn_rip_relative(&insn)) {
503 			if (need_reloc(next + insn.displacement.value, repl, repl_len)) {
504 				apply_reloc(insn.displacement.nbytes,
505 					    buf + i + insn_offset_displacement(&insn),
506 					    repl - instr);
507 			}
508 		}
509 	}
510 }
511 
512 void text_poke_apply_relocation(u8 *buf, const u8 * const instr, size_t instrlen, u8 *repl, size_t repl_len)
513 {
514 	__apply_relocation(buf, instr, instrlen, repl, repl_len);
515 	optimize_nops(instr, buf, instrlen);
516 }
517 
518 /* Low-level backend functions usable from alternative code replacements. */
519 DEFINE_ASM_FUNC(nop_func, "", .entry.text);
520 EXPORT_SYMBOL_GPL(nop_func);
521 
522 noinstr void BUG_func(void)
523 {
524 	BUG();
525 }
526 EXPORT_SYMBOL(BUG_func);
527 
528 #define CALL_RIP_REL_OPCODE	0xff
529 #define CALL_RIP_REL_MODRM	0x15
530 
531 /*
532  * Rewrite the "call BUG_func" replacement to point to the target of the
533  * indirect pv_ops call "call *disp(%ip)".
534  */
535 static unsigned int alt_replace_call(u8 *instr, u8 *insn_buff, struct alt_instr *a)
536 {
537 	void *target, *bug = &BUG_func;
538 	s32 disp;
539 
540 	if (a->replacementlen != 5 || insn_buff[0] != CALL_INSN_OPCODE) {
541 		pr_err("ALT_FLAG_DIRECT_CALL set for a non-call replacement instruction\n");
542 		BUG();
543 	}
544 
545 	if (a->instrlen != 6 ||
546 	    instr[0] != CALL_RIP_REL_OPCODE ||
547 	    instr[1] != CALL_RIP_REL_MODRM) {
548 		pr_err("ALT_FLAG_DIRECT_CALL set for unrecognized indirect call\n");
549 		BUG();
550 	}
551 
552 	/* Skip CALL_RIP_REL_OPCODE and CALL_RIP_REL_MODRM */
553 	disp = *(s32 *)(instr + 2);
554 #ifdef CONFIG_X86_64
555 	/* ff 15 00 00 00 00   call   *0x0(%rip) */
556 	/* target address is stored at "next instruction + disp". */
557 	target = *(void **)(instr + a->instrlen + disp);
558 #else
559 	/* ff 15 00 00 00 00   call   *0x0 */
560 	/* target address is stored at disp. */
561 	target = *(void **)disp;
562 #endif
563 	if (!target)
564 		target = bug;
565 
566 	/* (BUG_func - .) + (target - BUG_func) := target - . */
567 	*(s32 *)(insn_buff + 1) += target - bug;
568 
569 	if (target == &nop_func)
570 		return 0;
571 
572 	return 5;
573 }
574 
575 static inline u8 * instr_va(struct alt_instr *i)
576 {
577 	return (u8 *)&i->instr_offset + i->instr_offset;
578 }
579 
580 struct patch_site {
581 	u8 *instr;
582 	struct alt_instr *alt;
583 	u8 buff[MAX_PATCH_LEN];
584 	u8 len;
585 };
586 
587 static struct alt_instr * __init_or_module analyze_patch_site(struct patch_site *ps,
588 							     struct alt_instr *start,
589 							     struct alt_instr *end)
590 {
591 	struct alt_instr *alt = start;
592 
593 	ps->instr = instr_va(start);
594 
595 	/*
596 	 * In case of nested ALTERNATIVE()s the outer alternative might add
597 	 * more padding. To ensure consistent patching find the max padding for
598 	 * all alt_instr entries for this site (nested alternatives result in
599 	 * consecutive entries).
600 	 * Find the last alt_instr eligible for patching at the site.
601 	 */
602 	for (; alt < end && instr_va(alt) == ps->instr; alt++) {
603 		ps->len = max(ps->len, alt->instrlen);
604 
605 		BUG_ON(alt->cpuid >= (NCAPINTS + NBUGINTS) * 32);
606 		/*
607 		 * Patch if either:
608 		 * - feature is present
609 		 * - feature not present but ALT_FLAG_NOT is set to mean,
610 		 *   patch if feature is *NOT* present.
611 		 */
612 		if (!boot_cpu_has(alt->cpuid) != !(alt->flags & ALT_FLAG_NOT))
613 			ps->alt = alt;
614 	}
615 
616 	BUG_ON(ps->len > sizeof(ps->buff));
617 
618 	return alt;
619 }
620 
621 static void __init_or_module prep_patch_site(struct patch_site *ps)
622 {
623 	struct alt_instr *alt = ps->alt;
624 	u8 buff_sz;
625 	u8 *repl;
626 
627 	if (!alt) {
628 		/* Nothing to patch, use original instruction. */
629 		memcpy(ps->buff, ps->instr, ps->len);
630 		return;
631 	}
632 
633 	repl = (u8 *)&alt->repl_offset + alt->repl_offset;
634 	DPRINTK(ALT, "feat: %d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d) flags: 0x%x",
635 		alt->cpuid >> 5, alt->cpuid & 0x1f,
636 		ps->instr, ps->instr, ps->len,
637 		repl, alt->replacementlen, alt->flags);
638 
639 	memcpy(ps->buff, repl, alt->replacementlen);
640 	buff_sz = alt->replacementlen;
641 
642 	if (alt->flags & ALT_FLAG_DIRECT_CALL)
643 		buff_sz = alt_replace_call(ps->instr, ps->buff, alt);
644 
645 	for (; buff_sz < ps->len; buff_sz++)
646 		ps->buff[buff_sz] = 0x90;
647 
648 	__apply_relocation(ps->buff, ps->instr, ps->len, repl, alt->replacementlen);
649 
650 	DUMP_BYTES(ALT, ps->instr, ps->len, "%px:   old_insn: ", ps->instr);
651 	DUMP_BYTES(ALT, repl, alt->replacementlen, "%px:   rpl_insn: ", repl);
652 	DUMP_BYTES(ALT, ps->buff, ps->len, "%px: final_insn: ", ps->instr);
653 }
654 
655 static void __init_or_module patch_site(struct patch_site *ps)
656 {
657 	optimize_nops(ps->instr, ps->buff, ps->len);
658 	text_poke_early(ps->instr, ps->buff, ps->len);
659 }
660 
661 /*
662  * Replace instructions with better alternatives for this CPU type. This runs
663  * before SMP is initialized to avoid SMP problems with self modifying code.
664  * This implies that asymmetric systems where APs have less capabilities than
665  * the boot processor are not handled. Tough. Make sure you disable such
666  * features by hand.
667  *
668  * Marked "noinline" to cause control flow change and thus insn cache
669  * to refetch changed I$ lines.
670  */
671 void __init_or_module noinline apply_alternatives(struct alt_instr *start,
672 						  struct alt_instr *end)
673 {
674 	struct alt_instr *a;
675 
676 	DPRINTK(ALT, "alt table %px, -> %px", start, end);
677 
678 	/*
679 	 * KASAN_SHADOW_START is defined using
680 	 * cpu_feature_enabled(X86_FEATURE_LA57) and is therefore patched here.
681 	 * During the process, KASAN becomes confused seeing partial LA57
682 	 * conversion and triggers a false-positive out-of-bound report.
683 	 *
684 	 * Disable KASAN until the patching is complete.
685 	 */
686 	kasan_disable_current();
687 
688 	/*
689 	 * The scan order should be from start to end. A later scanned
690 	 * alternative code can overwrite previously scanned alternative code.
691 	 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
692 	 * patch code.
693 	 *
694 	 * So be careful if you want to change the scan order to any other
695 	 * order.
696 	 */
697 	a = start;
698 	while (a < end) {
699 		struct patch_site ps = {
700 			.alt = NULL,
701 			.len = 0
702 		};
703 
704 		a = analyze_patch_site(&ps, a, end);
705 		prep_patch_site(&ps);
706 		patch_site(&ps);
707 	}
708 
709 	kasan_enable_current();
710 }
711 
712 static inline bool is_jcc32(struct insn *insn)
713 {
714 	/* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
715 	return insn->opcode.bytes[0] == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80;
716 }
717 
718 #if defined(CONFIG_MITIGATION_RETPOLINE) && defined(CONFIG_OBJTOOL)
719 
720 /*
721  * [CS]{,3} CALL/JMP *%\reg [INT3]*
722  */
723 static int emit_indirect(int op, int reg, u8 *bytes, int len)
724 {
725 	int cs = 0, bp = 0;
726 	int i = 0;
727 	u8 modrm;
728 
729 	/*
730 	 * Set @len to the excess bytes after writing the instruction.
731 	 */
732 	len -= 2 + (reg >= 8);
733 	WARN_ON_ONCE(len < 0);
734 
735 	switch (op) {
736 	case CALL_INSN_OPCODE:
737 		modrm = 0x10; /* Reg = 2; CALL r/m */
738 		/*
739 		 * Additional NOP is better than prefix decode penalty.
740 		 */
741 		if (len <= 3)
742 			cs = len;
743 		break;
744 
745 	case JMP32_INSN_OPCODE:
746 		modrm = 0x20; /* Reg = 4; JMP r/m */
747 		bp = len;
748 		break;
749 
750 	default:
751 		WARN_ON_ONCE(1);
752 		return -1;
753 	}
754 
755 	while (cs--)
756 		bytes[i++] = 0x2e; /* CS-prefix */
757 
758 	if (reg >= 8) {
759 		bytes[i++] = 0x41; /* REX.B prefix */
760 		reg -= 8;
761 	}
762 
763 	modrm |= 0xc0; /* Mod = 3 */
764 	modrm += reg;
765 
766 	bytes[i++] = 0xff; /* opcode */
767 	bytes[i++] = modrm;
768 
769 	while (bp--)
770 		bytes[i++] = 0xcc; /* INT3 */
771 
772 	return i;
773 }
774 
775 static int __emit_trampoline(void *addr, struct insn *insn, u8 *bytes,
776 			     void *call_dest, void *jmp_dest)
777 {
778 	u8 op = insn->opcode.bytes[0];
779 	int i = 0;
780 
781 	/*
782 	 * Clang does 'weird' Jcc __x86_indirect_thunk_r11 conditional
783 	 * tail-calls. Deal with them.
784 	 */
785 	if (is_jcc32(insn)) {
786 		bytes[i++] = op;
787 		op = insn->opcode.bytes[1];
788 		goto clang_jcc;
789 	}
790 
791 	if (insn->length == 6)
792 		bytes[i++] = 0x2e; /* CS-prefix */
793 
794 	switch (op) {
795 	case CALL_INSN_OPCODE:
796 		__text_gen_insn(bytes+i, op, addr+i,
797 				call_dest,
798 				CALL_INSN_SIZE);
799 		i += CALL_INSN_SIZE;
800 		break;
801 
802 	case JMP32_INSN_OPCODE:
803 clang_jcc:
804 		__text_gen_insn(bytes+i, op, addr+i,
805 				jmp_dest,
806 				JMP32_INSN_SIZE);
807 		i += JMP32_INSN_SIZE;
808 		break;
809 
810 	default:
811 		WARN(1, "%pS %px %*ph\n", addr, addr, 6, addr);
812 		return -1;
813 	}
814 
815 	WARN_ON_ONCE(i != insn->length);
816 
817 	return i;
818 }
819 
820 static int emit_call_track_retpoline(void *addr, struct insn *insn, int reg, u8 *bytes)
821 {
822 	return __emit_trampoline(addr, insn, bytes,
823 				 __x86_indirect_call_thunk_array[reg],
824 				 __x86_indirect_jump_thunk_array[reg]);
825 }
826 
827 #ifdef CONFIG_MITIGATION_ITS
828 static int emit_its_trampoline(void *addr, struct insn *insn, int reg, u8 *bytes)
829 {
830 	u8 *thunk = __x86_indirect_its_thunk_array[reg];
831 	u8 *tmp = its_allocate_thunk(reg);
832 
833 	if (tmp)
834 		thunk = tmp;
835 
836 	return __emit_trampoline(addr, insn, bytes, thunk, thunk);
837 }
838 
839 /* Check if an indirect branch is at ITS-unsafe address */
840 static bool cpu_wants_indirect_its_thunk_at(unsigned long addr, int reg)
841 {
842 	if (!cpu_feature_enabled(X86_FEATURE_INDIRECT_THUNK_ITS))
843 		return false;
844 
845 	/* Indirect branch opcode is 2 or 3 bytes depending on reg */
846 	addr += 1 + reg / 8;
847 
848 	/* Lower-half of the cacheline? */
849 	return !(addr & 0x20);
850 }
851 #else /* CONFIG_MITIGATION_ITS */
852 
853 #ifdef CONFIG_FINEIBT
854 static bool cpu_wants_indirect_its_thunk_at(unsigned long addr, int reg)
855 {
856 	return false;
857 }
858 #endif
859 
860 #endif /* CONFIG_MITIGATION_ITS */
861 
862 /*
863  * Rewrite the compiler generated retpoline thunk calls.
864  *
865  * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
866  * indirect instructions, avoiding the extra indirection.
867  *
868  * For example, convert:
869  *
870  *   CALL __x86_indirect_thunk_\reg
871  *
872  * into:
873  *
874  *   CALL *%\reg
875  *
876  * It also tries to inline spectre_v2=retpoline,lfence when size permits.
877  */
878 static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
879 {
880 	retpoline_thunk_t *target;
881 	int reg, ret, i = 0;
882 	u8 op, cc;
883 
884 	target = addr + insn->length + insn->immediate.value;
885 	reg = target - __x86_indirect_thunk_array;
886 
887 	if (WARN_ON_ONCE(reg & ~0xf))
888 		return -1;
889 
890 	/* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
891 	BUG_ON(reg == 4);
892 
893 	if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
894 	    !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
895 		if (cpu_feature_enabled(X86_FEATURE_CALL_DEPTH))
896 			return emit_call_track_retpoline(addr, insn, reg, bytes);
897 
898 		return -1;
899 	}
900 
901 	op = insn->opcode.bytes[0];
902 
903 	/*
904 	 * Convert:
905 	 *
906 	 *   Jcc.d32 __x86_indirect_thunk_\reg
907 	 *
908 	 * into:
909 	 *
910 	 *   Jncc.d8 1f
911 	 *   [ LFENCE ]
912 	 *   JMP *%\reg
913 	 *   [ NOP ]
914 	 * 1:
915 	 */
916 	if (is_jcc32(insn)) {
917 		cc = insn->opcode.bytes[1] & 0xf;
918 		cc ^= 1; /* invert condition */
919 
920 		bytes[i++] = 0x70 + cc;        /* Jcc.d8 */
921 		bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
922 
923 		/* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
924 		op = JMP32_INSN_OPCODE;
925 	}
926 
927 	/*
928 	 * For RETPOLINE_LFENCE: prepend the indirect CALL/JMP with an LFENCE.
929 	 */
930 	if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
931 		bytes[i++] = 0x0f;
932 		bytes[i++] = 0xae;
933 		bytes[i++] = 0xe8; /* LFENCE */
934 	}
935 
936 #ifdef CONFIG_MITIGATION_ITS
937 	/*
938 	 * Check if the address of last byte of emitted-indirect is in
939 	 * lower-half of the cacheline. Such branches need ITS mitigation.
940 	 */
941 	if (cpu_wants_indirect_its_thunk_at((unsigned long)addr + i, reg))
942 		return emit_its_trampoline(addr, insn, reg, bytes);
943 #endif
944 
945 	ret = emit_indirect(op, reg, bytes + i, insn->length - i);
946 	if (ret < 0)
947 		return ret;
948 	i += ret;
949 
950 	for (; i < insn->length;)
951 		bytes[i++] = BYTES_NOP1;
952 
953 	return i;
954 }
955 
956 /*
957  * Generated by 'objtool --retpoline'.
958  */
959 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
960 {
961 	s32 *s;
962 
963 	for (s = start; s < end; s++) {
964 		void *addr = (void *)s + *s;
965 		struct insn insn;
966 		int len, ret;
967 		u8 bytes[16];
968 		u8 op1, op2;
969 		u8 *dest;
970 
971 		ret = insn_decode_kernel(&insn, addr);
972 		if (WARN_ON_ONCE(ret < 0))
973 			continue;
974 
975 		op1 = insn.opcode.bytes[0];
976 		op2 = insn.opcode.bytes[1];
977 
978 		switch (op1) {
979 		case 0x70 ... 0x7f:	/* Jcc.d8 */
980 			/* See cfi_paranoid. */
981 			WARN_ON_ONCE(cfi_mode != CFI_FINEIBT);
982 			continue;
983 
984 		case CALL_INSN_OPCODE:
985 		case JMP32_INSN_OPCODE:
986 			/* Check for cfi_paranoid + ITS */
987 			dest = addr + insn.length + insn.immediate.value;
988 			if (dest[-1] == 0xd6 && (dest[0] & 0xf0) == 0x70) {
989 				WARN_ON_ONCE(cfi_mode != CFI_FINEIBT);
990 				continue;
991 			}
992 			break;
993 
994 		case 0x0f: /* escape */
995 			if (op2 >= 0x80 && op2 <= 0x8f)
996 				break;
997 			fallthrough;
998 		default:
999 			WARN_ON_ONCE(1);
1000 			continue;
1001 		}
1002 
1003 		DPRINTK(RETPOLINE, "retpoline at: %pS (%px) len: %d to: %pS",
1004 			addr, addr, insn.length,
1005 			addr + insn.length + insn.immediate.value);
1006 
1007 		len = patch_retpoline(addr, &insn, bytes);
1008 		if (len == insn.length) {
1009 			optimize_nops(addr, bytes, len);
1010 			DUMP_BYTES(RETPOLINE, ((u8*)addr),  len, "%px: orig: ", addr);
1011 			DUMP_BYTES(RETPOLINE, ((u8*)bytes), len, "%px: repl: ", addr);
1012 			text_poke_early(addr, bytes, len);
1013 		}
1014 	}
1015 }
1016 
1017 #ifdef CONFIG_MITIGATION_RETHUNK
1018 
1019 bool cpu_wants_rethunk(void)
1020 {
1021 	return cpu_feature_enabled(X86_FEATURE_RETHUNK);
1022 }
1023 
1024 bool cpu_wants_rethunk_at(void *addr)
1025 {
1026 	if (!cpu_feature_enabled(X86_FEATURE_RETHUNK))
1027 		return false;
1028 	if (x86_return_thunk != its_return_thunk)
1029 		return true;
1030 
1031 	return !((unsigned long)addr & 0x20);
1032 }
1033 
1034 /*
1035  * Rewrite the compiler generated return thunk tail-calls.
1036  *
1037  * For example, convert:
1038  *
1039  *   JMP __x86_return_thunk
1040  *
1041  * into:
1042  *
1043  *   RET
1044  */
1045 static int patch_return(void *addr, struct insn *insn, u8 *bytes)
1046 {
1047 	int i = 0;
1048 
1049 	/* Patch the custom return thunks... */
1050 	if (cpu_wants_rethunk_at(addr)) {
1051 		i = JMP32_INSN_SIZE;
1052 		__text_gen_insn(bytes, JMP32_INSN_OPCODE, addr, x86_return_thunk, i);
1053 	} else {
1054 		/* ... or patch them out if not needed. */
1055 		bytes[i++] = RET_INSN_OPCODE;
1056 	}
1057 
1058 	for (; i < insn->length;)
1059 		bytes[i++] = INT3_INSN_OPCODE;
1060 	return i;
1061 }
1062 
1063 void __init_or_module noinline apply_returns(s32 *start, s32 *end)
1064 {
1065 	s32 *s;
1066 
1067 	if (cpu_wants_rethunk())
1068 		static_call_force_reinit();
1069 
1070 	for (s = start; s < end; s++) {
1071 		void *dest = NULL, *addr = (void *)s + *s;
1072 		struct insn insn;
1073 		int len, ret;
1074 		u8 bytes[16];
1075 		u8 op;
1076 
1077 		ret = insn_decode_kernel(&insn, addr);
1078 		if (WARN_ON_ONCE(ret < 0))
1079 			continue;
1080 
1081 		op = insn.opcode.bytes[0];
1082 		if (op == JMP32_INSN_OPCODE)
1083 			dest = addr + insn.length + insn.immediate.value;
1084 
1085 		if (__static_call_fixup(addr, op, dest) ||
1086 		    WARN_ONCE(dest != &__x86_return_thunk,
1087 			      "missing return thunk: %pS-%pS: %*ph",
1088 			      addr, dest, 5, addr))
1089 			continue;
1090 
1091 		DPRINTK(RET, "return thunk at: %pS (%px) len: %d to: %pS",
1092 			addr, addr, insn.length,
1093 			addr + insn.length + insn.immediate.value);
1094 
1095 		len = patch_return(addr, &insn, bytes);
1096 		if (len == insn.length) {
1097 			DUMP_BYTES(RET, ((u8*)addr),  len, "%px: orig: ", addr);
1098 			DUMP_BYTES(RET, ((u8*)bytes), len, "%px: repl: ", addr);
1099 			text_poke_early(addr, bytes, len);
1100 		}
1101 	}
1102 }
1103 #else /* !CONFIG_MITIGATION_RETHUNK: */
1104 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
1105 #endif /* !CONFIG_MITIGATION_RETHUNK */
1106 
1107 #else /* !CONFIG_MITIGATION_RETPOLINE || !CONFIG_OBJTOOL */
1108 
1109 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
1110 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
1111 
1112 #endif /* !CONFIG_MITIGATION_RETPOLINE || !CONFIG_OBJTOOL */
1113 
1114 #ifdef CONFIG_X86_KERNEL_IBT
1115 
1116 __noendbr bool is_endbr(u32 *val)
1117 {
1118 	u32 endbr;
1119 
1120 	__get_kernel_nofault(&endbr, val, u32, Efault);
1121 	return __is_endbr(endbr);
1122 
1123 Efault:
1124 	return false;
1125 }
1126 
1127 #ifdef CONFIG_FINEIBT
1128 
1129 static __noendbr bool exact_endbr(u32 *val)
1130 {
1131 	u32 endbr;
1132 
1133 	__get_kernel_nofault(&endbr, val, u32, Efault);
1134 	return endbr == gen_endbr();
1135 
1136 Efault:
1137 	return false;
1138 }
1139 
1140 #endif
1141 
1142 static void poison_cfi(void *addr);
1143 
1144 static void __init_or_module poison_endbr(void *addr)
1145 {
1146 	u32 poison = gen_endbr_poison();
1147 
1148 	if (WARN_ON_ONCE(!is_endbr(addr)))
1149 		return;
1150 
1151 	DPRINTK(ENDBR, "ENDBR at: %pS (%px)", addr, addr);
1152 
1153 	/*
1154 	 * When we have IBT, the lack of ENDBR will trigger #CP
1155 	 */
1156 	DUMP_BYTES(ENDBR, ((u8*)addr), 4, "%px: orig: ", addr);
1157 	DUMP_BYTES(ENDBR, ((u8*)&poison), 4, "%px: repl: ", addr);
1158 	text_poke_early(addr, &poison, 4);
1159 }
1160 
1161 /*
1162  * Generated by: objtool --ibt
1163  *
1164  * Seal the functions for indirect calls by clobbering the ENDBR instructions
1165  * and the kCFI hash value.
1166  */
1167 void __init_or_module noinline apply_seal_endbr(s32 *start, s32 *end)
1168 {
1169 	s32 *s;
1170 
1171 	for (s = start; s < end; s++) {
1172 		void *addr = (void *)s + *s;
1173 
1174 		poison_endbr(addr);
1175 		if (IS_ENABLED(CONFIG_FINEIBT))
1176 			poison_cfi(addr - CFI_OFFSET);
1177 	}
1178 }
1179 
1180 #else /* !CONFIG_X86_KERNEL_IBT: */
1181 
1182 void __init_or_module apply_seal_endbr(s32 *start, s32 *end) { }
1183 
1184 #endif /* !CONFIG_X86_KERNEL_IBT */
1185 
1186 #ifdef CONFIG_CFI_AUTO_DEFAULT
1187 # define __CFI_DEFAULT CFI_AUTO
1188 #elif defined(CONFIG_CFI)
1189 # define __CFI_DEFAULT CFI_KCFI
1190 #else
1191 # define __CFI_DEFAULT CFI_OFF
1192 #endif
1193 
1194 enum cfi_mode cfi_mode __ro_after_init = __CFI_DEFAULT;
1195 static bool cfi_debug __ro_after_init;
1196 
1197 #ifdef CONFIG_FINEIBT_BHI
1198 bool cfi_bhi __ro_after_init = false;
1199 #endif
1200 
1201 #ifdef CONFIG_CFI
1202 u32 cfi_get_func_hash(void *func)
1203 {
1204 	u32 hash;
1205 
1206 	func -= cfi_get_offset();
1207 	switch (cfi_mode) {
1208 	case CFI_FINEIBT:
1209 		func += 7;
1210 		break;
1211 	case CFI_KCFI:
1212 		func += 1;
1213 		break;
1214 	default:
1215 		return 0;
1216 	}
1217 
1218 	if (get_kernel_nofault(hash, func))
1219 		return 0;
1220 
1221 	return hash;
1222 }
1223 
1224 int cfi_get_func_arity(void *func)
1225 {
1226 	bhi_thunk *target;
1227 	s32 disp;
1228 
1229 	if (cfi_mode != CFI_FINEIBT && !cfi_bhi)
1230 		return 0;
1231 
1232 	if (get_kernel_nofault(disp, func - 4))
1233 		return 0;
1234 
1235 	target = func + disp;
1236 	return target - __bhi_args;
1237 }
1238 #endif
1239 
1240 #ifdef CONFIG_FINEIBT
1241 
1242 static bool cfi_rand __ro_after_init = true;
1243 static u32  cfi_seed __ro_after_init;
1244 
1245 /*
1246  * Re-hash the CFI hash with a boot-time seed while making sure the result is
1247  * not a valid ENDBR instruction.
1248  */
1249 static u32 cfi_rehash(u32 hash)
1250 {
1251 	hash ^= cfi_seed;
1252 	while (unlikely(__is_endbr(hash) || __is_endbr(-hash))) {
1253 		bool lsb = hash & 1;
1254 		hash >>= 1;
1255 		if (lsb)
1256 			hash ^= 0x80200003;
1257 	}
1258 	return hash;
1259 }
1260 
1261 static __init int cfi_parse_cmdline(char *str)
1262 {
1263 	if (!str)
1264 		return -EINVAL;
1265 
1266 	while (str) {
1267 		char *next = strchr(str, ',');
1268 		if (next) {
1269 			*next = 0;
1270 			next++;
1271 		}
1272 
1273 		if (!strcmp(str, "auto")) {
1274 			cfi_mode = CFI_AUTO;
1275 		} else if (!strcmp(str, "off")) {
1276 			cfi_mode = CFI_OFF;
1277 			cfi_rand = false;
1278 		} else if (!strcmp(str, "debug")) {
1279 			cfi_debug = true;
1280 		} else if (!strcmp(str, "kcfi")) {
1281 			cfi_mode = CFI_KCFI;
1282 		} else if (!strcmp(str, "fineibt")) {
1283 			cfi_mode = CFI_FINEIBT;
1284 		} else if (!strcmp(str, "norand")) {
1285 			cfi_rand = false;
1286 		} else if (!strcmp(str, "warn")) {
1287 			pr_alert("CFI: mismatch non-fatal!\n");
1288 			cfi_warn = true;
1289 		} else if (!strcmp(str, "paranoid")) {
1290 			if (cfi_mode == CFI_FINEIBT) {
1291 				cfi_paranoid = true;
1292 			} else {
1293 				pr_err("CFI: ignoring paranoid; depends on fineibt.\n");
1294 			}
1295 		} else if (!strcmp(str, "bhi")) {
1296 #ifdef CONFIG_FINEIBT_BHI
1297 			if (cfi_mode == CFI_FINEIBT) {
1298 				cfi_bhi = true;
1299 			} else {
1300 				pr_err("CFI: ignoring bhi; depends on fineibt.\n");
1301 			}
1302 #else
1303 			pr_err("CFI: ignoring bhi; depends on FINEIBT_BHI=y.\n");
1304 #endif
1305 		} else {
1306 			pr_err("CFI: Ignoring unknown option (%s).", str);
1307 		}
1308 
1309 		str = next;
1310 	}
1311 
1312 	return 0;
1313 }
1314 early_param("cfi", cfi_parse_cmdline);
1315 
1316 /*
1317  * kCFI						FineIBT
1318  *
1319  * __cfi_\func:					__cfi_\func:
1320  *	movl   $0x12345678,%eax		// 5	     endbr64			// 4
1321  *	nop					     subl   $0x12345678,%eax    // 5
1322  *	nop					     jne.d32,pn \func+3		// 7
1323  *	nop
1324  *	nop
1325  *	nop
1326  *	nop
1327  *	nop
1328  *	nop
1329  *	nop
1330  *	nop
1331  *	nop
1332  * \func:					\func:
1333  *	endbr64					     nopl -42(%rax)
1334  *
1335  *
1336  * caller:					caller:
1337  *	movl	$(-0x12345678),%r10d	 // 6	     movl   $0x12345678,%eax	// 5
1338  *	addl	$-15(%r11),%r10d	 // 4	     lea    -0x10(%r11),%r11	// 4
1339  *	je	1f			 // 2	     nop5			// 5
1340  *	ud2				 // 2
1341  * 1:	cs call	__x86_indirect_thunk_r11 // 6	     call   *%r11; nop3;	// 6
1342  *
1343  *
1344  * Notably, the FineIBT sequences are crafted such that branches are presumed
1345  * non-taken. This is based on Agner Fog's optimization manual, which states:
1346  *
1347  *  "Make conditional jumps most often not taken: The efficiency and throughput
1348  *   for not-taken branches is better than for taken branches on most
1349  *   processors. Therefore, it is good to place the most frequent branch first"
1350  *
1351  * NOTE: Update the kCFI caller sequence to make use of this observation:
1352  *
1353  * kCFI						kCFI-OPT
1354  *
1355  * caller:					caller:
1356  *	movl	$(-0x12345678),%r10d	 // 6	     movl	$(-0x12345678),%r10d	 // 6
1357  *	addl	$-15(%r11),%r10d	 // 4	     addl	$-15(%r11),%r10d	 // 4
1358  *	je	1f			 // 2	     jne	. + 3                    // 2
1359  *	ud2				 // 2        test	$0xd6, %al		 // 2
1360  * 1:	cs call	__x86_indirect_thunk_r11 // 6	1:   cs call	__x86_indirect_thunk_r11 // 6
1361  *
1362  * This new test clobbers eflags, but those are clobbered by the hash test
1363  * anyway.
1364  */
1365 
1366 /*
1367  * <fineibt_preamble_start>:
1368  *  0:   f3 0f 1e fa             endbr64
1369  *  4:   2d 78 56 34 12          sub    $0x12345678, %eax
1370  *  9:   2e 0f 85 03 00 00 00    jne,pn 13 <fineibt_preamble_start+0x13>
1371  * 10:   0f 1f 40 d6             nopl   -0x2a(%rax)
1372  *
1373  * Note that the JNE target is the 0xD6 byte inside the NOPL, this decodes as
1374  * UDB on x86_64 and raises #UD.
1375  */
1376 asm(	".pushsection .rodata				\n"
1377 	"fineibt_preamble_start:			\n"
1378 	"	endbr64					\n"
1379 	"	subl	$0x12345678, %eax		\n"
1380 	"fineibt_preamble_bhi:				\n"
1381 	"	cs jne.d32 fineibt_preamble_start+0x13	\n"
1382 	"#fineibt_func:					\n"
1383 	"	nopl	-42(%rax)			\n"
1384 	"fineibt_preamble_end:				\n"
1385 	".popsection\n"
1386 );
1387 
1388 extern u8 fineibt_preamble_start[];
1389 extern u8 fineibt_preamble_bhi[];
1390 extern u8 fineibt_preamble_end[];
1391 
1392 #define fineibt_preamble_size (fineibt_preamble_end - fineibt_preamble_start)
1393 #define fineibt_preamble_bhi  (fineibt_preamble_bhi - fineibt_preamble_start)
1394 #define fineibt_preamble_ud   0x13
1395 #define fineibt_preamble_hash 5
1396 
1397 #define fineibt_prefix_size (fineibt_preamble_size - ENDBR_INSN_SIZE)
1398 
1399 /*
1400  * <fineibt_caller_start>:
1401  *  0:   b8 78 56 34 12          mov    $0x12345678, %eax
1402  *  5:   4d 8d 5b f0             lea    -0x10(%r11), %r11
1403  *  9:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)
1404  */
1405 asm(	".pushsection .rodata			\n"
1406 	"fineibt_caller_start:			\n"
1407 	"	movl	$0x12345678, %eax	\n"
1408 	"	lea	-0x10(%r11), %r11	\n"
1409 	ASM_NOP5
1410 	"fineibt_caller_end:			\n"
1411 	".popsection				\n"
1412 );
1413 
1414 extern u8 fineibt_caller_start[];
1415 extern u8 fineibt_caller_end[];
1416 
1417 #define fineibt_caller_size (fineibt_caller_end - fineibt_caller_start)
1418 #define fineibt_caller_hash 1
1419 
1420 #define fineibt_caller_jmp (fineibt_caller_size - 2)
1421 
1422 /*
1423  * Since FineIBT does hash validation on the callee side it is prone to
1424  * circumvention attacks where a 'naked' ENDBR instruction exists that
1425  * is not part of the fineibt_preamble sequence.
1426  *
1427  * Notably the x86 entry points must be ENDBR and equally cannot be
1428  * fineibt_preamble.
1429  *
1430  * The fineibt_paranoid caller sequence adds additional caller side
1431  * hash validation. This stops such circumvention attacks dead, but at the cost
1432  * of adding a load.
1433  *
1434  * <fineibt_paranoid_start>:
1435  *  0:   b8 78 56 34 12          mov    $0x12345678, %eax
1436  *  5:   41 3b 43 f5             cmp    -0x11(%r11), %eax
1437  *  9:   2e 4d 8d 5b <f0>        cs lea -0x10(%r11), %r11
1438  *  e:   75 fd                   jne    d <fineibt_paranoid_start+0xd>
1439  * 10:   41 ff d3                call   *%r11
1440  * 13:   90                      nop
1441  *
1442  * Notably LEA does not modify flags and can be reordered with the CMP,
1443  * avoiding a dependency. Again, using a non-taken (backwards) branch
1444  * for the failure case, abusing LEA's immediate 0xf0 as LOCK prefix for the
1445  * Jcc.d8, causing #UD.
1446  */
1447 asm(	".pushsection .rodata				\n"
1448 	"fineibt_paranoid_start:			\n"
1449 	"	mov	$0x12345678, %eax		\n"
1450 	"	cmpl	-11(%r11), %eax			\n"
1451 	"	cs lea	-0x10(%r11), %r11		\n"
1452 	"#fineibt_caller_size:                          \n"
1453 	"	jne	fineibt_paranoid_start+0xd	\n"
1454 	"fineibt_paranoid_ind:				\n"
1455 	"	cs call	*%r11				\n"
1456 	"fineibt_paranoid_end:				\n"
1457 	".popsection					\n"
1458 );
1459 
1460 extern u8 fineibt_paranoid_start[];
1461 extern u8 fineibt_paranoid_ind[];
1462 extern u8 fineibt_paranoid_end[];
1463 
1464 #define fineibt_paranoid_size (fineibt_paranoid_end - fineibt_paranoid_start)
1465 #define fineibt_paranoid_ind  (fineibt_paranoid_ind - fineibt_paranoid_start)
1466 #define fineibt_paranoid_ud   0xd
1467 
1468 static u32 decode_preamble_hash(void *addr, int *reg)
1469 {
1470 	u8 *p = addr;
1471 
1472 	/* b8+reg 78 56 34 12          movl    $0x12345678,\reg */
1473 	if (p[0] >= 0xb8 && p[0] < 0xc0) {
1474 		if (reg)
1475 			*reg = p[0] - 0xb8;
1476 		return *(u32 *)(addr + 1);
1477 	}
1478 
1479 	return 0; /* invalid hash value */
1480 }
1481 
1482 static u32 decode_caller_hash(void *addr)
1483 {
1484 	u8 *p = addr;
1485 
1486 	/* 41 ba 88 a9 cb ed       mov    $(-0x12345678),%r10d */
1487 	if (p[0] == 0x41 && p[1] == 0xba)
1488 		return -*(u32 *)(addr + 2);
1489 
1490 	/* e8 0c 88 a9 cb ed	   jmp.d8  +12 */
1491 	if (p[0] == JMP8_INSN_OPCODE && p[1] == fineibt_caller_jmp)
1492 		return -*(u32 *)(addr + 2);
1493 
1494 	return 0; /* invalid hash value */
1495 }
1496 
1497 /* .retpoline_sites */
1498 static int cfi_disable_callers(s32 *start, s32 *end)
1499 {
1500 	/*
1501 	 * Disable kCFI by patching in a JMP.d8, this leaves the hash immediate
1502 	 * in tact for later usage. Also see decode_caller_hash() and
1503 	 * cfi_rewrite_callers().
1504 	 */
1505 	const u8 jmp[] = { JMP8_INSN_OPCODE, fineibt_caller_jmp };
1506 	s32 *s;
1507 
1508 	for (s = start; s < end; s++) {
1509 		void *addr = (void *)s + *s;
1510 		u32 hash;
1511 
1512 		addr -= fineibt_caller_size;
1513 		hash = decode_caller_hash(addr);
1514 		if (!hash) /* nocfi callers */
1515 			continue;
1516 
1517 		text_poke_early(addr, jmp, 2);
1518 	}
1519 
1520 	return 0;
1521 }
1522 
1523 static int cfi_enable_callers(s32 *start, s32 *end)
1524 {
1525 	/*
1526 	 * Re-enable (and update) kCFI, undo what cfi_disable_callers() did.
1527 	 */
1528 	const u8 udne[] = { 0x75, 0x01, 0xa8, 0xd6 };
1529 	const u8 mov[] = { 0x41, 0xba };
1530 	s32 *s;
1531 
1532 	for (s = start; s < end; s++) {
1533 		void *addr = (void *)s + *s;
1534 		u32 hash;
1535 
1536 		addr -= fineibt_caller_size;
1537 		hash = decode_caller_hash(addr);
1538 		if (!hash) /* nocfi callers */
1539 			continue;
1540 
1541 		/*
1542 		 * See the kCFI/FineIBT comment above -- update note.
1543 		 */
1544 		text_poke_early(addr + 10, udne, 4);
1545 		text_poke_early(addr, mov, 2);
1546 	}
1547 
1548 	return 0;
1549 }
1550 
1551 /* .cfi_sites */
1552 static int cfi_rand_preamble(s32 *start, s32 *end)
1553 {
1554 	s32 *s;
1555 
1556 	for (s = start; s < end; s++) {
1557 		void *addr = (void *)s + *s;
1558 		u32 hash;
1559 
1560 		hash = decode_preamble_hash(addr, NULL);
1561 		if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1562 			 addr, addr, 5, addr))
1563 			return -EINVAL;
1564 
1565 		hash = cfi_rehash(hash);
1566 		text_poke_early(addr + 1, &hash, 4);
1567 	}
1568 
1569 	return 0;
1570 }
1571 
1572 /*
1573  * Inline the bhi-arity 1 case:
1574  *
1575  * __cfi_foo:
1576  *  0: f3 0f 1e fa             endbr64
1577  *  4: 2d 78 56 34 12          sub    $0x12345678, %eax
1578  *  9: 49 0f 45 fa             cmovne %rax, %rdi
1579  *  d: 2e 75 03                jne,pn    foo+0x3
1580  *
1581  * foo:
1582  * 10: 0f 1f 40 <d6>           nopl -42(%rax)
1583  *
1584  * Notably, this scheme is incompatible with permissive CFI
1585  * because the CMOVcc is unconditional and RDI will have been
1586  * clobbered.
1587  */
1588 asm(	".pushsection .rodata				\n"
1589 	"fineibt_bhi1_start:				\n"
1590 	"	cmovne %rax, %rdi			\n"
1591 	"	cs jne fineibt_bhi1_func + 0x3		\n"
1592 	"fineibt_bhi1_func:				\n"
1593 	"	nopl -42(%rax)				\n"
1594 	"fineibt_bhi1_end:				\n"
1595 	".popsection					\n"
1596 );
1597 
1598 extern u8 fineibt_bhi1_start[];
1599 extern u8 fineibt_bhi1_end[];
1600 
1601 #define fineibt_bhi1_size (fineibt_bhi1_end - fineibt_bhi1_start)
1602 
1603 static void cfi_fineibt_bhi_preamble(void *addr, int arity)
1604 {
1605 	u8 bytes[MAX_INSN_SIZE];
1606 
1607 	if (!arity)
1608 		return;
1609 
1610 	if (!cfi_warn && arity == 1) {
1611 		text_poke_early(addr + fineibt_preamble_bhi,
1612 				fineibt_bhi1_start, fineibt_bhi1_size);
1613 		return;
1614 	}
1615 
1616 	/*
1617 	 * Replace the bytes at fineibt_preamble_bhi with a CALL instruction
1618 	 * that lines up exactly with the end of the preamble, such that the
1619 	 * return address will be foo+0.
1620 	 *
1621 	 * __cfi_foo:
1622 	 *  0: f3 0f 1e fa             endbr64
1623 	 *  4: 2d 78 56 34 12          sub    $0x12345678, %eax
1624 	 *  9: 2e 2e e8 DD DD DD DD    cs cs call __bhi_args[arity]
1625 	 */
1626 	bytes[0] = 0x2e;
1627 	bytes[1] = 0x2e;
1628 	__text_gen_insn(bytes + 2, CALL_INSN_OPCODE,
1629 			addr + fineibt_preamble_bhi + 2,
1630 			__bhi_args[arity], CALL_INSN_SIZE);
1631 
1632 	text_poke_early(addr + fineibt_preamble_bhi, bytes, 7);
1633 }
1634 
1635 static int cfi_rewrite_preamble(s32 *start, s32 *end)
1636 {
1637 	s32 *s;
1638 
1639 	for (s = start; s < end; s++) {
1640 		void *addr = (void *)s + *s;
1641 		int arity;
1642 		u32 hash;
1643 
1644 		/*
1645 		 * When the function doesn't start with ENDBR the compiler will
1646 		 * have determined there are no indirect calls to it and we
1647 		 * don't need no CFI either.
1648 		 */
1649 		if (!is_endbr(addr + CFI_OFFSET))
1650 			continue;
1651 
1652 		hash = decode_preamble_hash(addr, &arity);
1653 		if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1654 			 addr, addr, 5, addr))
1655 			return -EINVAL;
1656 
1657 		/*
1658 		 * FineIBT relies on being at func-16, so if the preamble is
1659 		 * actually larger than that, place it the tail end.
1660 		 *
1661 		 * NOTE: this is possible with things like DEBUG_CALL_THUNKS
1662 		 * and DEBUG_FORCE_FUNCTION_ALIGN_64B.
1663 		 */
1664 		addr += CFI_OFFSET - fineibt_prefix_size;
1665 
1666 		text_poke_early(addr, fineibt_preamble_start, fineibt_preamble_size);
1667 		WARN_ON(*(u32 *)(addr + fineibt_preamble_hash) != 0x12345678);
1668 		text_poke_early(addr + fineibt_preamble_hash, &hash, 4);
1669 
1670 		WARN_ONCE(!IS_ENABLED(CONFIG_FINEIBT_BHI) && arity,
1671 			  "kCFI preamble has wrong register at: %pS %*ph\n",
1672 			  addr, 5, addr);
1673 
1674 		if (cfi_bhi)
1675 			cfi_fineibt_bhi_preamble(addr, arity);
1676 	}
1677 
1678 	return 0;
1679 }
1680 
1681 static void cfi_rewrite_endbr(s32 *start, s32 *end)
1682 {
1683 	s32 *s;
1684 
1685 	for (s = start; s < end; s++) {
1686 		void *addr = (void *)s + *s;
1687 
1688 		if (!exact_endbr(addr + CFI_OFFSET))
1689 			continue;
1690 
1691 		poison_endbr(addr + CFI_OFFSET);
1692 	}
1693 }
1694 
1695 /* .retpoline_sites */
1696 static int cfi_rand_callers(s32 *start, s32 *end)
1697 {
1698 	s32 *s;
1699 
1700 	for (s = start; s < end; s++) {
1701 		void *addr = (void *)s + *s;
1702 		u32 hash;
1703 
1704 		addr -= fineibt_caller_size;
1705 		hash = decode_caller_hash(addr);
1706 		if (hash) {
1707 			hash = -cfi_rehash(hash);
1708 			text_poke_early(addr + 2, &hash, 4);
1709 		}
1710 	}
1711 
1712 	return 0;
1713 }
1714 
1715 static int emit_paranoid_trampoline(void *addr, struct insn *insn, int reg, u8 *bytes)
1716 {
1717 	u8 *thunk = (void *)__x86_indirect_its_thunk_array[reg] - 2;
1718 
1719 #ifdef CONFIG_MITIGATION_ITS
1720 	u8 *tmp = its_allocate_thunk(reg);
1721 	if (tmp)
1722 		thunk = tmp;
1723 #endif
1724 
1725 	return __emit_trampoline(addr, insn, bytes, thunk, thunk);
1726 }
1727 
1728 static int cfi_rewrite_callers(s32 *start, s32 *end)
1729 {
1730 	s32 *s;
1731 
1732 	for (s = start; s < end; s++) {
1733 		void *addr = (void *)s + *s;
1734 		struct insn insn;
1735 		u8 bytes[20];
1736 		u32 hash;
1737 		int ret;
1738 		u8 op;
1739 
1740 		addr -= fineibt_caller_size;
1741 		hash = decode_caller_hash(addr);
1742 		if (!hash)
1743 			continue;
1744 
1745 		if (!cfi_paranoid) {
1746 			text_poke_early(addr, fineibt_caller_start, fineibt_caller_size);
1747 			WARN_ON(*(u32 *)(addr + fineibt_caller_hash) != 0x12345678);
1748 			text_poke_early(addr + fineibt_caller_hash, &hash, 4);
1749 			/* rely on apply_retpolines() */
1750 			continue;
1751 		}
1752 
1753 		/* cfi_paranoid */
1754 		ret = insn_decode_kernel(&insn, addr + fineibt_caller_size);
1755 		if (WARN_ON_ONCE(ret < 0))
1756 			continue;
1757 
1758 		op = insn.opcode.bytes[0];
1759 		if (op != CALL_INSN_OPCODE && op != JMP32_INSN_OPCODE) {
1760 			WARN_ON_ONCE(1);
1761 			continue;
1762 		}
1763 
1764 		memcpy(bytes, fineibt_paranoid_start, fineibt_paranoid_size);
1765 		memcpy(bytes + fineibt_caller_hash, &hash, 4);
1766 
1767 		if (cpu_wants_indirect_its_thunk_at((unsigned long)addr + fineibt_paranoid_ind, 11)) {
1768 			emit_paranoid_trampoline(addr + fineibt_caller_size,
1769 						 &insn, 11, bytes + fineibt_caller_size);
1770 		} else {
1771 			int len = fineibt_paranoid_size - fineibt_paranoid_ind;
1772 			ret = emit_indirect(op, 11, bytes + fineibt_paranoid_ind, len);
1773 			if (WARN_ON_ONCE(ret != len))
1774 				continue;
1775 		}
1776 
1777 		text_poke_early(addr, bytes, fineibt_paranoid_size);
1778 	}
1779 
1780 	return 0;
1781 }
1782 
1783 #define pr_cfi_debug(X...) if (cfi_debug) pr_info(X)
1784 
1785 #define FINEIBT_WARN(_f, _v) \
1786 	WARN_ONCE((_f) != (_v), "FineIBT: " #_f " %ld != %d\n", _f, _v)
1787 
1788 static void __init_or_module __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1789 					     s32 *start_cfi, s32 *end_cfi, bool builtin)
1790 {
1791 	int ret;
1792 
1793 	if (FINEIBT_WARN(fineibt_preamble_size, 20)			||
1794 	    FINEIBT_WARN(fineibt_preamble_bhi + fineibt_bhi1_size, 20)	||
1795 	    FINEIBT_WARN(fineibt_caller_size, 14)			||
1796 	    FINEIBT_WARN(fineibt_paranoid_size, 20)			||
1797 	    WARN_ON_ONCE(CFI_OFFSET < fineibt_prefix_size))
1798 		return;
1799 
1800 	if (cfi_mode == CFI_AUTO) {
1801 		cfi_mode = CFI_KCFI;
1802 		if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT)) {
1803 			/*
1804 			 * FRED has much saner context on exception entry and
1805 			 * is less easy to take advantage of.
1806 			 */
1807 			if (!cpu_feature_enabled(X86_FEATURE_FRED))
1808 				cfi_paranoid = true;
1809 			cfi_mode = CFI_FINEIBT;
1810 		}
1811 	}
1812 
1813 	/*
1814 	 * Rewrite the callers to not use the __cfi_ stubs, such that we might
1815 	 * rewrite them. This disables all CFI. If this succeeds but any of the
1816 	 * later stages fails, we're without CFI.
1817 	 */
1818 	pr_cfi_debug("CFI: disabling all indirect call checking\n");
1819 	ret = cfi_disable_callers(start_retpoline, end_retpoline);
1820 	if (ret)
1821 		goto err;
1822 
1823 	if (cfi_rand) {
1824 		if (builtin) {
1825 			cfi_seed = get_random_u32();
1826 			cfi_bpf_hash = cfi_rehash(cfi_bpf_hash);
1827 			cfi_bpf_subprog_hash = cfi_rehash(cfi_bpf_subprog_hash);
1828 		}
1829 		pr_cfi_debug("CFI: cfi_seed: 0x%08x\n", cfi_seed);
1830 
1831 		pr_cfi_debug("CFI: rehashing all preambles\n");
1832 		ret = cfi_rand_preamble(start_cfi, end_cfi);
1833 		if (ret)
1834 			goto err;
1835 
1836 		pr_cfi_debug("CFI: rehashing all indirect calls\n");
1837 		ret = cfi_rand_callers(start_retpoline, end_retpoline);
1838 		if (ret)
1839 			goto err;
1840 	} else {
1841 		pr_cfi_debug("CFI: rehashing disabled\n");
1842 	}
1843 
1844 	switch (cfi_mode) {
1845 	case CFI_OFF:
1846 		if (builtin)
1847 			pr_info("CFI: disabled\n");
1848 		return;
1849 
1850 	case CFI_KCFI:
1851 		pr_cfi_debug("CFI: re-enabling all indirect call checking\n");
1852 		ret = cfi_enable_callers(start_retpoline, end_retpoline);
1853 		if (ret)
1854 			goto err;
1855 
1856 		if (builtin)
1857 			pr_info("CFI: Using %sretpoline kCFI\n",
1858 				cfi_rand ? "rehashed " : "");
1859 		return;
1860 
1861 	case CFI_FINEIBT:
1862 		pr_cfi_debug("CFI: adding FineIBT to all preambles\n");
1863 		/* place the FineIBT preamble at func()-16 */
1864 		ret = cfi_rewrite_preamble(start_cfi, end_cfi);
1865 		if (ret)
1866 			goto err;
1867 
1868 		/* rewrite the callers to target func()-16 */
1869 		pr_cfi_debug("CFI: rewriting indirect call sites to use FineIBT\n");
1870 		ret = cfi_rewrite_callers(start_retpoline, end_retpoline);
1871 		if (ret)
1872 			goto err;
1873 
1874 		/* now that nobody targets func()+0, remove ENDBR there */
1875 		pr_cfi_debug("CFI: removing old endbr insns\n");
1876 		cfi_rewrite_endbr(start_cfi, end_cfi);
1877 
1878 		if (builtin) {
1879 			pr_info("Using %sFineIBT%s CFI\n",
1880 				cfi_paranoid ? "paranoid " : "",
1881 				cfi_bhi ? "+BHI" : "");
1882 		}
1883 		return;
1884 
1885 	default:
1886 		break;
1887 	}
1888 
1889 err:
1890 	pr_err("Something went horribly wrong trying to rewrite the CFI implementation.\n");
1891 }
1892 
1893 static inline void poison_hash(void *addr)
1894 {
1895 	*(u32 *)addr = 0;
1896 }
1897 
1898 static void poison_cfi(void *addr)
1899 {
1900 	/*
1901 	 * Compilers manage to be inconsistent with ENDBR vs __cfi prefixes,
1902 	 * some (static) functions for which they can determine the address
1903 	 * is never taken do not get a __cfi prefix, but *DO* get an ENDBR.
1904 	 *
1905 	 * As such, these functions will get sealed, but we need to be careful
1906 	 * to not unconditionally scribble the previous function.
1907 	 */
1908 	switch (cfi_mode) {
1909 	case CFI_FINEIBT:
1910 		/*
1911 		 * FineIBT preamble is at func-16.
1912 		 */
1913 		addr += CFI_OFFSET - fineibt_prefix_size;
1914 
1915 		/*
1916 		 * FineIBT prefix should start with an ENDBR.
1917 		 */
1918 		if (!is_endbr(addr))
1919 			break;
1920 
1921 		/*
1922 		 * __cfi_\func:
1923 		 *	nopl	-42(%rax)
1924 		 *	sub	$0, %eax
1925 		 *	jne	\func+3
1926 		 * \func:
1927 		 *	nopl	-42(%rax)
1928 		 */
1929 		poison_endbr(addr);
1930 		poison_hash(addr + fineibt_preamble_hash);
1931 		break;
1932 
1933 	case CFI_KCFI:
1934 		/*
1935 		 * kCFI prefix should start with a valid hash.
1936 		 */
1937 		if (!decode_preamble_hash(addr, NULL))
1938 			break;
1939 
1940 		/*
1941 		 * __cfi_\func:
1942 		 *	movl	$0, %eax
1943 		 *	.skip	11, 0x90
1944 		 */
1945 		poison_hash(addr + 1);
1946 		break;
1947 
1948 	default:
1949 		break;
1950 	}
1951 }
1952 
1953 /*
1954  * When regs->ip points to a 0xD6 byte in the FineIBT preamble,
1955  * return true and fill out target and type.
1956  *
1957  * We check the preamble by checking for the ENDBR instruction relative to the
1958  * UDB instruction.
1959  */
1960 static bool decode_fineibt_preamble(struct pt_regs *regs, unsigned long *target, u32 *type)
1961 {
1962 	unsigned long addr = regs->ip - fineibt_preamble_ud;
1963 	u32 hash;
1964 
1965 	if (!exact_endbr((void *)addr))
1966 		return false;
1967 
1968 	*target = addr + fineibt_prefix_size;
1969 
1970 	__get_kernel_nofault(&hash, addr + fineibt_preamble_hash, u32, Efault);
1971 	*type = (u32)regs->ax + hash;
1972 
1973 	/*
1974 	 * Since regs->ip points to the middle of an instruction; it cannot
1975 	 * continue with the normal fixup.
1976 	 */
1977 	regs->ip = *target;
1978 
1979 	return true;
1980 
1981 Efault:
1982 	return false;
1983 }
1984 
1985 /*
1986  * regs->ip points to one of the UD2 in __bhi_args[].
1987  */
1988 static bool decode_fineibt_bhi(struct pt_regs *regs, unsigned long *target, u32 *type)
1989 {
1990 	unsigned long addr;
1991 	u32 hash;
1992 
1993 	if (!cfi_bhi)
1994 		return false;
1995 
1996 	if (regs->ip < (unsigned long)__bhi_args ||
1997 	    regs->ip >= (unsigned long)__bhi_args_end)
1998 		return false;
1999 
2000 	/*
2001 	 * Fetch the return address from the stack, this points to the
2002 	 * FineIBT preamble. Since the CALL instruction is in the 5 last
2003 	 * bytes of the preamble, the return address is in fact the target
2004 	 * address.
2005 	 */
2006 	__get_kernel_nofault(&addr, regs->sp, unsigned long, Efault);
2007 	*target = addr;
2008 
2009 	addr -= fineibt_prefix_size;
2010 	if (!exact_endbr((void *)addr))
2011 		return false;
2012 
2013 	__get_kernel_nofault(&hash, addr + fineibt_preamble_hash, u32, Efault);
2014 	*type = (u32)regs->ax + hash;
2015 
2016 	/*
2017 	 * The UD2 sites are constructed with a RET immediately following,
2018 	 * as such the non-fatal case can use the regular fixup.
2019 	 */
2020 	return true;
2021 
2022 Efault:
2023 	return false;
2024 }
2025 
2026 static bool is_paranoid_thunk(unsigned long addr)
2027 {
2028 	u32 thunk;
2029 
2030 	__get_kernel_nofault(&thunk, (u32 *)addr, u32, Efault);
2031 	return (thunk & 0x00FFFFFF) == 0xfd75d6;
2032 
2033 Efault:
2034 	return false;
2035 }
2036 
2037 /*
2038  * regs->ip points to a LOCK Jcc.d8 instruction from the fineibt_paranoid_start[]
2039  * sequence, or to UDB + Jcc.d8 for cfi_paranoid + ITS thunk.
2040  */
2041 static bool decode_fineibt_paranoid(struct pt_regs *regs, unsigned long *target, u32 *type)
2042 {
2043 	unsigned long addr = regs->ip - fineibt_paranoid_ud;
2044 
2045 	if (!cfi_paranoid)
2046 		return false;
2047 
2048 	if (is_cfi_trap(addr + fineibt_caller_size - LEN_UD2)) {
2049 		*target = regs->r11 + fineibt_prefix_size;
2050 		*type = regs->ax;
2051 
2052 		/*
2053 		 * Since the trapping instruction is the exact, but LOCK prefixed,
2054 		 * Jcc.d8 that got us here, the normal fixup will work.
2055 		 */
2056 		return true;
2057 	}
2058 
2059 	/*
2060 	 * The cfi_paranoid + ITS thunk combination results in:
2061 	 *
2062 	 *  0:   b8 78 56 34 12          mov    $0x12345678, %eax
2063 	 *  5:   41 3b 43 f7             cmp    -11(%r11), %eax
2064 	 *  a:   2e 3d 8d 5b f0          cs lea -0x10(%r11), %r11
2065 	 *  e:   2e e8 XX XX XX XX	 cs call __x86_indirect_paranoid_thunk_r11
2066 	 *
2067 	 * Where the paranoid_thunk looks like:
2068 	 *
2069 	 *  1d:  <d6>                    udb
2070 	 *  __x86_indirect_paranoid_thunk_r11:
2071 	 *  1e:  75 fd                   jne 1d
2072 	 *  __x86_indirect_its_thunk_r11:
2073 	 *  20:  41 ff eb                jmp *%r11
2074 	 *  23:  cc                      int3
2075 	 *
2076 	 */
2077 	if (is_paranoid_thunk(regs->ip)) {
2078 		*target = regs->r11 + fineibt_prefix_size;
2079 		*type = regs->ax;
2080 
2081 		regs->ip = *target;
2082 		return true;
2083 	}
2084 
2085 	return false;
2086 }
2087 
2088 bool decode_fineibt_insn(struct pt_regs *regs, unsigned long *target, u32 *type)
2089 {
2090 	if (decode_fineibt_paranoid(regs, target, type))
2091 		return true;
2092 
2093 	if (decode_fineibt_bhi(regs, target, type))
2094 		return true;
2095 
2096 	return decode_fineibt_preamble(regs, target, type);
2097 }
2098 
2099 #else /* !CONFIG_FINEIBT: */
2100 
2101 static void __init_or_module __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
2102 					     s32 *start_cfi, s32 *end_cfi, bool builtin)
2103 {
2104 	if (IS_ENABLED(CONFIG_CFI) && builtin)
2105 		pr_info("CFI: Using standard kCFI\n");
2106 }
2107 
2108 #ifdef CONFIG_X86_KERNEL_IBT
2109 static void poison_cfi(void *addr) { }
2110 #endif
2111 
2112 #endif /* !CONFIG_FINEIBT */
2113 
2114 void __init_or_module apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
2115 				    s32 *start_cfi, s32 *end_cfi)
2116 {
2117 	return __apply_fineibt(start_retpoline, end_retpoline,
2118 			       start_cfi, end_cfi,
2119 			       /* .builtin = */ false);
2120 }
2121 
2122 /*
2123  * Self-test for the INT3 based CALL emulation code.
2124  *
2125  * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
2126  * properly and that there is a stack gap between the INT3 frame and the
2127  * previous context. Without this gap doing a virtual PUSH on the interrupted
2128  * stack would corrupt the INT3 IRET frame.
2129  *
2130  * See entry_{32,64}.S for more details.
2131  */
2132 
2133 extern void int3_selftest_asm(unsigned int *ptr);
2134 
2135 asm (
2136 "	.pushsection	.init.text, \"ax\", @progbits\n"
2137 "	.type		int3_selftest_asm, @function\n"
2138 "int3_selftest_asm:\n"
2139 	ANNOTATE_NOENDBR "\n"
2140 	/*
2141 	 * INT3 padded with NOP to CALL_INSN_SIZE. The INT3 triggers an
2142 	 * exception, then the int3_exception_nb notifier emulates a call to
2143 	 * int3_selftest_callee().
2144 	 */
2145 "	int3; nop; nop; nop; nop\n"
2146 	ASM_RET
2147 "	.size		int3_selftest_asm, . - int3_selftest_asm\n"
2148 "	.popsection\n"
2149 );
2150 
2151 extern void int3_selftest_callee(unsigned int *ptr);
2152 
2153 asm (
2154 "	.pushsection	.init.text, \"ax\", @progbits\n"
2155 "	.type		int3_selftest_callee, @function\n"
2156 "int3_selftest_callee:\n"
2157 	ANNOTATE_NOENDBR "\n"
2158 "	movl	$0x1234, (%" _ASM_ARG1 ")\n"
2159 	ASM_RET
2160 "	.size		int3_selftest_callee, . - int3_selftest_callee\n"
2161 "	.popsection\n"
2162 );
2163 
2164 extern void int3_selftest_ip(void); /* defined in asm below */
2165 
2166 static int __init
2167 int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
2168 {
2169 	unsigned long selftest = (unsigned long)&int3_selftest_asm;
2170 	struct die_args *args = data;
2171 	struct pt_regs *regs = args->regs;
2172 
2173 	OPTIMIZER_HIDE_VAR(selftest);
2174 
2175 	if (!regs || user_mode(regs))
2176 		return NOTIFY_DONE;
2177 
2178 	if (val != DIE_INT3)
2179 		return NOTIFY_DONE;
2180 
2181 	if (regs->ip - INT3_INSN_SIZE != selftest)
2182 		return NOTIFY_DONE;
2183 
2184 	int3_emulate_call(regs, (unsigned long)&int3_selftest_callee);
2185 	return NOTIFY_STOP;
2186 }
2187 
2188 /* Must be noinline to ensure uniqueness of int3_selftest_ip. */
2189 static noinline void __init int3_selftest(void)
2190 {
2191 	static __initdata struct notifier_block int3_exception_nb = {
2192 		.notifier_call	= int3_exception_notify,
2193 		.priority	= INT_MAX-1, /* last */
2194 	};
2195 	unsigned int val = 0;
2196 
2197 	BUG_ON(register_die_notifier(&int3_exception_nb));
2198 
2199 	/*
2200 	 * Basically: int3_selftest_callee(&val); but really complicated :-)
2201 	 */
2202 	int3_selftest_asm(&val);
2203 
2204 	BUG_ON(val != 0x1234);
2205 
2206 	unregister_die_notifier(&int3_exception_nb);
2207 }
2208 
2209 static __initdata int __alt_reloc_selftest_addr;
2210 
2211 extern void __init __alt_reloc_selftest(void *arg);
2212 __visible noinline void __init __alt_reloc_selftest(void *arg)
2213 {
2214 	WARN_ON(arg != &__alt_reloc_selftest_addr);
2215 }
2216 
2217 static noinline void __init alt_reloc_selftest(void)
2218 {
2219 	/*
2220 	 * Tests text_poke_apply_relocation().
2221 	 *
2222 	 * This has a relative immediate (CALL) in a place other than the first
2223 	 * instruction and additionally on x86_64 we get a RIP-relative LEA:
2224 	 *
2225 	 *   lea    0x0(%rip),%rdi  # 5d0: R_X86_64_PC32    .init.data+0x5566c
2226 	 *   call   +0              # 5d5: R_X86_64_PLT32   __alt_reloc_selftest-0x4
2227 	 *
2228 	 * Getting this wrong will either crash and burn or tickle the WARN
2229 	 * above.
2230 	 */
2231 	asm_inline volatile (
2232 		ALTERNATIVE("", "lea %[mem], %%" _ASM_ARG1 "; call __alt_reloc_selftest;", X86_FEATURE_ALWAYS)
2233 		: ASM_CALL_CONSTRAINT
2234 		: [mem] "m" (__alt_reloc_selftest_addr)
2235 		: _ASM_ARG1
2236 	);
2237 }
2238 
2239 void __init alternative_instructions(void)
2240 {
2241 	u64 ibt;
2242 
2243 	int3_selftest();
2244 
2245 	/*
2246 	 * The patching is not fully atomic, so try to avoid local
2247 	 * interruptions that might execute the to be patched code.
2248 	 * Other CPUs are not running.
2249 	 */
2250 	stop_nmi();
2251 
2252 	/*
2253 	 * Don't stop machine check exceptions while patching.
2254 	 * MCEs only happen when something got corrupted and in this
2255 	 * case we must do something about the corruption.
2256 	 * Ignoring it is worse than an unlikely patching race.
2257 	 * Also machine checks tend to be broadcast and if one CPU
2258 	 * goes into machine check the others follow quickly, so we don't
2259 	 * expect a machine check to cause undue problems during to code
2260 	 * patching.
2261 	 */
2262 
2263 	/*
2264 	 * Make sure to set (artificial) features depending on used paravirt
2265 	 * functions which can later influence alternative patching.
2266 	 */
2267 	paravirt_set_cap();
2268 
2269 	/* Keep CET-IBT disabled until caller/callee are patched */
2270 	ibt = ibt_save(/*disable*/ true);
2271 
2272 	__apply_fineibt(__retpoline_sites, __retpoline_sites_end,
2273 			__cfi_sites, __cfi_sites_end, true);
2274 	cfi_debug = false;
2275 
2276 	/*
2277 	 * Rewrite the retpolines, must be done before alternatives since
2278 	 * those can rewrite the retpoline thunks.
2279 	 */
2280 	apply_retpolines(__retpoline_sites, __retpoline_sites_end);
2281 	apply_returns(__return_sites, __return_sites_end);
2282 
2283 	its_fini_core();
2284 
2285 	/*
2286 	 * Adjust all CALL instructions to point to func()-10, including
2287 	 * those in .altinstr_replacement.
2288 	 */
2289 	callthunks_patch_builtin_calls();
2290 
2291 	apply_alternatives(__alt_instructions, __alt_instructions_end);
2292 
2293 	/*
2294 	 * Seal all functions that do not have their address taken.
2295 	 */
2296 	apply_seal_endbr(__ibt_endbr_seal, __ibt_endbr_seal_end);
2297 
2298 	ibt_restore(ibt);
2299 
2300 	restart_nmi();
2301 	alternatives_patched = 1;
2302 
2303 	alt_reloc_selftest();
2304 }
2305 
2306 /**
2307  * text_poke_early - Update instructions on a live kernel at boot time
2308  * @addr: address to modify
2309  * @opcode: source of the copy
2310  * @len: length to copy
2311  *
2312  * When you use this code to patch more than one byte of an instruction
2313  * you need to make sure that other CPUs cannot execute this code in parallel.
2314  * Also no thread must be currently preempted in the middle of these
2315  * instructions. And on the local CPU you need to be protected against NMI or
2316  * MCE handlers seeing an inconsistent instruction while you patch.
2317  */
2318 void __init_or_module text_poke_early(void *addr, const void *opcode,
2319 				      size_t len)
2320 {
2321 	unsigned long flags;
2322 
2323 	if (boot_cpu_has(X86_FEATURE_NX) &&
2324 	    is_module_text_address((unsigned long)addr)) {
2325 		/*
2326 		 * Modules text is marked initially as non-executable, so the
2327 		 * code cannot be running and speculative code-fetches are
2328 		 * prevented. Just change the code.
2329 		 */
2330 		memcpy(addr, opcode, len);
2331 	} else {
2332 		local_irq_save(flags);
2333 		memcpy(addr, opcode, len);
2334 		sync_core();
2335 		local_irq_restore(flags);
2336 
2337 		/*
2338 		 * Could also do a CLFLUSH here to speed up CPU recovery; but
2339 		 * that causes hangs on some VIA CPUs.
2340 		 */
2341 	}
2342 }
2343 
2344 __ro_after_init struct mm_struct *text_poke_mm;
2345 __ro_after_init unsigned long text_poke_mm_addr;
2346 
2347 /*
2348  * Text poking creates and uses a mapping in the lower half of the
2349  * address space. Relax LASS enforcement when accessing the poking
2350  * address.
2351  *
2352  * objtool enforces a strict policy of "no function calls within AC=1
2353  * regions". Adhere to the policy by using inline versions of
2354  * memcpy()/memset() that will never result in a function call.
2355  */
2356 
2357 static void text_poke_memcpy(void *dst, const void *src, size_t len)
2358 {
2359 	lass_stac();
2360 	__inline_memcpy(dst, src, len);
2361 	lass_clac();
2362 }
2363 
2364 static void text_poke_memset(void *dst, const void *src, size_t len)
2365 {
2366 	int c = *(const int *)src;
2367 
2368 	lass_stac();
2369 	__inline_memset(dst, c, len);
2370 	lass_clac();
2371 }
2372 
2373 typedef void text_poke_f(void *dst, const void *src, size_t len);
2374 
2375 static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t len)
2376 {
2377 	bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
2378 	struct page *pages[2] = {NULL};
2379 	struct mm_struct *prev_mm;
2380 	unsigned long flags;
2381 	pte_t pte, *ptep;
2382 	spinlock_t *ptl;
2383 	pgprot_t pgprot;
2384 
2385 	/*
2386 	 * While boot memory allocator is running we cannot use struct pages as
2387 	 * they are not yet initialized. There is no way to recover.
2388 	 */
2389 	BUG_ON(!after_bootmem);
2390 
2391 	if (!core_kernel_text((unsigned long)addr)) {
2392 		pages[0] = vmalloc_to_page(addr);
2393 		if (cross_page_boundary)
2394 			pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
2395 	} else {
2396 		pages[0] = virt_to_page(addr);
2397 		WARN_ON(!PageReserved(pages[0]));
2398 		if (cross_page_boundary)
2399 			pages[1] = virt_to_page(addr + PAGE_SIZE);
2400 	}
2401 	/*
2402 	 * If something went wrong, crash and burn since recovery paths are not
2403 	 * implemented.
2404 	 */
2405 	BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
2406 
2407 	/*
2408 	 * Map the page without the global bit, as TLB flushing is done with
2409 	 * flush_tlb_mm_range(), which is intended for non-global PTEs.
2410 	 */
2411 	pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
2412 
2413 	/*
2414 	 * The lock is not really needed, but this allows to avoid open-coding.
2415 	 */
2416 	ptep = get_locked_pte(text_poke_mm, text_poke_mm_addr, &ptl);
2417 
2418 	/*
2419 	 * This must not fail; preallocated in poking_init().
2420 	 */
2421 	VM_BUG_ON(!ptep);
2422 
2423 	local_irq_save(flags);
2424 
2425 	pte = mk_pte(pages[0], pgprot);
2426 	set_pte_at(text_poke_mm, text_poke_mm_addr, ptep, pte);
2427 
2428 	if (cross_page_boundary) {
2429 		pte = mk_pte(pages[1], pgprot);
2430 		set_pte_at(text_poke_mm, text_poke_mm_addr + PAGE_SIZE, ptep + 1, pte);
2431 	}
2432 
2433 	/*
2434 	 * Loading the temporary mm behaves as a compiler barrier, which
2435 	 * guarantees that the PTE will be set at the time memcpy() is done.
2436 	 */
2437 	prev_mm = use_temporary_mm(text_poke_mm);
2438 
2439 	kasan_disable_current();
2440 	func((u8 *)text_poke_mm_addr + offset_in_page(addr), src, len);
2441 	kasan_enable_current();
2442 
2443 	/*
2444 	 * Ensure that the PTE is only cleared after the instructions of memcpy
2445 	 * were issued by using a compiler barrier.
2446 	 */
2447 	barrier();
2448 
2449 	pte_clear(text_poke_mm, text_poke_mm_addr, ptep);
2450 	if (cross_page_boundary)
2451 		pte_clear(text_poke_mm, text_poke_mm_addr + PAGE_SIZE, ptep + 1);
2452 
2453 	/*
2454 	 * Loading the previous page-table hierarchy requires a serializing
2455 	 * instruction that already allows the core to see the updated version.
2456 	 * Xen-PV is assumed to serialize execution in a similar manner.
2457 	 */
2458 	unuse_temporary_mm(prev_mm);
2459 
2460 	/*
2461 	 * Flushing the TLB might involve IPIs, which would require enabled
2462 	 * IRQs, but not if the mm is not used, as it is in this point.
2463 	 */
2464 	flush_tlb_mm_range(text_poke_mm, text_poke_mm_addr, text_poke_mm_addr +
2465 			   (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
2466 			   PAGE_SHIFT, false);
2467 
2468 	if (func == text_poke_memcpy) {
2469 		/*
2470 		 * If the text does not match what we just wrote then something is
2471 		 * fundamentally screwy; there's nothing we can really do about that.
2472 		 */
2473 		BUG_ON(memcmp(addr, src, len));
2474 	}
2475 
2476 	local_irq_restore(flags);
2477 	pte_unmap_unlock(ptep, ptl);
2478 	return addr;
2479 }
2480 
2481 /**
2482  * text_poke - Update instructions on a live kernel
2483  * @addr: address to modify
2484  * @opcode: source of the copy
2485  * @len: length to copy
2486  *
2487  * Only atomic text poke/set should be allowed when not doing early patching.
2488  * It means the size must be writable atomically and the address must be aligned
2489  * in a way that permits an atomic write. It also makes sure we fit on a single
2490  * page.
2491  *
2492  * Note that the caller must ensure that if the modified code is part of a
2493  * module, the module would not be removed during poking. This can be achieved
2494  * by registering a module notifier, and ordering module removal and patching
2495  * through a mutex.
2496  */
2497 void *text_poke(void *addr, const void *opcode, size_t len)
2498 {
2499 	lockdep_assert_held(&text_mutex);
2500 
2501 	return __text_poke(text_poke_memcpy, addr, opcode, len);
2502 }
2503 
2504 /**
2505  * text_poke_kgdb - Update instructions on a live kernel by kgdb
2506  * @addr: address to modify
2507  * @opcode: source of the copy
2508  * @len: length to copy
2509  *
2510  * Only atomic text poke/set should be allowed when not doing early patching.
2511  * It means the size must be writable atomically and the address must be aligned
2512  * in a way that permits an atomic write. It also makes sure we fit on a single
2513  * page.
2514  *
2515  * Context: should only be used by kgdb, which ensures no other core is running,
2516  *	    despite the fact it does not hold the text_mutex.
2517  */
2518 void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
2519 {
2520 	return __text_poke(text_poke_memcpy, addr, opcode, len);
2521 }
2522 
2523 void *text_poke_copy_locked(void *addr, const void *opcode, size_t len,
2524 			    bool core_ok)
2525 {
2526 	unsigned long start = (unsigned long)addr;
2527 	size_t patched = 0;
2528 
2529 	if (WARN_ON_ONCE(!core_ok && core_kernel_text(start)))
2530 		return NULL;
2531 
2532 	while (patched < len) {
2533 		unsigned long ptr = start + patched;
2534 		size_t s;
2535 
2536 		s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
2537 
2538 		__text_poke(text_poke_memcpy, (void *)ptr, opcode + patched, s);
2539 		patched += s;
2540 	}
2541 	return addr;
2542 }
2543 
2544 /**
2545  * text_poke_copy - Copy instructions into (an unused part of) RX memory
2546  * @addr: address to modify
2547  * @opcode: source of the copy
2548  * @len: length to copy, could be more than 2x PAGE_SIZE
2549  *
2550  * Not safe against concurrent execution; useful for JITs to dump
2551  * new code blocks into unused regions of RX memory. Can be used in
2552  * conjunction with synchronize_rcu_tasks() to wait for existing
2553  * execution to quiesce after having made sure no existing functions
2554  * pointers are live.
2555  */
2556 void *text_poke_copy(void *addr, const void *opcode, size_t len)
2557 {
2558 	mutex_lock(&text_mutex);
2559 	addr = text_poke_copy_locked(addr, opcode, len, false);
2560 	mutex_unlock(&text_mutex);
2561 	return addr;
2562 }
2563 
2564 /**
2565  * text_poke_set - memset into (an unused part of) RX memory
2566  * @addr: address to modify
2567  * @c: the byte to fill the area with
2568  * @len: length to copy, could be more than 2x PAGE_SIZE
2569  *
2570  * This is useful to overwrite unused regions of RX memory with illegal
2571  * instructions.
2572  */
2573 void *text_poke_set(void *addr, int c, size_t len)
2574 {
2575 	unsigned long start = (unsigned long)addr;
2576 	size_t patched = 0;
2577 
2578 	if (WARN_ON_ONCE(core_kernel_text(start)))
2579 		return NULL;
2580 
2581 	mutex_lock(&text_mutex);
2582 	while (patched < len) {
2583 		unsigned long ptr = start + patched;
2584 		size_t s;
2585 
2586 		s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
2587 
2588 		__text_poke(text_poke_memset, (void *)ptr, (void *)&c, s);
2589 		patched += s;
2590 	}
2591 	mutex_unlock(&text_mutex);
2592 	return addr;
2593 }
2594 
2595 static void do_sync_core(void *info)
2596 {
2597 	sync_core();
2598 }
2599 
2600 void smp_text_poke_sync_each_cpu(void)
2601 {
2602 	on_each_cpu(do_sync_core, NULL, 1);
2603 }
2604 
2605 /*
2606  * NOTE: crazy scheme to allow patching Jcc.d32 but not increase the size of
2607  * this thing. When len == 6 everything is prefixed with 0x0f and we map
2608  * opcode to Jcc.d8, using len to distinguish.
2609  */
2610 struct smp_text_poke_loc {
2611 	/* addr := _stext + rel_addr */
2612 	s32 rel_addr;
2613 	s32 disp;
2614 	u8 len;
2615 	u8 opcode;
2616 	const u8 text[TEXT_POKE_MAX_OPCODE_SIZE];
2617 	/* see smp_text_poke_batch_finish() */
2618 	u8 old;
2619 };
2620 
2621 #define TEXT_POKE_ARRAY_MAX (PAGE_SIZE / sizeof(struct smp_text_poke_loc))
2622 
2623 static struct smp_text_poke_array {
2624 	struct smp_text_poke_loc vec[TEXT_POKE_ARRAY_MAX];
2625 	int nr_entries;
2626 } text_poke_array;
2627 
2628 static DEFINE_PER_CPU(atomic_t, text_poke_array_refs);
2629 
2630 /*
2631  * These four __always_inline annotations imply noinstr, necessary
2632  * due to smp_text_poke_int3_handler() being noinstr:
2633  */
2634 
2635 static __always_inline bool try_get_text_poke_array(void)
2636 {
2637 	atomic_t *refs = this_cpu_ptr(&text_poke_array_refs);
2638 
2639 	if (!raw_atomic_inc_not_zero(refs))
2640 		return false;
2641 
2642 	return true;
2643 }
2644 
2645 static __always_inline void put_text_poke_array(void)
2646 {
2647 	atomic_t *refs = this_cpu_ptr(&text_poke_array_refs);
2648 
2649 	smp_mb__before_atomic();
2650 	raw_atomic_dec(refs);
2651 }
2652 
2653 static __always_inline void *text_poke_addr(const struct smp_text_poke_loc *tpl)
2654 {
2655 	return _stext + tpl->rel_addr;
2656 }
2657 
2658 static __always_inline int patch_cmp(const void *tpl_a, const void *tpl_b)
2659 {
2660 	if (tpl_a < text_poke_addr(tpl_b))
2661 		return -1;
2662 	if (tpl_a > text_poke_addr(tpl_b))
2663 		return 1;
2664 	return 0;
2665 }
2666 
2667 noinstr int smp_text_poke_int3_handler(struct pt_regs *regs)
2668 {
2669 	struct smp_text_poke_loc *tpl;
2670 	int ret = 0;
2671 	void *ip;
2672 
2673 	if (user_mode(regs))
2674 		return 0;
2675 
2676 	/*
2677 	 * Having observed our INT3 instruction, we now must observe
2678 	 * text_poke_array with non-zero refcount:
2679 	 *
2680 	 *	text_poke_array_refs = 1		INT3
2681 	 *	WMB			RMB
2682 	 *	write INT3		if (text_poke_array_refs != 0)
2683 	 */
2684 	smp_rmb();
2685 
2686 	if (!try_get_text_poke_array())
2687 		return 0;
2688 
2689 	/*
2690 	 * Discount the INT3. See smp_text_poke_batch_finish().
2691 	 */
2692 	ip = (void *) regs->ip - INT3_INSN_SIZE;
2693 
2694 	/*
2695 	 * Skip the binary search if there is a single member in the vector.
2696 	 */
2697 	if (unlikely(text_poke_array.nr_entries > 1)) {
2698 		tpl = __inline_bsearch(ip, text_poke_array.vec, text_poke_array.nr_entries,
2699 				      sizeof(struct smp_text_poke_loc),
2700 				      patch_cmp);
2701 		if (!tpl)
2702 			goto out_put;
2703 	} else {
2704 		tpl = text_poke_array.vec;
2705 		if (text_poke_addr(tpl) != ip)
2706 			goto out_put;
2707 	}
2708 
2709 	ip += tpl->len;
2710 
2711 	switch (tpl->opcode) {
2712 	case INT3_INSN_OPCODE:
2713 		/*
2714 		 * Someone poked an explicit INT3, they'll want to handle it,
2715 		 * do not consume.
2716 		 */
2717 		goto out_put;
2718 
2719 	case RET_INSN_OPCODE:
2720 		int3_emulate_ret(regs);
2721 		break;
2722 
2723 	case CALL_INSN_OPCODE:
2724 		int3_emulate_call(regs, (long)ip + tpl->disp);
2725 		break;
2726 
2727 	case JMP32_INSN_OPCODE:
2728 	case JMP8_INSN_OPCODE:
2729 		int3_emulate_jmp(regs, (long)ip + tpl->disp);
2730 		break;
2731 
2732 	case 0x70 ... 0x7f: /* Jcc */
2733 		int3_emulate_jcc(regs, tpl->opcode & 0xf, (long)ip, tpl->disp);
2734 		break;
2735 
2736 	default:
2737 		BUG();
2738 	}
2739 
2740 	ret = 1;
2741 
2742 out_put:
2743 	put_text_poke_array();
2744 	return ret;
2745 }
2746 
2747 /**
2748  * smp_text_poke_batch_finish() -- update instructions on live kernel on SMP
2749  *
2750  * Input state:
2751  *  text_poke_array.vec: vector of instructions to patch
2752  *  text_poke_array.nr_entries: number of entries in the vector
2753  *
2754  * Modify multi-byte instructions by using INT3 breakpoints on SMP.
2755  * We completely avoid using stop_machine() here, and achieve the
2756  * synchronization using INT3 breakpoints and SMP cross-calls.
2757  *
2758  * The way it is done:
2759  *	- For each entry in the vector:
2760  *		- add an INT3 trap to the address that will be patched
2761  *	- SMP sync all CPUs
2762  *	- For each entry in the vector:
2763  *		- update all but the first byte of the patched range
2764  *	- SMP sync all CPUs
2765  *	- For each entry in the vector:
2766  *		- replace the first byte (INT3) by the first byte of the
2767  *		  replacing opcode
2768  *	- SMP sync all CPUs
2769  */
2770 void smp_text_poke_batch_finish(void)
2771 {
2772 	unsigned char int3 = INT3_INSN_OPCODE;
2773 	unsigned int i;
2774 	int do_sync;
2775 
2776 	if (!text_poke_array.nr_entries)
2777 		return;
2778 
2779 	lockdep_assert_held(&text_mutex);
2780 
2781 	/*
2782 	 * Corresponds to the implicit memory barrier in try_get_text_poke_array() to
2783 	 * ensure reading a non-zero refcount provides up to date text_poke_array data.
2784 	 */
2785 	for_each_possible_cpu(i)
2786 		atomic_set_release(per_cpu_ptr(&text_poke_array_refs, i), 1);
2787 
2788 	/*
2789 	 * Function tracing can enable thousands of places that need to be
2790 	 * updated. This can take quite some time, and with full kernel debugging
2791 	 * enabled, this could cause the softlockup watchdog to trigger.
2792 	 * This function gets called every 256 entries added to be patched.
2793 	 * Call cond_resched() here to make sure that other tasks can get scheduled
2794 	 * while processing all the functions being patched.
2795 	 */
2796 	cond_resched();
2797 
2798 	/*
2799 	 * Corresponding read barrier in INT3 notifier for making sure the
2800 	 * text_poke_array.nr_entries and handler are correctly ordered wrt. patching.
2801 	 */
2802 	smp_wmb();
2803 
2804 	/*
2805 	 * First step: add a INT3 trap to the address that will be patched.
2806 	 */
2807 	for (i = 0; i < text_poke_array.nr_entries; i++) {
2808 		text_poke_array.vec[i].old = *(u8 *)text_poke_addr(&text_poke_array.vec[i]);
2809 		text_poke(text_poke_addr(&text_poke_array.vec[i]), &int3, INT3_INSN_SIZE);
2810 	}
2811 
2812 	smp_text_poke_sync_each_cpu();
2813 
2814 	/*
2815 	 * Second step: update all but the first byte of the patched range.
2816 	 */
2817 	for (do_sync = 0, i = 0; i < text_poke_array.nr_entries; i++) {
2818 		u8 old[TEXT_POKE_MAX_OPCODE_SIZE+1] = { text_poke_array.vec[i].old, };
2819 		u8 _new[TEXT_POKE_MAX_OPCODE_SIZE+1];
2820 		const u8 *new = text_poke_array.vec[i].text;
2821 		int len = text_poke_array.vec[i].len;
2822 
2823 		if (len - INT3_INSN_SIZE > 0) {
2824 			memcpy(old + INT3_INSN_SIZE,
2825 			       text_poke_addr(&text_poke_array.vec[i]) + INT3_INSN_SIZE,
2826 			       len - INT3_INSN_SIZE);
2827 
2828 			if (len == 6) {
2829 				_new[0] = 0x0f;
2830 				memcpy(_new + 1, new, 5);
2831 				new = _new;
2832 			}
2833 
2834 			text_poke(text_poke_addr(&text_poke_array.vec[i]) + INT3_INSN_SIZE,
2835 				  new + INT3_INSN_SIZE,
2836 				  len - INT3_INSN_SIZE);
2837 
2838 			do_sync++;
2839 		}
2840 
2841 		/*
2842 		 * Emit a perf event to record the text poke, primarily to
2843 		 * support Intel PT decoding which must walk the executable code
2844 		 * to reconstruct the trace. The flow up to here is:
2845 		 *   - write INT3 byte
2846 		 *   - IPI-SYNC
2847 		 *   - write instruction tail
2848 		 * At this point the actual control flow will be through the
2849 		 * INT3 and handler and not hit the old or new instruction.
2850 		 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
2851 		 * can still be decoded. Subsequently:
2852 		 *   - emit RECORD_TEXT_POKE with the new instruction
2853 		 *   - IPI-SYNC
2854 		 *   - write first byte
2855 		 *   - IPI-SYNC
2856 		 * So before the text poke event timestamp, the decoder will see
2857 		 * either the old instruction flow or FUP/TIP of INT3. After the
2858 		 * text poke event timestamp, the decoder will see either the
2859 		 * new instruction flow or FUP/TIP of INT3. Thus decoders can
2860 		 * use the timestamp as the point at which to modify the
2861 		 * executable code.
2862 		 * The old instruction is recorded so that the event can be
2863 		 * processed forwards or backwards.
2864 		 */
2865 		perf_event_text_poke(text_poke_addr(&text_poke_array.vec[i]), old, len, new, len);
2866 	}
2867 
2868 	if (do_sync) {
2869 		/*
2870 		 * According to Intel, this core syncing is very likely
2871 		 * not necessary and we'd be safe even without it. But
2872 		 * better safe than sorry (plus there's not only Intel).
2873 		 */
2874 		smp_text_poke_sync_each_cpu();
2875 	}
2876 
2877 	/*
2878 	 * Third step: replace the first byte (INT3) by the first byte of the
2879 	 * replacing opcode.
2880 	 */
2881 	for (do_sync = 0, i = 0; i < text_poke_array.nr_entries; i++) {
2882 		u8 byte = text_poke_array.vec[i].text[0];
2883 
2884 		if (text_poke_array.vec[i].len == 6)
2885 			byte = 0x0f;
2886 
2887 		if (byte == INT3_INSN_OPCODE)
2888 			continue;
2889 
2890 		text_poke(text_poke_addr(&text_poke_array.vec[i]), &byte, INT3_INSN_SIZE);
2891 		do_sync++;
2892 	}
2893 
2894 	if (do_sync)
2895 		smp_text_poke_sync_each_cpu();
2896 
2897 	/*
2898 	 * Remove and wait for refs to be zero.
2899 	 *
2900 	 * Notably, if after step-3 above the INT3 got removed, then the
2901 	 * smp_text_poke_sync_each_cpu() will have serialized against any running INT3
2902 	 * handlers and the below spin-wait will not happen.
2903 	 *
2904 	 * IOW. unless the replacement instruction is INT3, this case goes
2905 	 * unused.
2906 	 */
2907 	for_each_possible_cpu(i) {
2908 		atomic_t *refs = per_cpu_ptr(&text_poke_array_refs, i);
2909 
2910 		if (unlikely(!atomic_dec_and_test(refs)))
2911 			atomic_cond_read_acquire(refs, !VAL);
2912 	}
2913 
2914 	/* They are all completed: */
2915 	text_poke_array.nr_entries = 0;
2916 }
2917 
2918 static void __smp_text_poke_batch_add(void *addr, const void *opcode, size_t len, const void *emulate)
2919 {
2920 	struct smp_text_poke_loc *tpl;
2921 	struct insn insn;
2922 	int ret, i = 0;
2923 
2924 	tpl = &text_poke_array.vec[text_poke_array.nr_entries++];
2925 
2926 	if (len == 6)
2927 		i = 1;
2928 	memcpy((void *)tpl->text, opcode+i, len-i);
2929 	if (!emulate)
2930 		emulate = opcode;
2931 
2932 	ret = insn_decode_kernel(&insn, emulate);
2933 	BUG_ON(ret < 0);
2934 
2935 	tpl->rel_addr = addr - (void *)_stext;
2936 	tpl->len = len;
2937 	tpl->opcode = insn.opcode.bytes[0];
2938 
2939 	if (is_jcc32(&insn)) {
2940 		/*
2941 		 * Map Jcc.d32 onto Jcc.d8 and use len to distinguish.
2942 		 */
2943 		tpl->opcode = insn.opcode.bytes[1] - 0x10;
2944 	}
2945 
2946 	switch (tpl->opcode) {
2947 	case RET_INSN_OPCODE:
2948 	case JMP32_INSN_OPCODE:
2949 	case JMP8_INSN_OPCODE:
2950 		/*
2951 		 * Control flow instructions without implied execution of the
2952 		 * next instruction can be padded with INT3.
2953 		 */
2954 		for (i = insn.length; i < len; i++)
2955 			BUG_ON(tpl->text[i] != INT3_INSN_OPCODE);
2956 		break;
2957 
2958 	default:
2959 		BUG_ON(len != insn.length);
2960 	}
2961 
2962 	switch (tpl->opcode) {
2963 	case INT3_INSN_OPCODE:
2964 	case RET_INSN_OPCODE:
2965 		break;
2966 
2967 	case CALL_INSN_OPCODE:
2968 	case JMP32_INSN_OPCODE:
2969 	case JMP8_INSN_OPCODE:
2970 	case 0x70 ... 0x7f: /* Jcc */
2971 		tpl->disp = insn.immediate.value;
2972 		break;
2973 
2974 	default: /* assume NOP */
2975 		switch (len) {
2976 		case 2: /* NOP2 -- emulate as JMP8+0 */
2977 			BUG_ON(memcmp(emulate, x86_nops[len], len));
2978 			tpl->opcode = JMP8_INSN_OPCODE;
2979 			tpl->disp = 0;
2980 			break;
2981 
2982 		case 5: /* NOP5 -- emulate as JMP32+0 */
2983 			BUG_ON(memcmp(emulate, x86_nops[len], len));
2984 			tpl->opcode = JMP32_INSN_OPCODE;
2985 			tpl->disp = 0;
2986 			break;
2987 
2988 		default: /* unknown instruction */
2989 			BUG();
2990 		}
2991 		break;
2992 	}
2993 }
2994 
2995 /*
2996  * We hard rely on the text_poke_array.vec being ordered; ensure this is so by flushing
2997  * early if needed.
2998  */
2999 static bool text_poke_addr_ordered(void *addr)
3000 {
3001 	WARN_ON_ONCE(!addr);
3002 
3003 	if (!text_poke_array.nr_entries)
3004 		return true;
3005 
3006 	/*
3007 	 * If the last current entry's address is higher than the
3008 	 * new entry's address we'd like to add, then ordering
3009 	 * is violated and we must first flush all pending patching
3010 	 * requests:
3011 	 */
3012 	if (text_poke_addr(text_poke_array.vec + text_poke_array.nr_entries-1) > addr)
3013 		return false;
3014 
3015 	return true;
3016 }
3017 
3018 /**
3019  * smp_text_poke_batch_add() -- update instruction on live kernel on SMP, batched
3020  * @addr:	address to patch
3021  * @opcode:	opcode of new instruction
3022  * @len:	length to copy
3023  * @emulate:	instruction to be emulated
3024  *
3025  * Add a new instruction to the current queue of to-be-patched instructions
3026  * the kernel maintains. The patching request will not be executed immediately,
3027  * but becomes part of an array of patching requests, optimized for batched
3028  * execution. All pending patching requests will be executed on the next
3029  * smp_text_poke_batch_finish() call.
3030  */
3031 void __ref smp_text_poke_batch_add(void *addr, const void *opcode, size_t len, const void *emulate)
3032 {
3033 	if (text_poke_array.nr_entries == TEXT_POKE_ARRAY_MAX || !text_poke_addr_ordered(addr))
3034 		smp_text_poke_batch_finish();
3035 	__smp_text_poke_batch_add(addr, opcode, len, emulate);
3036 }
3037 
3038 /**
3039  * smp_text_poke_single() -- update instruction on live kernel on SMP immediately
3040  * @addr:	address to patch
3041  * @opcode:	opcode of new instruction
3042  * @len:	length to copy
3043  * @emulate:	instruction to be emulated
3044  *
3045  * Update a single instruction with the vector in the stack, avoiding
3046  * dynamically allocated memory. This function should be used when it is
3047  * not possible to allocate memory for a vector. The single instruction
3048  * is patched in immediately.
3049  */
3050 void __ref smp_text_poke_single(void *addr, const void *opcode, size_t len, const void *emulate)
3051 {
3052 	smp_text_poke_batch_add(addr, opcode, len, emulate);
3053 	smp_text_poke_batch_finish();
3054 }
3055