File Index
Files and directories
Sign in
FILE

alternative.c

File preview with syntax highlighting.

linux-6.19.14/arch/x86/kernel/alternative.c C
   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
  17int __read_mostly alternatives_patched;
  18
  19EXPORT_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
  30static unsigned int debug_alternative;
  31
  32static 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
  44static int noreplace_smp;
  45
  46static 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...)					\
  54do {									\
  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...)			\
  60do {									\
  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
  74static 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
  91const 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
 110static bool cfi_paranoid __ro_after_init;
 111#endif
 112
 113#ifdef CONFIG_MITIGATION_ITS
 114
 115#ifdef CONFIG_MODULES
 116static struct module *its_mod;
 117#endif
 118static void *its_page;
 119static unsigned int its_offset;
 120struct its_array its_pages;
 121
 122static 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. */
 140static 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
 173static 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
 181static 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
 189void 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
 199void 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
 214void 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
 227static 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
 247static 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
 286u8 *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
 299static 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 */
 325static 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 */
 353static 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 */
 372static 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
 445static __always_inline
 446void 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
 456static __always_inline
 457bool 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
 467static 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
 521void 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. */
 528DEFINE_ASM_FUNC(nop_func, "", .entry.text);
 529EXPORT_SYMBOL_GPL(nop_func);
 530
 531noinstr void BUG_func(void)
 532{
 533	BUG();
 534}
 535EXPORT_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 */
 544static 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
 584static 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 */
 599void __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
 686static 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 */
 697static 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
 749static 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:
 777clang_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
 794static 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
 802static 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 */
 814static 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
 828static 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 */
 852static 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 */
 933void __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
 993bool cpu_wants_rethunk(void)
 994{
 995	return cpu_feature_enabled(X86_FEATURE_RETHUNK);
 996}
 997
 998bool 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 */
1019static 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
1037void __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: */
1078void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
1079#endif /* !CONFIG_MITIGATION_RETHUNK */
1080
1081#else /* !CONFIG_MITIGATION_RETPOLINE || !CONFIG_OBJTOOL */
1082
1083void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
1084void __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
1097Efault:
1098	return false;
1099}
1100
1101#ifdef CONFIG_FINEIBT
1102
1103static __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
1110Efault:
1111	return false;
1112}
1113
1114#endif
1115
1116static void poison_cfi(void *addr);
1117
1118static 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 */
1141void __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 - CFI_OFFSET);
1151	}
1152}
1153
1154#else /* !CONFIG_X86_KERNEL_IBT: */
1155
1156void __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
1168enum cfi_mode cfi_mode __ro_after_init = __CFI_DEFAULT;
1169static bool cfi_debug __ro_after_init;
1170
1171#ifdef CONFIG_FINEIBT_BHI
1172bool cfi_bhi __ro_after_init = false;
1173#endif
1174
1175#ifdef CONFIG_CFI
1176u32 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
1198int 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
1216static bool cfi_rand __ro_after_init = true;
1217static 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 */
1223static 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
1235static __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}
1288early_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 */
1336asm(	".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
1348extern u8 fineibt_preamble_start[];
1349extern u8 fineibt_preamble_bhi[];
1350extern 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#define fineibt_prefix_size (fineibt_preamble_size - ENDBR_INSN_SIZE)
1358
1359/*
1360 * <fineibt_caller_start>:
1361 *  0:   b8 78 56 34 12          mov    $0x12345678, %eax
1362 *  5:   4d 8d 5b f0             lea    -0x10(%r11), %r11
1363 *  9:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)
1364 */
1365asm(	".pushsection .rodata			\n"
1366	"fineibt_caller_start:			\n"
1367	"	movl	$0x12345678, %eax	\n"
1368	"	lea	-0x10(%r11), %r11	\n"
1369	ASM_NOP5
1370	"fineibt_caller_end:			\n"
1371	".popsection				\n"
1372);
1373
1374extern u8 fineibt_caller_start[];
1375extern u8 fineibt_caller_end[];
1376
1377#define fineibt_caller_size (fineibt_caller_end - fineibt_caller_start)
1378#define fineibt_caller_hash 1
1379
1380#define fineibt_caller_jmp (fineibt_caller_size - 2)
1381
1382/*
1383 * Since FineIBT does hash validation on the callee side it is prone to
1384 * circumvention attacks where a 'naked' ENDBR instruction exists that
1385 * is not part of the fineibt_preamble sequence.
1386 *
1387 * Notably the x86 entry points must be ENDBR and equally cannot be
1388 * fineibt_preamble.
1389 *
1390 * The fineibt_paranoid caller sequence adds additional caller side
1391 * hash validation. This stops such circumvention attacks dead, but at the cost
1392 * of adding a load.
1393 *
1394 * <fineibt_paranoid_start>:
1395 *  0:   b8 78 56 34 12          mov    $0x12345678, %eax
1396 *  5:   41 3b 43 f5             cmp    -0x11(%r11), %eax
1397 *  9:   2e 4d 8d 5b <f0>        cs lea -0x10(%r11), %r11
1398 *  e:   75 fd                   jne    d <fineibt_paranoid_start+0xd>
1399 * 10:   41 ff d3                call   *%r11
1400 * 13:   90                      nop
1401 *
1402 * Notably LEA does not modify flags and can be reordered with the CMP,
1403 * avoiding a dependency. Again, using a non-taken (backwards) branch
1404 * for the failure case, abusing LEA's immediate 0xf0 as LOCK prefix for the
1405 * Jcc.d8, causing #UD.
1406 */
1407asm(	".pushsection .rodata				\n"
1408	"fineibt_paranoid_start:			\n"
1409	"	mov	$0x12345678, %eax		\n"
1410	"	cmpl	-11(%r11), %eax			\n"
1411	"	cs lea	-0x10(%r11), %r11		\n"
1412	"#fineibt_caller_size:                          \n"
1413	"	jne	fineibt_paranoid_start+0xd	\n"
1414	"fineibt_paranoid_ind:				\n"
1415	"	cs call	*%r11				\n"
1416	"fineibt_paranoid_end:				\n"
1417	".popsection					\n"
1418);
1419
1420extern u8 fineibt_paranoid_start[];
1421extern u8 fineibt_paranoid_ind[];
1422extern u8 fineibt_paranoid_end[];
1423
1424#define fineibt_paranoid_size (fineibt_paranoid_end - fineibt_paranoid_start)
1425#define fineibt_paranoid_ind  (fineibt_paranoid_ind - fineibt_paranoid_start)
1426#define fineibt_paranoid_ud   0xd
1427
1428static u32 decode_preamble_hash(void *addr, int *reg)
1429{
1430	u8 *p = addr;
1431
1432	/* b8+reg 78 56 34 12          movl    $0x12345678,\reg */
1433	if (p[0] >= 0xb8 && p[0] < 0xc0) {
1434		if (reg)
1435			*reg = p[0] - 0xb8;
1436		return *(u32 *)(addr + 1);
1437	}
1438
1439	return 0; /* invalid hash value */
1440}
1441
1442static u32 decode_caller_hash(void *addr)
1443{
1444	u8 *p = addr;
1445
1446	/* 41 ba 88 a9 cb ed       mov    $(-0x12345678),%r10d */
1447	if (p[0] == 0x41 && p[1] == 0xba)
1448		return -*(u32 *)(addr + 2);
1449
1450	/* e8 0c 88 a9 cb ed	   jmp.d8  +12 */
1451	if (p[0] == JMP8_INSN_OPCODE && p[1] == fineibt_caller_jmp)
1452		return -*(u32 *)(addr + 2);
1453
1454	return 0; /* invalid hash value */
1455}
1456
1457/* .retpoline_sites */
1458static int cfi_disable_callers(s32 *start, s32 *end)
1459{
1460	/*
1461	 * Disable kCFI by patching in a JMP.d8, this leaves the hash immediate
1462	 * in tact for later usage. Also see decode_caller_hash() and
1463	 * cfi_rewrite_callers().
1464	 */
1465	const u8 jmp[] = { JMP8_INSN_OPCODE, fineibt_caller_jmp };
1466	s32 *s;
1467
1468	for (s = start; s < end; s++) {
1469		void *addr = (void *)s + *s;
1470		u32 hash;
1471
1472		addr -= fineibt_caller_size;
1473		hash = decode_caller_hash(addr);
1474		if (!hash) /* nocfi callers */
1475			continue;
1476
1477		text_poke_early(addr, jmp, 2);
1478	}
1479
1480	return 0;
1481}
1482
1483static int cfi_enable_callers(s32 *start, s32 *end)
1484{
1485	/*
1486	 * Re-enable kCFI, undo what cfi_disable_callers() did.
1487	 */
1488	const u8 mov[] = { 0x41, 0xba };
1489	s32 *s;
1490
1491	for (s = start; s < end; s++) {
1492		void *addr = (void *)s + *s;
1493		u32 hash;
1494
1495		addr -= fineibt_caller_size;
1496		hash = decode_caller_hash(addr);
1497		if (!hash) /* nocfi callers */
1498			continue;
1499
1500		text_poke_early(addr, mov, 2);
1501	}
1502
1503	return 0;
1504}
1505
1506/* .cfi_sites */
1507static int cfi_rand_preamble(s32 *start, s32 *end)
1508{
1509	s32 *s;
1510
1511	for (s = start; s < end; s++) {
1512		void *addr = (void *)s + *s;
1513		u32 hash;
1514
1515		hash = decode_preamble_hash(addr, NULL);
1516		if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1517			 addr, addr, 5, addr))
1518			return -EINVAL;
1519
1520		hash = cfi_rehash(hash);
1521		text_poke_early(addr + 1, &hash, 4);
1522	}
1523
1524	return 0;
1525}
1526
1527/*
1528 * Inline the bhi-arity 1 case:
1529 *
1530 * __cfi_foo:
1531 *  0: f3 0f 1e fa             endbr64
1532 *  4: 2d 78 56 34 12          sub    $0x12345678, %eax
1533 *  9: 49 0f 45 fa             cmovne %rax, %rdi
1534 *  d: 2e 75 03                jne,pn    foo+0x3
1535 *
1536 * foo:
1537 * 10: 0f 1f 40 <d6>           nopl -42(%rax)
1538 *
1539 * Notably, this scheme is incompatible with permissive CFI
1540 * because the CMOVcc is unconditional and RDI will have been
1541 * clobbered.
1542 */
1543asm(	".pushsection .rodata				\n"
1544	"fineibt_bhi1_start:				\n"
1545	"	cmovne %rax, %rdi			\n"
1546	"	cs jne fineibt_bhi1_func + 0x3		\n"
1547	"fineibt_bhi1_func:				\n"
1548	"	nopl -42(%rax)				\n"
1549	"fineibt_bhi1_end:				\n"
1550	".popsection					\n"
1551);
1552
1553extern u8 fineibt_bhi1_start[];
1554extern u8 fineibt_bhi1_end[];
1555
1556#define fineibt_bhi1_size (fineibt_bhi1_end - fineibt_bhi1_start)
1557
1558static void cfi_fineibt_bhi_preamble(void *addr, int arity)
1559{
1560	u8 bytes[MAX_INSN_SIZE];
1561
1562	if (!arity)
1563		return;
1564
1565	if (!cfi_warn && arity == 1) {
1566		text_poke_early(addr + fineibt_preamble_bhi,
1567				fineibt_bhi1_start, fineibt_bhi1_size);
1568		return;
1569	}
1570
1571	/*
1572	 * Replace the bytes at fineibt_preamble_bhi with a CALL instruction
1573	 * that lines up exactly with the end of the preamble, such that the
1574	 * return address will be foo+0.
1575	 *
1576	 * __cfi_foo:
1577	 *  0: f3 0f 1e fa             endbr64
1578	 *  4: 2d 78 56 34 12          sub    $0x12345678, %eax
1579	 *  9: 2e 2e e8 DD DD DD DD    cs cs call __bhi_args[arity]
1580	 */
1581	bytes[0] = 0x2e;
1582	bytes[1] = 0x2e;
1583	__text_gen_insn(bytes + 2, CALL_INSN_OPCODE,
1584			addr + fineibt_preamble_bhi + 2,
1585			__bhi_args[arity], CALL_INSN_SIZE);
1586
1587	text_poke_early(addr + fineibt_preamble_bhi, bytes, 7);
1588}
1589
1590static int cfi_rewrite_preamble(s32 *start, s32 *end)
1591{
1592	s32 *s;
1593
1594	for (s = start; s < end; s++) {
1595		void *addr = (void *)s + *s;
1596		int arity;
1597		u32 hash;
1598
1599		/*
1600		 * When the function doesn't start with ENDBR the compiler will
1601		 * have determined there are no indirect calls to it and we
1602		 * don't need no CFI either.
1603		 */
1604		if (!is_endbr(addr + CFI_OFFSET))
1605			continue;
1606
1607		hash = decode_preamble_hash(addr, &arity);
1608		if (WARN(!hash, "no CFI hash found at: %pS %px %*ph\n",
1609			 addr, addr, 5, addr))
1610			return -EINVAL;
1611
1612		/*
1613		 * FineIBT relies on being at func-16, so if the preamble is
1614		 * actually larger than that, place it the tail end.
1615		 *
1616		 * NOTE: this is possible with things like DEBUG_CALL_THUNKS
1617		 * and DEBUG_FORCE_FUNCTION_ALIGN_64B.
1618		 */
1619		addr += CFI_OFFSET - fineibt_prefix_size;
1620
1621		text_poke_early(addr, fineibt_preamble_start, fineibt_preamble_size);
1622		WARN_ON(*(u32 *)(addr + fineibt_preamble_hash) != 0x12345678);
1623		text_poke_early(addr + fineibt_preamble_hash, &hash, 4);
1624
1625		WARN_ONCE(!IS_ENABLED(CONFIG_FINEIBT_BHI) && arity,
1626			  "kCFI preamble has wrong register at: %pS %*ph\n",
1627			  addr, 5, addr);
1628
1629		if (cfi_bhi)
1630			cfi_fineibt_bhi_preamble(addr, arity);
1631	}
1632
1633	return 0;
1634}
1635
1636static void cfi_rewrite_endbr(s32 *start, s32 *end)
1637{
1638	s32 *s;
1639
1640	for (s = start; s < end; s++) {
1641		void *addr = (void *)s + *s;
1642
1643		if (!exact_endbr(addr + CFI_OFFSET))
1644			continue;
1645
1646		poison_endbr(addr + CFI_OFFSET);
1647	}
1648}
1649
1650/* .retpoline_sites */
1651static int cfi_rand_callers(s32 *start, s32 *end)
1652{
1653	s32 *s;
1654
1655	for (s = start; s < end; s++) {
1656		void *addr = (void *)s + *s;
1657		u32 hash;
1658
1659		addr -= fineibt_caller_size;
1660		hash = decode_caller_hash(addr);
1661		if (hash) {
1662			hash = -cfi_rehash(hash);
1663			text_poke_early(addr + 2, &hash, 4);
1664		}
1665	}
1666
1667	return 0;
1668}
1669
1670static int emit_paranoid_trampoline(void *addr, struct insn *insn, int reg, u8 *bytes)
1671{
1672	u8 *thunk = (void *)__x86_indirect_its_thunk_array[reg] - 2;
1673
1674#ifdef CONFIG_MITIGATION_ITS
1675	u8 *tmp = its_allocate_thunk(reg);
1676	if (tmp)
1677		thunk = tmp;
1678#endif
1679
1680	return __emit_trampoline(addr, insn, bytes, thunk, thunk);
1681}
1682
1683static int cfi_rewrite_callers(s32 *start, s32 *end)
1684{
1685	s32 *s;
1686
1687	for (s = start; s < end; s++) {
1688		void *addr = (void *)s + *s;
1689		struct insn insn;
1690		u8 bytes[20];
1691		u32 hash;
1692		int ret;
1693		u8 op;
1694
1695		addr -= fineibt_caller_size;
1696		hash = decode_caller_hash(addr);
1697		if (!hash)
1698			continue;
1699
1700		if (!cfi_paranoid) {
1701			text_poke_early(addr, fineibt_caller_start, fineibt_caller_size);
1702			WARN_ON(*(u32 *)(addr + fineibt_caller_hash) != 0x12345678);
1703			text_poke_early(addr + fineibt_caller_hash, &hash, 4);
1704			/* rely on apply_retpolines() */
1705			continue;
1706		}
1707
1708		/* cfi_paranoid */
1709		ret = insn_decode_kernel(&insn, addr + fineibt_caller_size);
1710		if (WARN_ON_ONCE(ret < 0))
1711			continue;
1712
1713		op = insn.opcode.bytes[0];
1714		if (op != CALL_INSN_OPCODE && op != JMP32_INSN_OPCODE) {
1715			WARN_ON_ONCE(1);
1716			continue;
1717		}
1718
1719		memcpy(bytes, fineibt_paranoid_start, fineibt_paranoid_size);
1720		memcpy(bytes + fineibt_caller_hash, &hash, 4);
1721
1722		if (cpu_wants_indirect_its_thunk_at((unsigned long)addr + fineibt_paranoid_ind, 11)) {
1723			emit_paranoid_trampoline(addr + fineibt_caller_size,
1724						 &insn, 11, bytes + fineibt_caller_size);
1725		} else {
1726			int len = fineibt_paranoid_size - fineibt_paranoid_ind;
1727			ret = emit_indirect(op, 11, bytes + fineibt_paranoid_ind, len);
1728			if (WARN_ON_ONCE(ret != len))
1729				continue;
1730		}
1731
1732		text_poke_early(addr, bytes, fineibt_paranoid_size);
1733	}
1734
1735	return 0;
1736}
1737
1738#define pr_cfi_debug(X...) if (cfi_debug) pr_info(X)
1739
1740#define FINEIBT_WARN(_f, _v) \
1741	WARN_ONCE((_f) != (_v), "FineIBT: " #_f " %ld != %d\n", _f, _v)
1742
1743static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
1744			    s32 *start_cfi, s32 *end_cfi, bool builtin)
1745{
1746	int ret;
1747
1748	if (FINEIBT_WARN(fineibt_preamble_size, 20)			||
1749	    FINEIBT_WARN(fineibt_preamble_bhi + fineibt_bhi1_size, 20)	||
1750	    FINEIBT_WARN(fineibt_caller_size, 14)			||
1751	    FINEIBT_WARN(fineibt_paranoid_size, 20)			||
1752	    WARN_ON_ONCE(CFI_OFFSET < fineibt_prefix_size))
1753		return;
1754
1755	if (cfi_mode == CFI_AUTO) {
1756		cfi_mode = CFI_KCFI;
1757		if (HAS_KERNEL_IBT && cpu_feature_enabled(X86_FEATURE_IBT)) {
1758			/*
1759			 * FRED has much saner context on exception entry and
1760			 * is less easy to take advantage of.
1761			 */
1762			if (!cpu_feature_enabled(X86_FEATURE_FRED))
1763				cfi_paranoid = true;
1764			cfi_mode = CFI_FINEIBT;
1765		}
1766	}
1767
1768	/*
1769	 * Rewrite the callers to not use the __cfi_ stubs, such that we might
1770	 * rewrite them. This disables all CFI. If this succeeds but any of the
1771	 * later stages fails, we're without CFI.
1772	 */
1773	pr_cfi_debug("CFI: disabling all indirect call checking\n");
1774	ret = cfi_disable_callers(start_retpoline, end_retpoline);
1775	if (ret)
1776		goto err;
1777
1778	if (cfi_rand) {
1779		if (builtin) {
1780			cfi_seed = get_random_u32();
1781			cfi_bpf_hash = cfi_rehash(cfi_bpf_hash);
1782			cfi_bpf_subprog_hash = cfi_rehash(cfi_bpf_subprog_hash);
1783		}
1784		pr_cfi_debug("CFI: cfi_seed: 0x%08x\n", cfi_seed);
1785
1786		pr_cfi_debug("CFI: rehashing all preambles\n");
1787		ret = cfi_rand_preamble(start_cfi, end_cfi);
1788		if (ret)
1789			goto err;
1790
1791		pr_cfi_debug("CFI: rehashing all indirect calls\n");
1792		ret = cfi_rand_callers(start_retpoline, end_retpoline);
1793		if (ret)
1794			goto err;
1795	} else {
1796		pr_cfi_debug("CFI: rehashing disabled\n");
1797	}
1798
1799	switch (cfi_mode) {
1800	case CFI_OFF:
1801		if (builtin)
1802			pr_info("CFI: disabled\n");
1803		return;
1804
1805	case CFI_KCFI:
1806		pr_cfi_debug("CFI: re-enabling all indirect call checking\n");
1807		ret = cfi_enable_callers(start_retpoline, end_retpoline);
1808		if (ret)
1809			goto err;
1810
1811		if (builtin)
1812			pr_info("CFI: Using %sretpoline kCFI\n",
1813				cfi_rand ? "rehashed " : "");
1814		return;
1815
1816	case CFI_FINEIBT:
1817		pr_cfi_debug("CFI: adding FineIBT to all preambles\n");
1818		/* place the FineIBT preamble at func()-16 */
1819		ret = cfi_rewrite_preamble(start_cfi, end_cfi);
1820		if (ret)
1821			goto err;
1822
1823		/* rewrite the callers to target func()-16 */
1824		pr_cfi_debug("CFI: rewriting indirect call sites to use FineIBT\n");
1825		ret = cfi_rewrite_callers(start_retpoline, end_retpoline);
1826		if (ret)
1827			goto err;
1828
1829		/* now that nobody targets func()+0, remove ENDBR there */
1830		pr_cfi_debug("CFI: removing old endbr insns\n");
1831		cfi_rewrite_endbr(start_cfi, end_cfi);
1832
1833		if (builtin) {
1834			pr_info("Using %sFineIBT%s CFI\n",
1835				cfi_paranoid ? "paranoid " : "",
1836				cfi_bhi ? "+BHI" : "");
1837		}
1838		return;
1839
1840	default:
1841		break;
1842	}
1843
1844err:
1845	pr_err("Something went horribly wrong trying to rewrite the CFI implementation.\n");
1846}
1847
1848static inline void poison_hash(void *addr)
1849{
1850	*(u32 *)addr = 0;
1851}
1852
1853static void poison_cfi(void *addr)
1854{
1855	/*
1856	 * Compilers manage to be inconsistent with ENDBR vs __cfi prefixes,
1857	 * some (static) functions for which they can determine the address
1858	 * is never taken do not get a __cfi prefix, but *DO* get an ENDBR.
1859	 *
1860	 * As such, these functions will get sealed, but we need to be careful
1861	 * to not unconditionally scribble the previous function.
1862	 */
1863	switch (cfi_mode) {
1864	case CFI_FINEIBT:
1865		/*
1866		 * FineIBT preamble is at func-16.
1867		 */
1868		addr += CFI_OFFSET - fineibt_prefix_size;
1869
1870		/*
1871		 * FineIBT prefix should start with an ENDBR.
1872		 */
1873		if (!is_endbr(addr))
1874			break;
1875
1876		/*
1877		 * __cfi_\func:
1878		 *	nopl	-42(%rax)
1879		 *	sub	$0, %eax
1880		 *	jne	\func+3
1881		 * \func:
1882		 *	nopl	-42(%rax)
1883		 */
1884		poison_endbr(addr);
1885		poison_hash(addr + fineibt_preamble_hash);
1886		break;
1887
1888	case CFI_KCFI:
1889		/*
1890		 * kCFI prefix should start with a valid hash.
1891		 */
1892		if (!decode_preamble_hash(addr, NULL))
1893			break;
1894
1895		/*
1896		 * __cfi_\func:
1897		 *	movl	$0, %eax
1898		 *	.skip	11, 0x90
1899		 */
1900		poison_hash(addr + 1);
1901		break;
1902
1903	default:
1904		break;
1905	}
1906}
1907
1908/*
1909 * When regs->ip points to a 0xD6 byte in the FineIBT preamble,
1910 * return true and fill out target and type.
1911 *
1912 * We check the preamble by checking for the ENDBR instruction relative to the
1913 * UDB instruction.
1914 */
1915static bool decode_fineibt_preamble(struct pt_regs *regs, unsigned long *target, u32 *type)
1916{
1917	unsigned long addr = regs->ip - fineibt_preamble_ud;
1918	u32 hash;
1919
1920	if (!exact_endbr((void *)addr))
1921		return false;
1922
1923	*target = addr + fineibt_prefix_size;
1924
1925	__get_kernel_nofault(&hash, addr + fineibt_preamble_hash, u32, Efault);
1926	*type = (u32)regs->ax + hash;
1927
1928	/*
1929	 * Since regs->ip points to the middle of an instruction; it cannot
1930	 * continue with the normal fixup.
1931	 */
1932	regs->ip = *target;
1933
1934	return true;
1935
1936Efault:
1937	return false;
1938}
1939
1940/*
1941 * regs->ip points to one of the UD2 in __bhi_args[].
1942 */
1943static bool decode_fineibt_bhi(struct pt_regs *regs, unsigned long *target, u32 *type)
1944{
1945	unsigned long addr;
1946	u32 hash;
1947
1948	if (!cfi_bhi)
1949		return false;
1950
1951	if (regs->ip < (unsigned long)__bhi_args ||
1952	    regs->ip >= (unsigned long)__bhi_args_end)
1953		return false;
1954
1955	/*
1956	 * Fetch the return address from the stack, this points to the
1957	 * FineIBT preamble. Since the CALL instruction is in the 5 last
1958	 * bytes of the preamble, the return address is in fact the target
1959	 * address.
1960	 */
1961	__get_kernel_nofault(&addr, regs->sp, unsigned long, Efault);
1962	*target = addr;
1963
1964	addr -= fineibt_prefix_size;
1965	if (!exact_endbr((void *)addr))
1966		return false;
1967
1968	__get_kernel_nofault(&hash, addr + fineibt_preamble_hash, u32, Efault);
1969	*type = (u32)regs->ax + hash;
1970
1971	/*
1972	 * The UD2 sites are constructed with a RET immediately following,
1973	 * as such the non-fatal case can use the regular fixup.
1974	 */
1975	return true;
1976
1977Efault:
1978	return false;
1979}
1980
1981static bool is_paranoid_thunk(unsigned long addr)
1982{
1983	u32 thunk;
1984
1985	__get_kernel_nofault(&thunk, (u32 *)addr, u32, Efault);
1986	return (thunk & 0x00FFFFFF) == 0xfd75d6;
1987
1988Efault:
1989	return false;
1990}
1991
1992/*
1993 * regs->ip points to a LOCK Jcc.d8 instruction from the fineibt_paranoid_start[]
1994 * sequence, or to UDB + Jcc.d8 for cfi_paranoid + ITS thunk.
1995 */
1996static bool decode_fineibt_paranoid(struct pt_regs *regs, unsigned long *target, u32 *type)
1997{
1998	unsigned long addr = regs->ip - fineibt_paranoid_ud;
1999
2000	if (!cfi_paranoid)
2001		return false;
2002
2003	if (is_cfi_trap(addr + fineibt_caller_size - LEN_UD2)) {
2004		*target = regs->r11 + fineibt_prefix_size;
2005		*type = regs->ax;
2006
2007		/*
2008		 * Since the trapping instruction is the exact, but LOCK prefixed,
2009		 * Jcc.d8 that got us here, the normal fixup will work.
2010		 */
2011		return true;
2012	}
2013
2014	/*
2015	 * The cfi_paranoid + ITS thunk combination results in:
2016	 *
2017	 *  0:   b8 78 56 34 12          mov    $0x12345678, %eax
2018	 *  5:   41 3b 43 f7             cmp    -11(%r11), %eax
2019	 *  a:   2e 3d 8d 5b f0          cs lea -0x10(%r11), %r11
2020	 *  e:   2e e8 XX XX XX XX	 cs call __x86_indirect_paranoid_thunk_r11
2021	 *
2022	 * Where the paranoid_thunk looks like:
2023	 *
2024	 *  1d:  <d6>                    udb
2025	 *  __x86_indirect_paranoid_thunk_r11:
2026	 *  1e:  75 fd                   jne 1d
2027	 *  __x86_indirect_its_thunk_r11:
2028	 *  20:  41 ff eb                jmp *%r11
2029	 *  23:  cc                      int3
2030	 *
2031	 */
2032	if (is_paranoid_thunk(regs->ip)) {
2033		*target = regs->r11 + fineibt_prefix_size;
2034		*type = regs->ax;
2035
2036		regs->ip = *target;
2037		return true;
2038	}
2039
2040	return false;
2041}
2042
2043bool decode_fineibt_insn(struct pt_regs *regs, unsigned long *target, u32 *type)
2044{
2045	if (decode_fineibt_paranoid(regs, target, type))
2046		return true;
2047
2048	if (decode_fineibt_bhi(regs, target, type))
2049		return true;
2050
2051	return decode_fineibt_preamble(regs, target, type);
2052}
2053
2054#else /* !CONFIG_FINEIBT: */
2055
2056static void __apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
2057			    s32 *start_cfi, s32 *end_cfi, bool builtin)
2058{
2059	if (IS_ENABLED(CONFIG_CFI) && builtin)
2060		pr_info("CFI: Using standard kCFI\n");
2061}
2062
2063#ifdef CONFIG_X86_KERNEL_IBT
2064static void poison_cfi(void *addr) { }
2065#endif
2066
2067#endif /* !CONFIG_FINEIBT */
2068
2069void apply_fineibt(s32 *start_retpoline, s32 *end_retpoline,
2070		   s32 *start_cfi, s32 *end_cfi)
2071{
2072	return __apply_fineibt(start_retpoline, end_retpoline,
2073			       start_cfi, end_cfi,
2074			       /* .builtin = */ false);
2075}
2076
2077#ifdef CONFIG_SMP
2078static void alternatives_smp_lock(const s32 *start, const s32 *end,
2079				  u8 *text, u8 *text_end)
2080{
2081	const s32 *poff;
2082
2083	for (poff = start; poff < end; poff++) {
2084		u8 *ptr = (u8 *)poff + *poff;
2085
2086		if (!*poff || ptr < text || ptr >= text_end)
2087			continue;
2088		/* turn DS segment override prefix into lock prefix */
2089		if (*ptr == 0x3e)
2090			text_poke(ptr, ((unsigned char []){0xf0}), 1);
2091	}
2092}
2093
2094static void alternatives_smp_unlock(const s32 *start, const s32 *end,
2095				    u8 *text, u8 *text_end)
2096{
2097	const s32 *poff;
2098
2099	for (poff = start; poff < end; poff++) {
2100		u8 *ptr = (u8 *)poff + *poff;
2101
2102		if (!*poff || ptr < text || ptr >= text_end)
2103			continue;
2104		/* turn lock prefix into DS segment override prefix */
2105		if (*ptr == 0xf0)
2106			text_poke(ptr, ((unsigned char []){0x3E}), 1);
2107	}
2108}
2109
2110struct smp_alt_module {
2111	/* what is this ??? */
2112	struct module	*mod;
2113	char		*name;
2114
2115	/* ptrs to lock prefixes */
2116	const s32	*locks;
2117	const s32	*locks_end;
2118
2119	/* .text segment, needed to avoid patching init code ;) */
2120	u8		*text;
2121	u8		*text_end;
2122
2123	struct list_head next;
2124};
2125static LIST_HEAD(smp_alt_modules);
2126static bool uniproc_patched = false;	/* protected by text_mutex */
2127
2128void __init_or_module alternatives_smp_module_add(struct module *mod,
2129						  char *name,
2130						  void *locks, void *locks_end,
2131						  void *text,  void *text_end)
2132{
2133	struct smp_alt_module *smp;
2134
2135	mutex_lock(&text_mutex);
2136	if (!uniproc_patched)
2137		goto unlock;
2138
2139	if (num_possible_cpus() == 1)
2140		/* Don't bother remembering, we'll never have to undo it. */
2141		goto smp_unlock;
2142
2143	smp = kzalloc(sizeof(*smp), GFP_KERNEL);
2144	if (NULL == smp)
2145		/* we'll run the (safe but slow) SMP code then ... */
2146		goto unlock;
2147
2148	smp->mod	= mod;
2149	smp->name	= name;
2150	smp->locks	= locks;
2151	smp->locks_end	= locks_end;
2152	smp->text	= text;
2153	smp->text_end	= text_end;
2154	DPRINTK(SMP, "locks %p -> %p, text %p -> %p, name %s\n",
2155		smp->locks, smp->locks_end,
2156		smp->text, smp->text_end, smp->name);
2157
2158	list_add_tail(&smp->next, &smp_alt_modules);
2159smp_unlock:
2160	alternatives_smp_unlock(locks, locks_end, text, text_end);
2161unlock:
2162	mutex_unlock(&text_mutex);
2163}
2164
2165void __init_or_module alternatives_smp_module_del(struct module *mod)
2166{
2167	struct smp_alt_module *item;
2168
2169	mutex_lock(&text_mutex);
2170	list_for_each_entry(item, &smp_alt_modules, next) {
2171		if (mod != item->mod)
2172			continue;
2173		list_del(&item->next);
2174		kfree(item);
2175		break;
2176	}
2177	mutex_unlock(&text_mutex);
2178}
2179
2180void alternatives_enable_smp(void)
2181{
2182	struct smp_alt_module *mod;
2183
2184	/* Why bother if there are no other CPUs? */
2185	BUG_ON(num_possible_cpus() == 1);
2186
2187	mutex_lock(&text_mutex);
2188
2189	if (uniproc_patched) {
2190		pr_info("switching to SMP code\n");
2191		BUG_ON(num_online_cpus() != 1);
2192		clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
2193		clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
2194		list_for_each_entry(mod, &smp_alt_modules, next)
2195			alternatives_smp_lock(mod->locks, mod->locks_end,
2196					      mod->text, mod->text_end);
2197		uniproc_patched = false;
2198	}
2199	mutex_unlock(&text_mutex);
2200}
2201
2202/*
2203 * Return 1 if the address range is reserved for SMP-alternatives.
2204 * Must hold text_mutex.
2205 */
2206int alternatives_text_reserved(void *start, void *end)
2207{
2208	struct smp_alt_module *mod;
2209	const s32 *poff;
2210	u8 *text_start = start;
2211	u8 *text_end = end;
2212
2213	lockdep_assert_held(&text_mutex);
2214
2215	list_for_each_entry(mod, &smp_alt_modules, next) {
2216		if (mod->text > text_end || mod->text_end < text_start)
2217			continue;
2218		for (poff = mod->locks; poff < mod->locks_end; poff++) {
2219			const u8 *ptr = (const u8 *)poff + *poff;
2220
2221			if (text_start <= ptr && text_end > ptr)
2222				return 1;
2223		}
2224	}
2225
2226	return 0;
2227}
2228#endif /* CONFIG_SMP */
2229
2230/*
2231 * Self-test for the INT3 based CALL emulation code.
2232 *
2233 * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
2234 * properly and that there is a stack gap between the INT3 frame and the
2235 * previous context. Without this gap doing a virtual PUSH on the interrupted
2236 * stack would corrupt the INT3 IRET frame.
2237 *
2238 * See entry_{32,64}.S for more details.
2239 */
2240
2241extern void int3_selftest_asm(unsigned int *ptr);
2242
2243asm (
2244"	.pushsection	.init.text, \"ax\", @progbits\n"
2245"	.type		int3_selftest_asm, @function\n"
2246"int3_selftest_asm:\n"
2247	ANNOTATE_NOENDBR "\n"
2248	/*
2249	 * INT3 padded with NOP to CALL_INSN_SIZE. The INT3 triggers an
2250	 * exception, then the int3_exception_nb notifier emulates a call to
2251	 * int3_selftest_callee().
2252	 */
2253"	int3; nop; nop; nop; nop\n"
2254	ASM_RET
2255"	.size		int3_selftest_asm, . - int3_selftest_asm\n"
2256"	.popsection\n"
2257);
2258
2259extern void int3_selftest_callee(unsigned int *ptr);
2260
2261asm (
2262"	.pushsection	.init.text, \"ax\", @progbits\n"
2263"	.type		int3_selftest_callee, @function\n"
2264"int3_selftest_callee:\n"
2265	ANNOTATE_NOENDBR "\n"
2266"	movl	$0x1234, (%" _ASM_ARG1 ")\n"
2267	ASM_RET
2268"	.size		int3_selftest_callee, . - int3_selftest_callee\n"
2269"	.popsection\n"
2270);
2271
2272extern void int3_selftest_ip(void); /* defined in asm below */
2273
2274static int __init
2275int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
2276{
2277	unsigned long selftest = (unsigned long)&int3_selftest_asm;
2278	struct die_args *args = data;
2279	struct pt_regs *regs = args->regs;
2280
2281	OPTIMIZER_HIDE_VAR(selftest);
2282
2283	if (!regs || user_mode(regs))
2284		return NOTIFY_DONE;
2285
2286	if (val != DIE_INT3)
2287		return NOTIFY_DONE;
2288
2289	if (regs->ip - INT3_INSN_SIZE != selftest)
2290		return NOTIFY_DONE;
2291
2292	int3_emulate_call(regs, (unsigned long)&int3_selftest_callee);
2293	return NOTIFY_STOP;
2294}
2295
2296/* Must be noinline to ensure uniqueness of int3_selftest_ip. */
2297static noinline void __init int3_selftest(void)
2298{
2299	static __initdata struct notifier_block int3_exception_nb = {
2300		.notifier_call	= int3_exception_notify,
2301		.priority	= INT_MAX-1, /* last */
2302	};
2303	unsigned int val = 0;
2304
2305	BUG_ON(register_die_notifier(&int3_exception_nb));
2306
2307	/*
2308	 * Basically: int3_selftest_callee(&val); but really complicated :-)
2309	 */
2310	int3_selftest_asm(&val);
2311
2312	BUG_ON(val != 0x1234);
2313
2314	unregister_die_notifier(&int3_exception_nb);
2315}
2316
2317static __initdata int __alt_reloc_selftest_addr;
2318
2319extern void __init __alt_reloc_selftest(void *arg);
2320__visible noinline void __init __alt_reloc_selftest(void *arg)
2321{
2322	WARN_ON(arg != &__alt_reloc_selftest_addr);
2323}
2324
2325static noinline void __init alt_reloc_selftest(void)
2326{
2327	/*
2328	 * Tests text_poke_apply_relocation().
2329	 *
2330	 * This has a relative immediate (CALL) in a place other than the first
2331	 * instruction and additionally on x86_64 we get a RIP-relative LEA:
2332	 *
2333	 *   lea    0x0(%rip),%rdi  # 5d0: R_X86_64_PC32    .init.data+0x5566c
2334	 *   call   +0              # 5d5: R_X86_64_PLT32   __alt_reloc_selftest-0x4
2335	 *
2336	 * Getting this wrong will either crash and burn or tickle the WARN
2337	 * above.
2338	 */
2339	asm_inline volatile (
2340		ALTERNATIVE("", "lea %[mem], %%" _ASM_ARG1 "; call __alt_reloc_selftest;", X86_FEATURE_ALWAYS)
2341		: ASM_CALL_CONSTRAINT
2342		: [mem] "m" (__alt_reloc_selftest_addr)
2343		: _ASM_ARG1
2344	);
2345}
2346
2347void __init alternative_instructions(void)
2348{
2349	u64 ibt;
2350
2351	int3_selftest();
2352
2353	/*
2354	 * The patching is not fully atomic, so try to avoid local
2355	 * interruptions that might execute the to be patched code.
2356	 * Other CPUs are not running.
2357	 */
2358	stop_nmi();
2359
2360	/*
2361	 * Don't stop machine check exceptions while patching.
2362	 * MCEs only happen when something got corrupted and in this
2363	 * case we must do something about the corruption.
2364	 * Ignoring it is worse than an unlikely patching race.
2365	 * Also machine checks tend to be broadcast and if one CPU
2366	 * goes into machine check the others follow quickly, so we don't
2367	 * expect a machine check to cause undue problems during to code
2368	 * patching.
2369	 */
2370
2371	/*
2372	 * Make sure to set (artificial) features depending on used paravirt
2373	 * functions which can later influence alternative patching.
2374	 */
2375	paravirt_set_cap();
2376
2377	/* Keep CET-IBT disabled until caller/callee are patched */
2378	ibt = ibt_save(/*disable*/ true);
2379
2380	__apply_fineibt(__retpoline_sites, __retpoline_sites_end,
2381			__cfi_sites, __cfi_sites_end, true);
2382	cfi_debug = false;
2383
2384	/*
2385	 * Rewrite the retpolines, must be done before alternatives since
2386	 * those can rewrite the retpoline thunks.
2387	 */
2388	apply_retpolines(__retpoline_sites, __retpoline_sites_end);
2389	apply_returns(__return_sites, __return_sites_end);
2390
2391	its_fini_core();
2392
2393	/*
2394	 * Adjust all CALL instructions to point to func()-10, including
2395	 * those in .altinstr_replacement.
2396	 */
2397	callthunks_patch_builtin_calls();
2398
2399	apply_alternatives(__alt_instructions, __alt_instructions_end);
2400
2401	/*
2402	 * Seal all functions that do not have their address taken.
2403	 */
2404	apply_seal_endbr(__ibt_endbr_seal, __ibt_endbr_seal_end);
2405
2406	ibt_restore(ibt);
2407
2408#ifdef CONFIG_SMP
2409	/* Patch to UP if other cpus not imminent. */
2410	if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
2411		uniproc_patched = true;
2412		alternatives_smp_module_add(NULL, "core kernel",
2413					    __smp_locks, __smp_locks_end,
2414					    _text, _etext);
2415	}
2416
2417	if (!uniproc_patched || num_possible_cpus() == 1) {
2418		free_init_pages("SMP alternatives",
2419				(unsigned long)__smp_locks,
2420				(unsigned long)__smp_locks_end);
2421	}
2422#endif
2423
2424	restart_nmi();
2425	alternatives_patched = 1;
2426
2427	alt_reloc_selftest();
2428}
2429
2430/**
2431 * text_poke_early - Update instructions on a live kernel at boot time
2432 * @addr: address to modify
2433 * @opcode: source of the copy
2434 * @len: length to copy
2435 *
2436 * When you use this code to patch more than one byte of an instruction
2437 * you need to make sure that other CPUs cannot execute this code in parallel.
2438 * Also no thread must be currently preempted in the middle of these
2439 * instructions. And on the local CPU you need to be protected against NMI or
2440 * MCE handlers seeing an inconsistent instruction while you patch.
2441 */
2442void __init_or_module text_poke_early(void *addr, const void *opcode,
2443				      size_t len)
2444{
2445	unsigned long flags;
2446
2447	if (boot_cpu_has(X86_FEATURE_NX) &&
2448	    is_module_text_address((unsigned long)addr)) {
2449		/*
2450		 * Modules text is marked initially as non-executable, so the
2451		 * code cannot be running and speculative code-fetches are
2452		 * prevented. Just change the code.
2453		 */
2454		memcpy(addr, opcode, len);
2455	} else {
2456		local_irq_save(flags);
2457		memcpy(addr, opcode, len);
2458		sync_core();
2459		local_irq_restore(flags);
2460
2461		/*
2462		 * Could also do a CLFLUSH here to speed up CPU recovery; but
2463		 * that causes hangs on some VIA CPUs.
2464		 */
2465	}
2466}
2467
2468__ro_after_init struct mm_struct *text_poke_mm;
2469__ro_after_init unsigned long text_poke_mm_addr;
2470
2471/*
2472 * Text poking creates and uses a mapping in the lower half of the
2473 * address space. Relax LASS enforcement when accessing the poking
2474 * address.
2475 *
2476 * objtool enforces a strict policy of "no function calls within AC=1
2477 * regions". Adhere to the policy by using inline versions of
2478 * memcpy()/memset() that will never result in a function call.
2479 */
2480
2481static void text_poke_memcpy(void *dst, const void *src, size_t len)
2482{
2483	lass_stac();
2484	__inline_memcpy(dst, src, len);
2485	lass_clac();
2486}
2487
2488static void text_poke_memset(void *dst, const void *src, size_t len)
2489{
2490	int c = *(const int *)src;
2491
2492	lass_stac();
2493	__inline_memset(dst, c, len);
2494	lass_clac();
2495}
2496
2497typedef void text_poke_f(void *dst, const void *src, size_t len);
2498
2499static void *__text_poke(text_poke_f func, void *addr, const void *src, size_t len)
2500{
2501	bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
2502	struct page *pages[2] = {NULL};
2503	struct mm_struct *prev_mm;
2504	unsigned long flags;
2505	pte_t pte, *ptep;
2506	spinlock_t *ptl;
2507	pgprot_t pgprot;
2508
2509	/*
2510	 * While boot memory allocator is running we cannot use struct pages as
2511	 * they are not yet initialized. There is no way to recover.
2512	 */
2513	BUG_ON(!after_bootmem);
2514
2515	if (!core_kernel_text((unsigned long)addr)) {
2516		pages[0] = vmalloc_to_page(addr);
2517		if (cross_page_boundary)
2518			pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
2519	} else {
2520		pages[0] = virt_to_page(addr);
2521		WARN_ON(!PageReserved(pages[0]));
2522		if (cross_page_boundary)
2523			pages[1] = virt_to_page(addr + PAGE_SIZE);
2524	}
2525	/*
2526	 * If something went wrong, crash and burn since recovery paths are not
2527	 * implemented.
2528	 */
2529	BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
2530
2531	/*
2532	 * Map the page without the global bit, as TLB flushing is done with
2533	 * flush_tlb_mm_range(), which is intended for non-global PTEs.
2534	 */
2535	pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
2536
2537	/*
2538	 * The lock is not really needed, but this allows to avoid open-coding.
2539	 */
2540	ptep = get_locked_pte(text_poke_mm, text_poke_mm_addr, &ptl);
2541
2542	/*
2543	 * This must not fail; preallocated in poking_init().
2544	 */
2545	VM_BUG_ON(!ptep);
2546
2547	local_irq_save(flags);
2548
2549	pte = mk_pte(pages[0], pgprot);
2550	set_pte_at(text_poke_mm, text_poke_mm_addr, ptep, pte);
2551
2552	if (cross_page_boundary) {
2553		pte = mk_pte(pages[1], pgprot);
2554		set_pte_at(text_poke_mm, text_poke_mm_addr + PAGE_SIZE, ptep + 1, pte);
2555	}
2556
2557	/*
2558	 * Loading the temporary mm behaves as a compiler barrier, which
2559	 * guarantees that the PTE will be set at the time memcpy() is done.
2560	 */
2561	prev_mm = use_temporary_mm(text_poke_mm);
2562
2563	kasan_disable_current();
2564	func((u8 *)text_poke_mm_addr + offset_in_page(addr), src, len);
2565	kasan_enable_current();
2566
2567	/*
2568	 * Ensure that the PTE is only cleared after the instructions of memcpy
2569	 * were issued by using a compiler barrier.
2570	 */
2571	barrier();
2572
2573	pte_clear(text_poke_mm, text_poke_mm_addr, ptep);
2574	if (cross_page_boundary)
2575		pte_clear(text_poke_mm, text_poke_mm_addr + PAGE_SIZE, ptep + 1);
2576
2577	/*
2578	 * Loading the previous page-table hierarchy requires a serializing
2579	 * instruction that already allows the core to see the updated version.
2580	 * Xen-PV is assumed to serialize execution in a similar manner.
2581	 */
2582	unuse_temporary_mm(prev_mm);
2583
2584	/*
2585	 * Flushing the TLB might involve IPIs, which would require enabled
2586	 * IRQs, but not if the mm is not used, as it is in this point.
2587	 */
2588	flush_tlb_mm_range(text_poke_mm, text_poke_mm_addr, text_poke_mm_addr +
2589			   (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
2590			   PAGE_SHIFT, false);
2591
2592	if (func == text_poke_memcpy) {
2593		/*
2594		 * If the text does not match what we just wrote then something is
2595		 * fundamentally screwy; there's nothing we can really do about that.
2596		 */
2597		BUG_ON(memcmp(addr, src, len));
2598	}
2599
2600	local_irq_restore(flags);
2601	pte_unmap_unlock(ptep, ptl);
2602	return addr;
2603}
2604
2605/**
2606 * text_poke - Update instructions on a live kernel
2607 * @addr: address to modify
2608 * @opcode: source of the copy
2609 * @len: length to copy
2610 *
2611 * Only atomic text poke/set should be allowed when not doing early patching.
2612 * It means the size must be writable atomically and the address must be aligned
2613 * in a way that permits an atomic write. It also makes sure we fit on a single
2614 * page.
2615 *
2616 * Note that the caller must ensure that if the modified code is part of a
2617 * module, the module would not be removed during poking. This can be achieved
2618 * by registering a module notifier, and ordering module removal and patching
2619 * through a mutex.
2620 */
2621void *text_poke(void *addr, const void *opcode, size_t len)
2622{
2623	lockdep_assert_held(&text_mutex);
2624
2625	return __text_poke(text_poke_memcpy, addr, opcode, len);
2626}
2627
2628/**
2629 * text_poke_kgdb - Update instructions on a live kernel by kgdb
2630 * @addr: address to modify
2631 * @opcode: source of the copy
2632 * @len: length to copy
2633 *
2634 * Only atomic text poke/set should be allowed when not doing early patching.
2635 * It means the size must be writable atomically and the address must be aligned
2636 * in a way that permits an atomic write. It also makes sure we fit on a single
2637 * page.
2638 *
2639 * Context: should only be used by kgdb, which ensures no other core is running,
2640 *	    despite the fact it does not hold the text_mutex.
2641 */
2642void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
2643{
2644	return __text_poke(text_poke_memcpy, addr, opcode, len);
2645}
2646
2647void *text_poke_copy_locked(void *addr, const void *opcode, size_t len,
2648			    bool core_ok)
2649{
2650	unsigned long start = (unsigned long)addr;
2651	size_t patched = 0;
2652
2653	if (WARN_ON_ONCE(!core_ok && core_kernel_text(start)))
2654		return NULL;
2655
2656	while (patched < len) {
2657		unsigned long ptr = start + patched;
2658		size_t s;
2659
2660		s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
2661
2662		__text_poke(text_poke_memcpy, (void *)ptr, opcode + patched, s);
2663		patched += s;
2664	}
2665	return addr;
2666}
2667
2668/**
2669 * text_poke_copy - Copy instructions into (an unused part of) RX memory
2670 * @addr: address to modify
2671 * @opcode: source of the copy
2672 * @len: length to copy, could be more than 2x PAGE_SIZE
2673 *
2674 * Not safe against concurrent execution; useful for JITs to dump
2675 * new code blocks into unused regions of RX memory. Can be used in
2676 * conjunction with synchronize_rcu_tasks() to wait for existing
2677 * execution to quiesce after having made sure no existing functions
2678 * pointers are live.
2679 */
2680void *text_poke_copy(void *addr, const void *opcode, size_t len)
2681{
2682	mutex_lock(&text_mutex);
2683	addr = text_poke_copy_locked(addr, opcode, len, false);
2684	mutex_unlock(&text_mutex);
2685	return addr;
2686}
2687
2688/**
2689 * text_poke_set - memset into (an unused part of) RX memory
2690 * @addr: address to modify
2691 * @c: the byte to fill the area with
2692 * @len: length to copy, could be more than 2x PAGE_SIZE
2693 *
2694 * This is useful to overwrite unused regions of RX memory with illegal
2695 * instructions.
2696 */
2697void *text_poke_set(void *addr, int c, size_t len)
2698{
2699	unsigned long start = (unsigned long)addr;
2700	size_t patched = 0;
2701
2702	if (WARN_ON_ONCE(core_kernel_text(start)))
2703		return NULL;
2704
2705	mutex_lock(&text_mutex);
2706	while (patched < len) {
2707		unsigned long ptr = start + patched;
2708		size_t s;
2709
2710		s = min_t(size_t, PAGE_SIZE * 2 - offset_in_page(ptr), len - patched);
2711
2712		__text_poke(text_poke_memset, (void *)ptr, (void *)&c, s);
2713		patched += s;
2714	}
2715	mutex_unlock(&text_mutex);
2716	return addr;
2717}
2718
2719static void do_sync_core(void *info)
2720{
2721	sync_core();
2722}
2723
2724void smp_text_poke_sync_each_cpu(void)
2725{
2726	on_each_cpu(do_sync_core, NULL, 1);
2727}
2728
2729/*
2730 * NOTE: crazy scheme to allow patching Jcc.d32 but not increase the size of
2731 * this thing. When len == 6 everything is prefixed with 0x0f and we map
2732 * opcode to Jcc.d8, using len to distinguish.
2733 */
2734struct smp_text_poke_loc {
2735	/* addr := _stext + rel_addr */
2736	s32 rel_addr;
2737	s32 disp;
2738	u8 len;
2739	u8 opcode;
2740	const u8 text[TEXT_POKE_MAX_OPCODE_SIZE];
2741	/* see smp_text_poke_batch_finish() */
2742	u8 old;
2743};
2744
2745#define TEXT_POKE_ARRAY_MAX (PAGE_SIZE / sizeof(struct smp_text_poke_loc))
2746
2747static struct smp_text_poke_array {
2748	struct smp_text_poke_loc vec[TEXT_POKE_ARRAY_MAX];
2749	int nr_entries;
2750} text_poke_array;
2751
2752static DEFINE_PER_CPU(atomic_t, text_poke_array_refs);
2753
2754/*
2755 * These four __always_inline annotations imply noinstr, necessary
2756 * due to smp_text_poke_int3_handler() being noinstr:
2757 */
2758
2759static __always_inline bool try_get_text_poke_array(void)
2760{
2761	atomic_t *refs = this_cpu_ptr(&text_poke_array_refs);
2762
2763	if (!raw_atomic_inc_not_zero(refs))
2764		return false;
2765
2766	return true;
2767}
2768
2769static __always_inline void put_text_poke_array(void)
2770{
2771	atomic_t *refs = this_cpu_ptr(&text_poke_array_refs);
2772
2773	smp_mb__before_atomic();
2774	raw_atomic_dec(refs);
2775}
2776
2777static __always_inline void *text_poke_addr(const struct smp_text_poke_loc *tpl)
2778{
2779	return _stext + tpl->rel_addr;
2780}
2781
2782static __always_inline int patch_cmp(const void *tpl_a, const void *tpl_b)
2783{
2784	if (tpl_a < text_poke_addr(tpl_b))
2785		return -1;
2786	if (tpl_a > text_poke_addr(tpl_b))
2787		return 1;
2788	return 0;
2789}
2790
2791noinstr int smp_text_poke_int3_handler(struct pt_regs *regs)
2792{
2793	struct smp_text_poke_loc *tpl;
2794	int ret = 0;
2795	void *ip;
2796
2797	if (user_mode(regs))
2798		return 0;
2799
2800	/*
2801	 * Having observed our INT3 instruction, we now must observe
2802	 * text_poke_array with non-zero refcount:
2803	 *
2804	 *	text_poke_array_refs = 1		INT3
2805	 *	WMB			RMB
2806	 *	write INT3		if (text_poke_array_refs != 0)
2807	 */
2808	smp_rmb();
2809
2810	if (!try_get_text_poke_array())
2811		return 0;
2812
2813	/*
2814	 * Discount the INT3. See smp_text_poke_batch_finish().
2815	 */
2816	ip = (void *) regs->ip - INT3_INSN_SIZE;
2817
2818	/*
2819	 * Skip the binary search if there is a single member in the vector.
2820	 */
2821	if (unlikely(text_poke_array.nr_entries > 1)) {
2822		tpl = __inline_bsearch(ip, text_poke_array.vec, text_poke_array.nr_entries,
2823				      sizeof(struct smp_text_poke_loc),
2824				      patch_cmp);
2825		if (!tpl)
2826			goto out_put;
2827	} else {
2828		tpl = text_poke_array.vec;
2829		if (text_poke_addr(tpl) != ip)
2830			goto out_put;
2831	}
2832
2833	ip += tpl->len;
2834
2835	switch (tpl->opcode) {
2836	case INT3_INSN_OPCODE:
2837		/*
2838		 * Someone poked an explicit INT3, they'll want to handle it,
2839		 * do not consume.
2840		 */
2841		goto out_put;
2842
2843	case RET_INSN_OPCODE:
2844		int3_emulate_ret(regs);
2845		break;
2846
2847	case CALL_INSN_OPCODE:
2848		int3_emulate_call(regs, (long)ip + tpl->disp);
2849		break;
2850
2851	case JMP32_INSN_OPCODE:
2852	case JMP8_INSN_OPCODE:
2853		int3_emulate_jmp(regs, (long)ip + tpl->disp);
2854		break;
2855
2856	case 0x70 ... 0x7f: /* Jcc */
2857		int3_emulate_jcc(regs, tpl->opcode & 0xf, (long)ip, tpl->disp);
2858		break;
2859
2860	default:
2861		BUG();
2862	}
2863
2864	ret = 1;
2865
2866out_put:
2867	put_text_poke_array();
2868	return ret;
2869}
2870
2871/**
2872 * smp_text_poke_batch_finish() -- update instructions on live kernel on SMP
2873 *
2874 * Input state:
2875 *  text_poke_array.vec: vector of instructions to patch
2876 *  text_poke_array.nr_entries: number of entries in the vector
2877 *
2878 * Modify multi-byte instructions by using INT3 breakpoints on SMP.
2879 * We completely avoid using stop_machine() here, and achieve the
2880 * synchronization using INT3 breakpoints and SMP cross-calls.
2881 *
2882 * The way it is done:
2883 *	- For each entry in the vector:
2884 *		- add an INT3 trap to the address that will be patched
2885 *	- SMP sync all CPUs
2886 *	- For each entry in the vector:
2887 *		- update all but the first byte of the patched range
2888 *	- SMP sync all CPUs
2889 *	- For each entry in the vector:
2890 *		- replace the first byte (INT3) by the first byte of the
2891 *		  replacing opcode
2892 *	- SMP sync all CPUs
2893 */
2894void smp_text_poke_batch_finish(void)
2895{
2896	unsigned char int3 = INT3_INSN_OPCODE;
2897	unsigned int i;
2898	int do_sync;
2899
2900	if (!text_poke_array.nr_entries)
2901		return;
2902
2903	lockdep_assert_held(&text_mutex);
2904
2905	/*
2906	 * Corresponds to the implicit memory barrier in try_get_text_poke_array() to
2907	 * ensure reading a non-zero refcount provides up to date text_poke_array data.
2908	 */
2909	for_each_possible_cpu(i)
2910		atomic_set_release(per_cpu_ptr(&text_poke_array_refs, i), 1);
2911
2912	/*
2913	 * Function tracing can enable thousands of places that need to be
2914	 * updated. This can take quite some time, and with full kernel debugging
2915	 * enabled, this could cause the softlockup watchdog to trigger.
2916	 * This function gets called every 256 entries added to be patched.
2917	 * Call cond_resched() here to make sure that other tasks can get scheduled
2918	 * while processing all the functions being patched.
2919	 */
2920	cond_resched();
2921
2922	/*
2923	 * Corresponding read barrier in INT3 notifier for making sure the
2924	 * text_poke_array.nr_entries and handler are correctly ordered wrt. patching.
2925	 */
2926	smp_wmb();
2927
2928	/*
2929	 * First step: add a INT3 trap to the address that will be patched.
2930	 */
2931	for (i = 0; i < text_poke_array.nr_entries; i++) {
2932		text_poke_array.vec[i].old = *(u8 *)text_poke_addr(&text_poke_array.vec[i]);
2933		text_poke(text_poke_addr(&text_poke_array.vec[i]), &int3, INT3_INSN_SIZE);
2934	}
2935
2936	smp_text_poke_sync_each_cpu();
2937
2938	/*
2939	 * Second step: update all but the first byte of the patched range.
2940	 */
2941	for (do_sync = 0, i = 0; i < text_poke_array.nr_entries; i++) {
2942		u8 old[TEXT_POKE_MAX_OPCODE_SIZE+1] = { text_poke_array.vec[i].old, };
2943		u8 _new[TEXT_POKE_MAX_OPCODE_SIZE+1];
2944		const u8 *new = text_poke_array.vec[i].text;
2945		int len = text_poke_array.vec[i].len;
2946
2947		if (len - INT3_INSN_SIZE > 0) {
2948			memcpy(old + INT3_INSN_SIZE,
2949			       text_poke_addr(&text_poke_array.vec[i]) + INT3_INSN_SIZE,
2950			       len - INT3_INSN_SIZE);
2951
2952			if (len == 6) {
2953				_new[0] = 0x0f;
2954				memcpy(_new + 1, new, 5);
2955				new = _new;
2956			}
2957
2958			text_poke(text_poke_addr(&text_poke_array.vec[i]) + INT3_INSN_SIZE,
2959				  new + INT3_INSN_SIZE,
2960				  len - INT3_INSN_SIZE);
2961
2962			do_sync++;
2963		}
2964
2965		/*
2966		 * Emit a perf event to record the text poke, primarily to
2967		 * support Intel PT decoding which must walk the executable code
2968		 * to reconstruct the trace. The flow up to here is:
2969		 *   - write INT3 byte
2970		 *   - IPI-SYNC
2971		 *   - write instruction tail
2972		 * At this point the actual control flow will be through the
2973		 * INT3 and handler and not hit the old or new instruction.
2974		 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
2975		 * can still be decoded. Subsequently:
2976		 *   - emit RECORD_TEXT_POKE with the new instruction
2977		 *   - IPI-SYNC
2978		 *   - write first byte
2979		 *   - IPI-SYNC
2980		 * So before the text poke event timestamp, the decoder will see
2981		 * either the old instruction flow or FUP/TIP of INT3. After the
2982		 * text poke event timestamp, the decoder will see either the
2983		 * new instruction flow or FUP/TIP of INT3. Thus decoders can
2984		 * use the timestamp as the point at which to modify the
2985		 * executable code.
2986		 * The old instruction is recorded so that the event can be
2987		 * processed forwards or backwards.
2988		 */
2989		perf_event_text_poke(text_poke_addr(&text_poke_array.vec[i]), old, len, new, len);
2990	}
2991
2992	if (do_sync) {
2993		/*
2994		 * According to Intel, this core syncing is very likely
2995		 * not necessary and we'd be safe even without it. But
2996		 * better safe than sorry (plus there's not only Intel).
2997		 */
2998		smp_text_poke_sync_each_cpu();
2999	}
3000
3001	/*
3002	 * Third step: replace the first byte (INT3) by the first byte of the
3003	 * replacing opcode.
3004	 */
3005	for (do_sync = 0, i = 0; i < text_poke_array.nr_entries; i++) {
3006		u8 byte = text_poke_array.vec[i].text[0];
3007
3008		if (text_poke_array.vec[i].len == 6)
3009			byte = 0x0f;
3010
3011		if (byte == INT3_INSN_OPCODE)
3012			continue;
3013
3014		text_poke(text_poke_addr(&text_poke_array.vec[i]), &byte, INT3_INSN_SIZE);
3015		do_sync++;
3016	}
3017
3018	if (do_sync)
3019		smp_text_poke_sync_each_cpu();
3020
3021	/*
3022	 * Remove and wait for refs to be zero.
3023	 *
3024	 * Notably, if after step-3 above the INT3 got removed, then the
3025	 * smp_text_poke_sync_each_cpu() will have serialized against any running INT3
3026	 * handlers and the below spin-wait will not happen.
3027	 *
3028	 * IOW. unless the replacement instruction is INT3, this case goes
3029	 * unused.
3030	 */
3031	for_each_possible_cpu(i) {
3032		atomic_t *refs = per_cpu_ptr(&text_poke_array_refs, i);
3033
3034		if (unlikely(!atomic_dec_and_test(refs)))
3035			atomic_cond_read_acquire(refs, !VAL);
3036	}
3037
3038	/* They are all completed: */
3039	text_poke_array.nr_entries = 0;
3040}
3041
3042static void __smp_text_poke_batch_add(void *addr, const void *opcode, size_t len, const void *emulate)
3043{
3044	struct smp_text_poke_loc *tpl;
3045	struct insn insn;
3046	int ret, i = 0;
3047
3048	tpl = &text_poke_array.vec[text_poke_array.nr_entries++];
3049
3050	if (len == 6)
3051		i = 1;
3052	memcpy((void *)tpl->text, opcode+i, len-i);
3053	if (!emulate)
3054		emulate = opcode;
3055
3056	ret = insn_decode_kernel(&insn, emulate);
3057	BUG_ON(ret < 0);
3058
3059	tpl->rel_addr = addr - (void *)_stext;
3060	tpl->len = len;
3061	tpl->opcode = insn.opcode.bytes[0];
3062
3063	if (is_jcc32(&insn)) {
3064		/*
3065		 * Map Jcc.d32 onto Jcc.d8 and use len to distinguish.
3066		 */
3067		tpl->opcode = insn.opcode.bytes[1] - 0x10;
3068	}
3069
3070	switch (tpl->opcode) {
3071	case RET_INSN_OPCODE:
3072	case JMP32_INSN_OPCODE:
3073	case JMP8_INSN_OPCODE:
3074		/*
3075		 * Control flow instructions without implied execution of the
3076		 * next instruction can be padded with INT3.
3077		 */
3078		for (i = insn.length; i < len; i++)
3079			BUG_ON(tpl->text[i] != INT3_INSN_OPCODE);
3080		break;
3081
3082	default:
3083		BUG_ON(len != insn.length);
3084	}
3085
3086	switch (tpl->opcode) {
3087	case INT3_INSN_OPCODE:
3088	case RET_INSN_OPCODE:
3089		break;
3090
3091	case CALL_INSN_OPCODE:
3092	case JMP32_INSN_OPCODE:
3093	case JMP8_INSN_OPCODE:
3094	case 0x70 ... 0x7f: /* Jcc */
3095		tpl->disp = insn.immediate.value;
3096		break;
3097
3098	default: /* assume NOP */
3099		switch (len) {
3100		case 2: /* NOP2 -- emulate as JMP8+0 */
3101			BUG_ON(memcmp(emulate, x86_nops[len], len));
3102			tpl->opcode = JMP8_INSN_OPCODE;
3103			tpl->disp = 0;
3104			break;
3105
3106		case 5: /* NOP5 -- emulate as JMP32+0 */
3107			BUG_ON(memcmp(emulate, x86_nops[len], len));
3108			tpl->opcode = JMP32_INSN_OPCODE;
3109			tpl->disp = 0;
3110			break;
3111
3112		default: /* unknown instruction */
3113			BUG();
3114		}
3115		break;
3116	}
3117}
3118
3119/*
3120 * We hard rely on the text_poke_array.vec being ordered; ensure this is so by flushing
3121 * early if needed.
3122 */
3123static bool text_poke_addr_ordered(void *addr)
3124{
3125	WARN_ON_ONCE(!addr);
3126
3127	if (!text_poke_array.nr_entries)
3128		return true;
3129
3130	/*
3131	 * If the last current entry's address is higher than the
3132	 * new entry's address we'd like to add, then ordering
3133	 * is violated and we must first flush all pending patching
3134	 * requests:
3135	 */
3136	if (text_poke_addr(text_poke_array.vec + text_poke_array.nr_entries-1) > addr)
3137		return false;
3138
3139	return true;
3140}
3141
3142/**
3143 * smp_text_poke_batch_add() -- update instruction on live kernel on SMP, batched
3144 * @addr:	address to patch
3145 * @opcode:	opcode of new instruction
3146 * @len:	length to copy
3147 * @emulate:	instruction to be emulated
3148 *
3149 * Add a new instruction to the current queue of to-be-patched instructions
3150 * the kernel maintains. The patching request will not be executed immediately,
3151 * but becomes part of an array of patching requests, optimized for batched
3152 * execution. All pending patching requests will be executed on the next
3153 * smp_text_poke_batch_finish() call.
3154 */
3155void __ref smp_text_poke_batch_add(void *addr, const void *opcode, size_t len, const void *emulate)
3156{
3157	if (text_poke_array.nr_entries == TEXT_POKE_ARRAY_MAX || !text_poke_addr_ordered(addr))
3158		smp_text_poke_batch_finish();
3159	__smp_text_poke_batch_add(addr, opcode, len, emulate);
3160}
3161
3162/**
3163 * smp_text_poke_single() -- update instruction on live kernel on SMP immediately
3164 * @addr:	address to patch
3165 * @opcode:	opcode of new instruction
3166 * @len:	length to copy
3167 * @emulate:	instruction to be emulated
3168 *
3169 * Update a single instruction with the vector in the stack, avoiding
3170 * dynamically allocated memory. This function should be used when it is
3171 * not possible to allocate memory for a vector. The single instruction
3172 * is patched in immediately.
3173 */
3174void __ref smp_text_poke_single(void *addr, const void *opcode, size_t len, const void *emulate)
3175{
3176	smp_text_poke_batch_add(addr, opcode, len, emulate);
3177	smp_text_poke_batch_finish();
3178}
~/ Read-only file preview.