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