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