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