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