• 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/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/asm-prototypes.h>
32 
33 int __read_mostly alternatives_patched;
34 
35 EXPORT_SYMBOL_GPL(alternatives_patched);
36 
37 #define MAX_PATCH_LEN (255-1)
38 
39 static int __initdata_or_module debug_alternative;
40 
debug_alt(char * str)41 static int __init debug_alt(char *str)
42 {
43 	debug_alternative = 1;
44 	return 1;
45 }
46 __setup("debug-alternative", debug_alt);
47 
48 static int noreplace_smp;
49 
setup_noreplace_smp(char * str)50 static int __init setup_noreplace_smp(char *str)
51 {
52 	noreplace_smp = 1;
53 	return 1;
54 }
55 __setup("noreplace-smp", setup_noreplace_smp);
56 
57 #define DPRINTK(fmt, args...)						\
58 do {									\
59 	if (debug_alternative)						\
60 		printk(KERN_DEBUG pr_fmt(fmt) "\n", ##args);		\
61 } while (0)
62 
63 #define DUMP_BYTES(buf, len, fmt, args...)				\
64 do {									\
65 	if (unlikely(debug_alternative)) {				\
66 		int j;							\
67 									\
68 		if (!(len))						\
69 			break;						\
70 									\
71 		printk(KERN_DEBUG pr_fmt(fmt), ##args);			\
72 		for (j = 0; j < (len) - 1; j++)				\
73 			printk(KERN_CONT "%02hhx ", buf[j]);		\
74 		printk(KERN_CONT "%02hhx\n", buf[j]);			\
75 	}								\
76 } while (0)
77 
78 /*
79  * Each GENERIC_NOPX is of X bytes, and defined as an array of bytes
80  * that correspond to that nop. Getting from one nop to the next, we
81  * add to the array the offset that is equal to the sum of all sizes of
82  * nops preceding the one we are after.
83  *
84  * Note: The GENERIC_NOP5_ATOMIC is at the end, as it breaks the
85  * nice symmetry of sizes of the previous nops.
86  */
87 #if defined(GENERIC_NOP1) && !defined(CONFIG_X86_64)
88 static const unsigned char intelnops[] =
89 {
90 	GENERIC_NOP1,
91 	GENERIC_NOP2,
92 	GENERIC_NOP3,
93 	GENERIC_NOP4,
94 	GENERIC_NOP5,
95 	GENERIC_NOP6,
96 	GENERIC_NOP7,
97 	GENERIC_NOP8,
98 	GENERIC_NOP5_ATOMIC
99 };
100 static const unsigned char * const intel_nops[ASM_NOP_MAX+2] =
101 {
102 	NULL,
103 	intelnops,
104 	intelnops + 1,
105 	intelnops + 1 + 2,
106 	intelnops + 1 + 2 + 3,
107 	intelnops + 1 + 2 + 3 + 4,
108 	intelnops + 1 + 2 + 3 + 4 + 5,
109 	intelnops + 1 + 2 + 3 + 4 + 5 + 6,
110 	intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
111 	intelnops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
112 };
113 #endif
114 
115 #ifdef K8_NOP1
116 static const unsigned char k8nops[] =
117 {
118 	K8_NOP1,
119 	K8_NOP2,
120 	K8_NOP3,
121 	K8_NOP4,
122 	K8_NOP5,
123 	K8_NOP6,
124 	K8_NOP7,
125 	K8_NOP8,
126 	K8_NOP5_ATOMIC
127 };
128 static const unsigned char * const k8_nops[ASM_NOP_MAX+2] =
129 {
130 	NULL,
131 	k8nops,
132 	k8nops + 1,
133 	k8nops + 1 + 2,
134 	k8nops + 1 + 2 + 3,
135 	k8nops + 1 + 2 + 3 + 4,
136 	k8nops + 1 + 2 + 3 + 4 + 5,
137 	k8nops + 1 + 2 + 3 + 4 + 5 + 6,
138 	k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
139 	k8nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
140 };
141 #endif
142 
143 #if defined(K7_NOP1) && !defined(CONFIG_X86_64)
144 static const unsigned char k7nops[] =
145 {
146 	K7_NOP1,
147 	K7_NOP2,
148 	K7_NOP3,
149 	K7_NOP4,
150 	K7_NOP5,
151 	K7_NOP6,
152 	K7_NOP7,
153 	K7_NOP8,
154 	K7_NOP5_ATOMIC
155 };
156 static const unsigned char * const k7_nops[ASM_NOP_MAX+2] =
157 {
158 	NULL,
159 	k7nops,
160 	k7nops + 1,
161 	k7nops + 1 + 2,
162 	k7nops + 1 + 2 + 3,
163 	k7nops + 1 + 2 + 3 + 4,
164 	k7nops + 1 + 2 + 3 + 4 + 5,
165 	k7nops + 1 + 2 + 3 + 4 + 5 + 6,
166 	k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
167 	k7nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
168 };
169 #endif
170 
171 #ifdef P6_NOP1
172 static const unsigned char p6nops[] =
173 {
174 	P6_NOP1,
175 	P6_NOP2,
176 	P6_NOP3,
177 	P6_NOP4,
178 	P6_NOP5,
179 	P6_NOP6,
180 	P6_NOP7,
181 	P6_NOP8,
182 	P6_NOP5_ATOMIC
183 };
184 static const unsigned char * const p6_nops[ASM_NOP_MAX+2] =
185 {
186 	NULL,
187 	p6nops,
188 	p6nops + 1,
189 	p6nops + 1 + 2,
190 	p6nops + 1 + 2 + 3,
191 	p6nops + 1 + 2 + 3 + 4,
192 	p6nops + 1 + 2 + 3 + 4 + 5,
193 	p6nops + 1 + 2 + 3 + 4 + 5 + 6,
194 	p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7,
195 	p6nops + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,
196 };
197 #endif
198 
199 /* Initialize these to a safe default */
200 #ifdef CONFIG_X86_64
201 const unsigned char * const *ideal_nops = p6_nops;
202 #else
203 const unsigned char * const *ideal_nops = intel_nops;
204 #endif
205 
arch_init_ideal_nops(void)206 void __init arch_init_ideal_nops(void)
207 {
208 	switch (boot_cpu_data.x86_vendor) {
209 	case X86_VENDOR_INTEL:
210 		/*
211 		 * Due to a decoder implementation quirk, some
212 		 * specific Intel CPUs actually perform better with
213 		 * the "k8_nops" than with the SDM-recommended NOPs.
214 		 */
215 		if (boot_cpu_data.x86 == 6 &&
216 		    boot_cpu_data.x86_model >= 0x0f &&
217 		    boot_cpu_data.x86_model != 0x1c &&
218 		    boot_cpu_data.x86_model != 0x26 &&
219 		    boot_cpu_data.x86_model != 0x27 &&
220 		    boot_cpu_data.x86_model < 0x30) {
221 			ideal_nops = k8_nops;
222 		} else if (boot_cpu_has(X86_FEATURE_NOPL)) {
223 			   ideal_nops = p6_nops;
224 		} else {
225 #ifdef CONFIG_X86_64
226 			ideal_nops = k8_nops;
227 #else
228 			ideal_nops = intel_nops;
229 #endif
230 		}
231 		break;
232 
233 	case X86_VENDOR_HYGON:
234 		ideal_nops = p6_nops;
235 		return;
236 
237 	case X86_VENDOR_AMD:
238 		if (boot_cpu_data.x86 > 0xf) {
239 			ideal_nops = p6_nops;
240 			return;
241 		}
242 
243 		fallthrough;
244 
245 	default:
246 #ifdef CONFIG_X86_64
247 		ideal_nops = k8_nops;
248 #else
249 		if (boot_cpu_has(X86_FEATURE_K8))
250 			ideal_nops = k8_nops;
251 		else if (boot_cpu_has(X86_FEATURE_K7))
252 			ideal_nops = k7_nops;
253 		else
254 			ideal_nops = intel_nops;
255 #endif
256 	}
257 }
258 
259 /* Use this to add nops to a buffer, then text_poke the whole buffer. */
add_nops(void * insns,unsigned int len)260 static void __init_or_module add_nops(void *insns, unsigned int len)
261 {
262 	while (len > 0) {
263 		unsigned int noplen = len;
264 		if (noplen > ASM_NOP_MAX)
265 			noplen = ASM_NOP_MAX;
266 		memcpy(insns, ideal_nops[noplen], noplen);
267 		insns += noplen;
268 		len -= noplen;
269 	}
270 }
271 
272 extern s32 __retpoline_sites[], __retpoline_sites_end[];
273 extern s32 __return_sites[], __return_sites_end[];
274 extern struct alt_instr __alt_instructions[], __alt_instructions_end[];
275 extern s32 __smp_locks[], __smp_locks_end[];
276 void text_poke_early(void *addr, const void *opcode, size_t len);
277 
278 /*
279  * Are we looking at a near JMP with a 1 or 4-byte displacement.
280  */
is_jmp(const u8 opcode)281 static inline bool is_jmp(const u8 opcode)
282 {
283 	return opcode == 0xeb || opcode == 0xe9;
284 }
285 
286 static void __init_or_module
recompute_jump(struct alt_instr * a,u8 * orig_insn,u8 * repl_insn,u8 * insn_buff)287 recompute_jump(struct alt_instr *a, u8 *orig_insn, u8 *repl_insn, u8 *insn_buff)
288 {
289 	u8 *next_rip, *tgt_rip;
290 	s32 n_dspl, o_dspl;
291 	int repl_len;
292 
293 	if (a->replacementlen != 5)
294 		return;
295 
296 	o_dspl = *(s32 *)(insn_buff + 1);
297 
298 	/* next_rip of the replacement JMP */
299 	next_rip = repl_insn + a->replacementlen;
300 	/* target rip of the replacement JMP */
301 	tgt_rip  = next_rip + o_dspl;
302 	n_dspl = tgt_rip - orig_insn;
303 
304 	DPRINTK("target RIP: %px, new_displ: 0x%x", tgt_rip, n_dspl);
305 
306 	if (tgt_rip - orig_insn >= 0) {
307 		if (n_dspl - 2 <= 127)
308 			goto two_byte_jmp;
309 		else
310 			goto five_byte_jmp;
311 	/* negative offset */
312 	} else {
313 		if (((n_dspl - 2) & 0xff) == (n_dspl - 2))
314 			goto two_byte_jmp;
315 		else
316 			goto five_byte_jmp;
317 	}
318 
319 two_byte_jmp:
320 	n_dspl -= 2;
321 
322 	insn_buff[0] = 0xeb;
323 	insn_buff[1] = (s8)n_dspl;
324 	add_nops(insn_buff + 2, 3);
325 
326 	repl_len = 2;
327 	goto done;
328 
329 five_byte_jmp:
330 	n_dspl -= 5;
331 
332 	insn_buff[0] = 0xe9;
333 	*(s32 *)&insn_buff[1] = n_dspl;
334 
335 	repl_len = 5;
336 
337 done:
338 
339 	DPRINTK("final displ: 0x%08x, JMP 0x%lx",
340 		n_dspl, (unsigned long)orig_insn + n_dspl + repl_len);
341 }
342 
343 /*
344  * optimize_nops_range() - Optimize a sequence of single byte NOPs (0x90)
345  *
346  * @instr: instruction byte stream
347  * @instrlen: length of the above
348  * @off: offset within @instr where the first NOP has been detected
349  *
350  * Return: number of NOPs found (and replaced).
351  */
optimize_nops_range(u8 * instr,u8 instrlen,int off)352 static __always_inline int optimize_nops_range(u8 *instr, u8 instrlen, int off)
353 {
354 	unsigned long flags;
355 	int i = off, nnops;
356 
357 	while (i < instrlen) {
358 		if (instr[i] != 0x90)
359 			break;
360 
361 		i++;
362 	}
363 
364 	nnops = i - off;
365 
366 	if (nnops <= 1)
367 		return nnops;
368 
369 	local_irq_save(flags);
370 	add_nops(instr + off, nnops);
371 	local_irq_restore(flags);
372 
373 	DUMP_BYTES(instr, instrlen, "%px: [%d:%d) optimized NOPs: ", instr, off, i);
374 
375 	return nnops;
376 }
377 
378 /*
379  * "noinline" to cause control flow change and thus invalidate I$ and
380  * cause refetch after modification.
381  */
optimize_nops(u8 * instr,size_t len)382 static void __init_or_module noinline optimize_nops(u8 *instr, size_t len)
383 {
384 	struct insn insn;
385 	int i = 0;
386 
387 	/*
388 	 * Jump over the non-NOP insns and optimize single-byte NOPs into bigger
389 	 * ones.
390 	 */
391 	for (;;) {
392 		if (insn_decode_kernel(&insn, &instr[i]))
393 			return;
394 
395 		/*
396 		 * See if this and any potentially following NOPs can be
397 		 * optimized.
398 		 */
399 		if (insn.length == 1 && insn.opcode.bytes[0] == 0x90)
400 			i += optimize_nops_range(instr, len, i);
401 		else
402 			i += insn.length;
403 
404 		if (i >= len)
405 			return;
406 	}
407 }
408 
409 /*
410  * Replace instructions with better alternatives for this CPU type. This runs
411  * before SMP is initialized to avoid SMP problems with self modifying code.
412  * This implies that asymmetric systems where APs have less capabilities than
413  * the boot processor are not handled. Tough. Make sure you disable such
414  * features by hand.
415  *
416  * Marked "noinline" to cause control flow change and thus insn cache
417  * to refetch changed I$ lines.
418  */
apply_alternatives(struct alt_instr * start,struct alt_instr * end)419 void __init_or_module noinline apply_alternatives(struct alt_instr *start,
420 						  struct alt_instr *end)
421 {
422 	struct alt_instr *a;
423 	u8 *instr, *replacement;
424 	u8 insn_buff[MAX_PATCH_LEN];
425 
426 	DPRINTK("alt table %px, -> %px", start, end);
427 
428 	/*
429 	 * In the case CONFIG_X86_5LEVEL=y, KASAN_SHADOW_START is defined using
430 	 * cpu_feature_enabled(X86_FEATURE_LA57) and is therefore patched here.
431 	 * During the process, KASAN becomes confused seeing partial LA57
432 	 * conversion and triggers a false-positive out-of-bound report.
433 	 *
434 	 * Disable KASAN until the patching is complete.
435 	 */
436 	kasan_disable_current();
437 
438 	/*
439 	 * The scan order should be from start to end. A later scanned
440 	 * alternative code can overwrite previously scanned alternative code.
441 	 * Some kernel functions (e.g. memcpy, memset, etc) use this order to
442 	 * patch code.
443 	 *
444 	 * So be careful if you want to change the scan order to any other
445 	 * order.
446 	 */
447 	for (a = start; a < end; a++) {
448 		int insn_buff_sz = 0;
449 		/* Mask away "NOT" flag bit for feature to test. */
450 		u16 feature = a->cpuid & ~ALTINSTR_FLAG_INV;
451 
452 		instr = (u8 *)&a->instr_offset + a->instr_offset;
453 		replacement = (u8 *)&a->repl_offset + a->repl_offset;
454 		BUG_ON(a->instrlen > sizeof(insn_buff));
455 		BUG_ON(feature >= (NCAPINTS + NBUGINTS) * 32);
456 
457 		/*
458 		 * Patch if either:
459 		 * - feature is present
460 		 * - feature not present but ALTINSTR_FLAG_INV is set to mean,
461 		 *   patch if feature is *NOT* present.
462 		 */
463 		if (!boot_cpu_has(feature) == !(a->cpuid & ALTINSTR_FLAG_INV))
464 			goto next;
465 
466 		DPRINTK("feat: %s%d*32+%d, old: (%pS (%px) len: %d), repl: (%px, len: %d)",
467 			(a->cpuid & ALTINSTR_FLAG_INV) ? "!" : "",
468 			feature >> 5,
469 			feature & 0x1f,
470 			instr, instr, a->instrlen,
471 			replacement, a->replacementlen);
472 
473 		DUMP_BYTES(instr, a->instrlen, "%px: old_insn: ", instr);
474 		DUMP_BYTES(replacement, a->replacementlen, "%px: rpl_insn: ", replacement);
475 
476 		memcpy(insn_buff, replacement, a->replacementlen);
477 		insn_buff_sz = a->replacementlen;
478 
479 		/*
480 		 * 0xe8 is a relative jump; fix the offset.
481 		 *
482 		 * Instruction length is checked before the opcode to avoid
483 		 * accessing uninitialized bytes for zero-length replacements.
484 		 */
485 		if (a->replacementlen == 5 && *insn_buff == 0xe8) {
486 			*(s32 *)(insn_buff + 1) += replacement - instr;
487 			DPRINTK("Fix CALL offset: 0x%x, CALL 0x%lx",
488 				*(s32 *)(insn_buff + 1),
489 				(unsigned long)instr + *(s32 *)(insn_buff + 1) + 5);
490 		}
491 
492 		if (a->replacementlen && is_jmp(replacement[0]))
493 			recompute_jump(a, instr, replacement, insn_buff);
494 
495 		for (; insn_buff_sz < a->instrlen; insn_buff_sz++)
496 			insn_buff[insn_buff_sz] = 0x90;
497 
498 		DUMP_BYTES(insn_buff, insn_buff_sz, "%px: final_insn: ", instr);
499 
500 		text_poke_early(instr, insn_buff, insn_buff_sz);
501 
502 next:
503 		optimize_nops(instr, a->instrlen);
504 	}
505 
506 	kasan_enable_current();
507 }
508 
509 #if defined(CONFIG_RETPOLINE) && defined(CONFIG_STACK_VALIDATION)
510 
511 /*
512  * CALL/JMP *%\reg
513  */
emit_indirect(int op,int reg,u8 * bytes)514 static int emit_indirect(int op, int reg, u8 *bytes)
515 {
516 	int i = 0;
517 	u8 modrm;
518 
519 	switch (op) {
520 	case CALL_INSN_OPCODE:
521 		modrm = 0x10; /* Reg = 2; CALL r/m */
522 		break;
523 
524 	case JMP32_INSN_OPCODE:
525 		modrm = 0x20; /* Reg = 4; JMP r/m */
526 		break;
527 
528 	default:
529 		WARN_ON_ONCE(1);
530 		return -1;
531 	}
532 
533 	if (reg >= 8) {
534 		bytes[i++] = 0x41; /* REX.B prefix */
535 		reg -= 8;
536 	}
537 
538 	modrm |= 0xc0; /* Mod = 3 */
539 	modrm += reg;
540 
541 	bytes[i++] = 0xff; /* opcode */
542 	bytes[i++] = modrm;
543 
544 	return i;
545 }
546 
547 /*
548  * Rewrite the compiler generated retpoline thunk calls.
549  *
550  * For spectre_v2=off (!X86_FEATURE_RETPOLINE), rewrite them into immediate
551  * indirect instructions, avoiding the extra indirection.
552  *
553  * For example, convert:
554  *
555  *   CALL __x86_indirect_thunk_\reg
556  *
557  * into:
558  *
559  *   CALL *%\reg
560  *
561  * It also tries to inline spectre_v2=retpoline,amd when size permits.
562  */
patch_retpoline(void * addr,struct insn * insn,u8 * bytes)563 static int patch_retpoline(void *addr, struct insn *insn, u8 *bytes)
564 {
565 	retpoline_thunk_t *target;
566 	int reg, ret, i = 0;
567 	u8 op, cc;
568 
569 	target = addr + insn->length + insn->immediate.value;
570 	reg = target - __x86_indirect_thunk_array;
571 
572 	if (WARN_ON_ONCE(reg & ~0xf))
573 		return -1;
574 
575 	/* If anyone ever does: CALL/JMP *%rsp, we're in deep trouble. */
576 	BUG_ON(reg == 4);
577 
578 	if (cpu_feature_enabled(X86_FEATURE_RETPOLINE) &&
579 	    !cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE))
580 		return -1;
581 
582 	op = insn->opcode.bytes[0];
583 
584 	/*
585 	 * Convert:
586 	 *
587 	 *   Jcc.d32 __x86_indirect_thunk_\reg
588 	 *
589 	 * into:
590 	 *
591 	 *   Jncc.d8 1f
592 	 *   [ LFENCE ]
593 	 *   JMP *%\reg
594 	 *   [ NOP ]
595 	 * 1:
596 	 */
597 	/* Jcc.d32 second opcode byte is in the range: 0x80-0x8f */
598 	if (op == 0x0f && (insn->opcode.bytes[1] & 0xf0) == 0x80) {
599 		cc = insn->opcode.bytes[1] & 0xf;
600 		cc ^= 1; /* invert condition */
601 
602 		bytes[i++] = 0x70 + cc;        /* Jcc.d8 */
603 		bytes[i++] = insn->length - 2; /* sizeof(Jcc.d8) == 2 */
604 
605 		/* Continue as if: JMP.d32 __x86_indirect_thunk_\reg */
606 		op = JMP32_INSN_OPCODE;
607 	}
608 
609 	/*
610 	 * For RETPOLINE_AMD: prepend the indirect CALL/JMP with an LFENCE.
611 	 */
612 	if (cpu_feature_enabled(X86_FEATURE_RETPOLINE_LFENCE)) {
613 		bytes[i++] = 0x0f;
614 		bytes[i++] = 0xae;
615 		bytes[i++] = 0xe8; /* LFENCE */
616 	}
617 
618 	ret = emit_indirect(op, reg, bytes + i);
619 	if (ret < 0)
620 		return ret;
621 	i += ret;
622 
623 	for (; i < insn->length;)
624 		bytes[i++] = 0x90;
625 
626 	return i;
627 }
628 
629 /*
630  * Generated by 'objtool --retpoline'.
631  */
apply_retpolines(s32 * start,s32 * end)632 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end)
633 {
634 	s32 *s;
635 
636 	for (s = start; s < end; s++) {
637 		void *addr = (void *)s + *s;
638 		struct insn insn;
639 		int len, ret;
640 		u8 bytes[16];
641 		u8 op1, op2;
642 
643 		ret = insn_decode_kernel(&insn, addr);
644 		if (WARN_ON_ONCE(ret < 0))
645 			continue;
646 
647 		op1 = insn.opcode.bytes[0];
648 		op2 = insn.opcode.bytes[1];
649 
650 		switch (op1) {
651 		case CALL_INSN_OPCODE:
652 		case JMP32_INSN_OPCODE:
653 			break;
654 
655 		case 0x0f: /* escape */
656 			if (op2 >= 0x80 && op2 <= 0x8f)
657 				break;
658 			fallthrough;
659 		default:
660 			WARN_ON_ONCE(1);
661 			continue;
662 		}
663 
664 		DPRINTK("retpoline at: %pS (%px) len: %d to: %pS",
665 			addr, addr, insn.length,
666 			addr + insn.length + insn.immediate.value);
667 
668 		len = patch_retpoline(addr, &insn, bytes);
669 		if (len == insn.length) {
670 			optimize_nops(bytes, len);
671 			DUMP_BYTES(((u8*)addr),  len, "%px: orig: ", addr);
672 			DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
673 			text_poke_early(addr, bytes, len);
674 		}
675 	}
676 }
677 
678 #ifdef CONFIG_RETHUNK
679 /*
680  * Rewrite the compiler generated return thunk tail-calls.
681  *
682  * For example, convert:
683  *
684  *   JMP __x86_return_thunk
685  *
686  * into:
687  *
688  *   RET
689  */
patch_return(void * addr,struct insn * insn,u8 * bytes)690 static int patch_return(void *addr, struct insn *insn, u8 *bytes)
691 {
692 	int i = 0;
693 
694 	if (cpu_feature_enabled(X86_FEATURE_RETHUNK))
695 		return -1;
696 
697 	bytes[i++] = RET_INSN_OPCODE;
698 
699 	for (; i < insn->length;)
700 		bytes[i++] = INT3_INSN_OPCODE;
701 
702 	return i;
703 }
704 
apply_returns(s32 * start,s32 * end)705 void __init_or_module noinline apply_returns(s32 *start, s32 *end)
706 {
707 	s32 *s;
708 
709 	for (s = start; s < end; s++) {
710 		void *dest = NULL, *addr = (void *)s + *s;
711 		struct insn insn;
712 		int len, ret;
713 		u8 bytes[16];
714 		u8 op;
715 
716 		ret = insn_decode_kernel(&insn, addr);
717 		if (WARN_ON_ONCE(ret < 0))
718 			continue;
719 
720 		op = insn.opcode.bytes[0];
721 		if (op == JMP32_INSN_OPCODE)
722 			dest = addr + insn.length + insn.immediate.value;
723 
724 		if (__static_call_fixup(addr, op, dest) ||
725 		    WARN_ONCE(dest != &__x86_return_thunk,
726 			      "missing return thunk: %pS-%pS: %*ph",
727 			      addr, dest, 5, addr))
728 			continue;
729 
730 		DPRINTK("return thunk at: %pS (%px) len: %d to: %pS",
731 			addr, addr, insn.length,
732 			addr + insn.length + insn.immediate.value);
733 
734 		len = patch_return(addr, &insn, bytes);
735 		if (len == insn.length) {
736 			DUMP_BYTES(((u8*)addr),  len, "%px: orig: ", addr);
737 			DUMP_BYTES(((u8*)bytes), len, "%px: repl: ", addr);
738 			text_poke_early(addr, bytes, len);
739 		}
740 	}
741 }
742 #else
apply_returns(s32 * start,s32 * end)743 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
744 #endif /* CONFIG_RETHUNK */
745 
746 #else /* !RETPOLINES || !CONFIG_STACK_VALIDATION */
747 
apply_retpolines(s32 * start,s32 * end)748 void __init_or_module noinline apply_retpolines(s32 *start, s32 *end) { }
apply_returns(s32 * start,s32 * end)749 void __init_or_module noinline apply_returns(s32 *start, s32 *end) { }
750 
751 #endif /* CONFIG_RETPOLINE && CONFIG_STACK_VALIDATION */
752 
753 #ifdef CONFIG_SMP
alternatives_smp_lock(const s32 * start,const s32 * end,u8 * text,u8 * text_end)754 static void alternatives_smp_lock(const s32 *start, const s32 *end,
755 				  u8 *text, u8 *text_end)
756 {
757 	const s32 *poff;
758 
759 	for (poff = start; poff < end; poff++) {
760 		u8 *ptr = (u8 *)poff + *poff;
761 
762 		if (!*poff || ptr < text || ptr >= text_end)
763 			continue;
764 		/* turn DS segment override prefix into lock prefix */
765 		if (*ptr == 0x3e)
766 			text_poke(ptr, ((unsigned char []){0xf0}), 1);
767 	}
768 }
769 
alternatives_smp_unlock(const s32 * start,const s32 * end,u8 * text,u8 * text_end)770 static void alternatives_smp_unlock(const s32 *start, const s32 *end,
771 				    u8 *text, u8 *text_end)
772 {
773 	const s32 *poff;
774 
775 	for (poff = start; poff < end; poff++) {
776 		u8 *ptr = (u8 *)poff + *poff;
777 
778 		if (!*poff || ptr < text || ptr >= text_end)
779 			continue;
780 		/* turn lock prefix into DS segment override prefix */
781 		if (*ptr == 0xf0)
782 			text_poke(ptr, ((unsigned char []){0x3E}), 1);
783 	}
784 }
785 
786 struct smp_alt_module {
787 	/* what is this ??? */
788 	struct module	*mod;
789 	char		*name;
790 
791 	/* ptrs to lock prefixes */
792 	const s32	*locks;
793 	const s32	*locks_end;
794 
795 	/* .text segment, needed to avoid patching init code ;) */
796 	u8		*text;
797 	u8		*text_end;
798 
799 	struct list_head next;
800 };
801 static LIST_HEAD(smp_alt_modules);
802 static bool uniproc_patched = false;	/* protected by text_mutex */
803 
alternatives_smp_module_add(struct module * mod,char * name,void * locks,void * locks_end,void * text,void * text_end)804 void __init_or_module alternatives_smp_module_add(struct module *mod,
805 						  char *name,
806 						  void *locks, void *locks_end,
807 						  void *text,  void *text_end)
808 {
809 	struct smp_alt_module *smp;
810 
811 	mutex_lock(&text_mutex);
812 	if (!uniproc_patched)
813 		goto unlock;
814 
815 	if (num_possible_cpus() == 1)
816 		/* Don't bother remembering, we'll never have to undo it. */
817 		goto smp_unlock;
818 
819 	smp = kzalloc(sizeof(*smp), GFP_KERNEL);
820 	if (NULL == smp)
821 		/* we'll run the (safe but slow) SMP code then ... */
822 		goto unlock;
823 
824 	smp->mod	= mod;
825 	smp->name	= name;
826 	smp->locks	= locks;
827 	smp->locks_end	= locks_end;
828 	smp->text	= text;
829 	smp->text_end	= text_end;
830 	DPRINTK("locks %p -> %p, text %p -> %p, name %s\n",
831 		smp->locks, smp->locks_end,
832 		smp->text, smp->text_end, smp->name);
833 
834 	list_add_tail(&smp->next, &smp_alt_modules);
835 smp_unlock:
836 	alternatives_smp_unlock(locks, locks_end, text, text_end);
837 unlock:
838 	mutex_unlock(&text_mutex);
839 }
840 
alternatives_smp_module_del(struct module * mod)841 void __init_or_module alternatives_smp_module_del(struct module *mod)
842 {
843 	struct smp_alt_module *item;
844 
845 	mutex_lock(&text_mutex);
846 	list_for_each_entry(item, &smp_alt_modules, next) {
847 		if (mod != item->mod)
848 			continue;
849 		list_del(&item->next);
850 		kfree(item);
851 		break;
852 	}
853 	mutex_unlock(&text_mutex);
854 }
855 
alternatives_enable_smp(void)856 void alternatives_enable_smp(void)
857 {
858 	struct smp_alt_module *mod;
859 
860 	/* Why bother if there are no other CPUs? */
861 	BUG_ON(num_possible_cpus() == 1);
862 
863 	mutex_lock(&text_mutex);
864 
865 	if (uniproc_patched) {
866 		pr_info("switching to SMP code\n");
867 		BUG_ON(num_online_cpus() != 1);
868 		clear_cpu_cap(&boot_cpu_data, X86_FEATURE_UP);
869 		clear_cpu_cap(&cpu_data(0), X86_FEATURE_UP);
870 		list_for_each_entry(mod, &smp_alt_modules, next)
871 			alternatives_smp_lock(mod->locks, mod->locks_end,
872 					      mod->text, mod->text_end);
873 		uniproc_patched = false;
874 	}
875 	mutex_unlock(&text_mutex);
876 }
877 
878 /*
879  * Return 1 if the address range is reserved for SMP-alternatives.
880  * Must hold text_mutex.
881  */
alternatives_text_reserved(void * start,void * end)882 int alternatives_text_reserved(void *start, void *end)
883 {
884 	struct smp_alt_module *mod;
885 	const s32 *poff;
886 	u8 *text_start = start;
887 	u8 *text_end = end;
888 
889 	lockdep_assert_held(&text_mutex);
890 
891 	list_for_each_entry(mod, &smp_alt_modules, next) {
892 		if (mod->text > text_end || mod->text_end < text_start)
893 			continue;
894 		for (poff = mod->locks; poff < mod->locks_end; poff++) {
895 			const u8 *ptr = (const u8 *)poff + *poff;
896 
897 			if (text_start <= ptr && text_end > ptr)
898 				return 1;
899 		}
900 	}
901 
902 	return 0;
903 }
904 #endif /* CONFIG_SMP */
905 
906 #ifdef CONFIG_PARAVIRT
apply_paravirt(struct paravirt_patch_site * start,struct paravirt_patch_site * end)907 void __init_or_module apply_paravirt(struct paravirt_patch_site *start,
908 				     struct paravirt_patch_site *end)
909 {
910 	struct paravirt_patch_site *p;
911 	char insn_buff[MAX_PATCH_LEN];
912 
913 	for (p = start; p < end; p++) {
914 		unsigned int used;
915 
916 		BUG_ON(p->len > MAX_PATCH_LEN);
917 		/* prep the buffer with the original instructions */
918 		memcpy(insn_buff, p->instr, p->len);
919 		used = pv_ops.init.patch(p->type, insn_buff, (unsigned long)p->instr, p->len);
920 
921 		BUG_ON(used > p->len);
922 
923 		/* Pad the rest with nops */
924 		add_nops(insn_buff + used, p->len - used);
925 		text_poke_early(p->instr, insn_buff, p->len);
926 	}
927 }
928 extern struct paravirt_patch_site __start_parainstructions[],
929 	__stop_parainstructions[];
930 #endif	/* CONFIG_PARAVIRT */
931 
932 /*
933  * Self-test for the INT3 based CALL emulation code.
934  *
935  * This exercises int3_emulate_call() to make sure INT3 pt_regs are set up
936  * properly and that there is a stack gap between the INT3 frame and the
937  * previous context. Without this gap doing a virtual PUSH on the interrupted
938  * stack would corrupt the INT3 IRET frame.
939  *
940  * See entry_{32,64}.S for more details.
941  */
942 
943 /*
944  * We define the int3_magic() function in assembly to control the calling
945  * convention such that we can 'call' it from assembly.
946  */
947 
948 extern void int3_magic(unsigned int *ptr); /* defined in asm */
949 
950 asm (
951 "	.pushsection	.init.text, \"ax\", @progbits\n"
952 "	.type		int3_magic, @function\n"
953 "int3_magic:\n"
954 "	movl	$1, (%" _ASM_ARG1 ")\n"
955 	ASM_RET
956 "	.size		int3_magic, .-int3_magic\n"
957 "	.popsection\n"
958 );
959 
960 extern __initdata unsigned long int3_selftest_ip; /* defined in asm below */
961 
962 static int __init
int3_exception_notify(struct notifier_block * self,unsigned long val,void * data)963 int3_exception_notify(struct notifier_block *self, unsigned long val, void *data)
964 {
965 	struct die_args *args = data;
966 	struct pt_regs *regs = args->regs;
967 
968 	if (!regs || user_mode(regs))
969 		return NOTIFY_DONE;
970 
971 	if (val != DIE_INT3)
972 		return NOTIFY_DONE;
973 
974 	if (regs->ip - INT3_INSN_SIZE != int3_selftest_ip)
975 		return NOTIFY_DONE;
976 
977 	int3_emulate_call(regs, (unsigned long)&int3_magic);
978 	return NOTIFY_STOP;
979 }
980 
int3_selftest(void)981 static void __init int3_selftest(void)
982 {
983 	static __initdata struct notifier_block int3_exception_nb = {
984 		.notifier_call	= int3_exception_notify,
985 		.priority	= INT_MAX-1, /* last */
986 	};
987 	unsigned int val = 0;
988 
989 	BUG_ON(register_die_notifier(&int3_exception_nb));
990 
991 	/*
992 	 * Basically: int3_magic(&val); but really complicated :-)
993 	 *
994 	 * Stick the address of the INT3 instruction into int3_selftest_ip,
995 	 * then trigger the INT3, padded with NOPs to match a CALL instruction
996 	 * length.
997 	 */
998 	asm volatile ("1: int3; nop; nop; nop; nop\n\t"
999 		      ".pushsection .init.data,\"aw\"\n\t"
1000 		      ".align " __ASM_SEL(4, 8) "\n\t"
1001 		      ".type int3_selftest_ip, @object\n\t"
1002 		      ".size int3_selftest_ip, " __ASM_SEL(4, 8) "\n\t"
1003 		      "int3_selftest_ip:\n\t"
1004 		      __ASM_SEL(.long, .quad) " 1b\n\t"
1005 		      ".popsection\n\t"
1006 		      : ASM_CALL_CONSTRAINT
1007 		      : __ASM_SEL_RAW(a, D) (&val)
1008 		      : "memory");
1009 
1010 	BUG_ON(val != 1);
1011 
1012 	unregister_die_notifier(&int3_exception_nb);
1013 }
1014 
alternative_instructions(void)1015 void __init alternative_instructions(void)
1016 {
1017 	int3_selftest();
1018 
1019 	/*
1020 	 * The patching is not fully atomic, so try to avoid local
1021 	 * interruptions that might execute the to be patched code.
1022 	 * Other CPUs are not running.
1023 	 */
1024 	stop_nmi();
1025 
1026 	/*
1027 	 * Don't stop machine check exceptions while patching.
1028 	 * MCEs only happen when something got corrupted and in this
1029 	 * case we must do something about the corruption.
1030 	 * Ignoring it is worse than an unlikely patching race.
1031 	 * Also machine checks tend to be broadcast and if one CPU
1032 	 * goes into machine check the others follow quickly, so we don't
1033 	 * expect a machine check to cause undue problems during to code
1034 	 * patching.
1035 	 */
1036 
1037 	/*
1038 	 * Rewrite the retpolines, must be done before alternatives since
1039 	 * those can rewrite the retpoline thunks.
1040 	 */
1041 	apply_retpolines(__retpoline_sites, __retpoline_sites_end);
1042 	apply_returns(__return_sites, __return_sites_end);
1043 
1044 	apply_alternatives(__alt_instructions, __alt_instructions_end);
1045 
1046 #ifdef CONFIG_SMP
1047 	/* Patch to UP if other cpus not imminent. */
1048 	if (!noreplace_smp && (num_present_cpus() == 1 || setup_max_cpus <= 1)) {
1049 		uniproc_patched = true;
1050 		alternatives_smp_module_add(NULL, "core kernel",
1051 					    __smp_locks, __smp_locks_end,
1052 					    _text, _etext);
1053 	}
1054 
1055 	if (!uniproc_patched || num_possible_cpus() == 1) {
1056 		free_init_pages("SMP alternatives",
1057 				(unsigned long)__smp_locks,
1058 				(unsigned long)__smp_locks_end);
1059 	}
1060 #endif
1061 
1062 	apply_paravirt(__parainstructions, __parainstructions_end);
1063 
1064 	restart_nmi();
1065 	alternatives_patched = 1;
1066 }
1067 
1068 /**
1069  * text_poke_early - Update instructions on a live kernel at boot time
1070  * @addr: address to modify
1071  * @opcode: source of the copy
1072  * @len: length to copy
1073  *
1074  * When you use this code to patch more than one byte of an instruction
1075  * you need to make sure that other CPUs cannot execute this code in parallel.
1076  * Also no thread must be currently preempted in the middle of these
1077  * instructions. And on the local CPU you need to be protected against NMI or
1078  * MCE handlers seeing an inconsistent instruction while you patch.
1079  */
text_poke_early(void * addr,const void * opcode,size_t len)1080 void __init_or_module text_poke_early(void *addr, const void *opcode,
1081 				      size_t len)
1082 {
1083 	unsigned long flags;
1084 
1085 	if (boot_cpu_has(X86_FEATURE_NX) &&
1086 	    is_module_text_address((unsigned long)addr)) {
1087 		/*
1088 		 * Modules text is marked initially as non-executable, so the
1089 		 * code cannot be running and speculative code-fetches are
1090 		 * prevented. Just change the code.
1091 		 */
1092 		memcpy(addr, opcode, len);
1093 	} else {
1094 		local_irq_save(flags);
1095 		memcpy(addr, opcode, len);
1096 		sync_core();
1097 		local_irq_restore(flags);
1098 
1099 		/*
1100 		 * Could also do a CLFLUSH here to speed up CPU recovery; but
1101 		 * that causes hangs on some VIA CPUs.
1102 		 */
1103 	}
1104 }
1105 
1106 typedef struct {
1107 	struct mm_struct *mm;
1108 } temp_mm_state_t;
1109 
1110 /*
1111  * Using a temporary mm allows to set temporary mappings that are not accessible
1112  * by other CPUs. Such mappings are needed to perform sensitive memory writes
1113  * that override the kernel memory protections (e.g., W^X), without exposing the
1114  * temporary page-table mappings that are required for these write operations to
1115  * other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the
1116  * mapping is torn down.
1117  *
1118  * Context: The temporary mm needs to be used exclusively by a single core. To
1119  *          harden security IRQs must be disabled while the temporary mm is
1120  *          loaded, thereby preventing interrupt handler bugs from overriding
1121  *          the kernel memory protection.
1122  */
use_temporary_mm(struct mm_struct * mm)1123 static inline temp_mm_state_t use_temporary_mm(struct mm_struct *mm)
1124 {
1125 	temp_mm_state_t temp_state;
1126 
1127 	lockdep_assert_irqs_disabled();
1128 
1129 	/*
1130 	 * Make sure not to be in TLB lazy mode, as otherwise we'll end up
1131 	 * with a stale address space WITHOUT being in lazy mode after
1132 	 * restoring the previous mm.
1133 	 */
1134 	if (this_cpu_read(cpu_tlbstate.is_lazy))
1135 		leave_mm(smp_processor_id());
1136 
1137 	temp_state.mm = this_cpu_read(cpu_tlbstate.loaded_mm);
1138 	switch_mm_irqs_off(NULL, mm, current);
1139 
1140 	/*
1141 	 * If breakpoints are enabled, disable them while the temporary mm is
1142 	 * used. Userspace might set up watchpoints on addresses that are used
1143 	 * in the temporary mm, which would lead to wrong signals being sent or
1144 	 * crashes.
1145 	 *
1146 	 * Note that breakpoints are not disabled selectively, which also causes
1147 	 * kernel breakpoints (e.g., perf's) to be disabled. This might be
1148 	 * undesirable, but still seems reasonable as the code that runs in the
1149 	 * temporary mm should be short.
1150 	 */
1151 	if (hw_breakpoint_active())
1152 		hw_breakpoint_disable();
1153 
1154 	return temp_state;
1155 }
1156 
unuse_temporary_mm(temp_mm_state_t prev_state)1157 static inline void unuse_temporary_mm(temp_mm_state_t prev_state)
1158 {
1159 	lockdep_assert_irqs_disabled();
1160 	switch_mm_irqs_off(NULL, prev_state.mm, current);
1161 
1162 	/*
1163 	 * Restore the breakpoints if they were disabled before the temporary mm
1164 	 * was loaded.
1165 	 */
1166 	if (hw_breakpoint_active())
1167 		hw_breakpoint_restore();
1168 }
1169 
1170 __ro_after_init struct mm_struct *poking_mm;
1171 __ro_after_init unsigned long poking_addr;
1172 
__text_poke(void * addr,const void * opcode,size_t len)1173 static void *__text_poke(void *addr, const void *opcode, size_t len)
1174 {
1175 	bool cross_page_boundary = offset_in_page(addr) + len > PAGE_SIZE;
1176 	struct page *pages[2] = {NULL};
1177 	temp_mm_state_t prev;
1178 	unsigned long flags;
1179 	pte_t pte, *ptep;
1180 	spinlock_t *ptl;
1181 	pgprot_t pgprot;
1182 
1183 	/*
1184 	 * While boot memory allocator is running we cannot use struct pages as
1185 	 * they are not yet initialized. There is no way to recover.
1186 	 */
1187 	BUG_ON(!after_bootmem);
1188 
1189 	if (!core_kernel_text((unsigned long)addr)) {
1190 		pages[0] = vmalloc_to_page(addr);
1191 		if (cross_page_boundary)
1192 			pages[1] = vmalloc_to_page(addr + PAGE_SIZE);
1193 	} else {
1194 		pages[0] = virt_to_page(addr);
1195 		WARN_ON(!PageReserved(pages[0]));
1196 		if (cross_page_boundary)
1197 			pages[1] = virt_to_page(addr + PAGE_SIZE);
1198 	}
1199 	/*
1200 	 * If something went wrong, crash and burn since recovery paths are not
1201 	 * implemented.
1202 	 */
1203 	BUG_ON(!pages[0] || (cross_page_boundary && !pages[1]));
1204 
1205 	/*
1206 	 * Map the page without the global bit, as TLB flushing is done with
1207 	 * flush_tlb_mm_range(), which is intended for non-global PTEs.
1208 	 */
1209 	pgprot = __pgprot(pgprot_val(PAGE_KERNEL) & ~_PAGE_GLOBAL);
1210 
1211 	/*
1212 	 * The lock is not really needed, but this allows to avoid open-coding.
1213 	 */
1214 	ptep = get_locked_pte(poking_mm, poking_addr, &ptl);
1215 
1216 	/*
1217 	 * This must not fail; preallocated in poking_init().
1218 	 */
1219 	VM_BUG_ON(!ptep);
1220 
1221 	local_irq_save(flags);
1222 
1223 	pte = mk_pte(pages[0], pgprot);
1224 	set_pte_at(poking_mm, poking_addr, ptep, pte);
1225 
1226 	if (cross_page_boundary) {
1227 		pte = mk_pte(pages[1], pgprot);
1228 		set_pte_at(poking_mm, poking_addr + PAGE_SIZE, ptep + 1, pte);
1229 	}
1230 
1231 	/*
1232 	 * Loading the temporary mm behaves as a compiler barrier, which
1233 	 * guarantees that the PTE will be set at the time memcpy() is done.
1234 	 */
1235 	prev = use_temporary_mm(poking_mm);
1236 
1237 	kasan_disable_current();
1238 	memcpy((u8 *)poking_addr + offset_in_page(addr), opcode, len);
1239 	kasan_enable_current();
1240 
1241 	/*
1242 	 * Ensure that the PTE is only cleared after the instructions of memcpy
1243 	 * were issued by using a compiler barrier.
1244 	 */
1245 	barrier();
1246 
1247 	pte_clear(poking_mm, poking_addr, ptep);
1248 	if (cross_page_boundary)
1249 		pte_clear(poking_mm, poking_addr + PAGE_SIZE, ptep + 1);
1250 
1251 	/*
1252 	 * Loading the previous page-table hierarchy requires a serializing
1253 	 * instruction that already allows the core to see the updated version.
1254 	 * Xen-PV is assumed to serialize execution in a similar manner.
1255 	 */
1256 	unuse_temporary_mm(prev);
1257 
1258 	/*
1259 	 * Flushing the TLB might involve IPIs, which would require enabled
1260 	 * IRQs, but not if the mm is not used, as it is in this point.
1261 	 */
1262 	flush_tlb_mm_range(poking_mm, poking_addr, poking_addr +
1263 			   (cross_page_boundary ? 2 : 1) * PAGE_SIZE,
1264 			   PAGE_SHIFT, false);
1265 
1266 	/*
1267 	 * If the text does not match what we just wrote then something is
1268 	 * fundamentally screwy; there's nothing we can really do about that.
1269 	 */
1270 	BUG_ON(memcmp(addr, opcode, len));
1271 
1272 	local_irq_restore(flags);
1273 	pte_unmap_unlock(ptep, ptl);
1274 	return addr;
1275 }
1276 
1277 /**
1278  * text_poke - Update instructions on a live kernel
1279  * @addr: address to modify
1280  * @opcode: source of the copy
1281  * @len: length to copy
1282  *
1283  * Only atomic text poke/set should be allowed when not doing early patching.
1284  * It means the size must be writable atomically and the address must be aligned
1285  * in a way that permits an atomic write. It also makes sure we fit on a single
1286  * page.
1287  *
1288  * Note that the caller must ensure that if the modified code is part of a
1289  * module, the module would not be removed during poking. This can be achieved
1290  * by registering a module notifier, and ordering module removal and patching
1291  * trough a mutex.
1292  */
text_poke(void * addr,const void * opcode,size_t len)1293 void *text_poke(void *addr, const void *opcode, size_t len)
1294 {
1295 	lockdep_assert_held(&text_mutex);
1296 
1297 	return __text_poke(addr, opcode, len);
1298 }
1299 
1300 /**
1301  * text_poke_kgdb - Update instructions on a live kernel by kgdb
1302  * @addr: address to modify
1303  * @opcode: source of the copy
1304  * @len: length to copy
1305  *
1306  * Only atomic text poke/set should be allowed when not doing early patching.
1307  * It means the size must be writable atomically and the address must be aligned
1308  * in a way that permits an atomic write. It also makes sure we fit on a single
1309  * page.
1310  *
1311  * Context: should only be used by kgdb, which ensures no other core is running,
1312  *	    despite the fact it does not hold the text_mutex.
1313  */
text_poke_kgdb(void * addr,const void * opcode,size_t len)1314 void *text_poke_kgdb(void *addr, const void *opcode, size_t len)
1315 {
1316 	return __text_poke(addr, opcode, len);
1317 }
1318 
do_sync_core(void * info)1319 static void do_sync_core(void *info)
1320 {
1321 	sync_core();
1322 }
1323 
text_poke_sync(void)1324 void text_poke_sync(void)
1325 {
1326 	on_each_cpu(do_sync_core, NULL, 1);
1327 }
1328 
1329 struct text_poke_loc {
1330 	/* addr := _stext + rel_addr */
1331 	s32 rel_addr;
1332 	s32 disp;
1333 	u8 len;
1334 	u8 opcode;
1335 	const u8 text[POKE_MAX_OPCODE_SIZE];
1336 	/* see text_poke_bp_batch() */
1337 	u8 old;
1338 };
1339 
1340 struct bp_patching_desc {
1341 	struct text_poke_loc *vec;
1342 	int nr_entries;
1343 	atomic_t refs;
1344 };
1345 
1346 static struct bp_patching_desc bp_desc;
1347 
1348 static __always_inline
try_get_desc(void)1349 struct bp_patching_desc *try_get_desc(void)
1350 {
1351 	struct bp_patching_desc *desc = &bp_desc;
1352 
1353 	if (!arch_atomic_inc_not_zero(&desc->refs))
1354 		return NULL;
1355 
1356 	return desc;
1357 }
1358 
put_desc(void)1359 static __always_inline void put_desc(void)
1360 {
1361 	struct bp_patching_desc *desc = &bp_desc;
1362 
1363 	smp_mb__before_atomic();
1364 	arch_atomic_dec(&desc->refs);
1365 }
1366 
text_poke_addr(struct text_poke_loc * tp)1367 static __always_inline void *text_poke_addr(struct text_poke_loc *tp)
1368 {
1369 	return _stext + tp->rel_addr;
1370 }
1371 
patch_cmp(const void * key,const void * elt)1372 static __always_inline int patch_cmp(const void *key, const void *elt)
1373 {
1374 	struct text_poke_loc *tp = (struct text_poke_loc *) elt;
1375 
1376 	if (key < text_poke_addr(tp))
1377 		return -1;
1378 	if (key > text_poke_addr(tp))
1379 		return 1;
1380 	return 0;
1381 }
1382 
poke_int3_handler(struct pt_regs * regs)1383 noinstr int poke_int3_handler(struct pt_regs *regs)
1384 {
1385 	struct bp_patching_desc *desc;
1386 	struct text_poke_loc *tp;
1387 	int ret = 0;
1388 	void *ip;
1389 
1390 	if (user_mode(regs))
1391 		return 0;
1392 
1393 	/*
1394 	 * Having observed our INT3 instruction, we now must observe
1395 	 * bp_desc with non-zero refcount:
1396 	 *
1397 	 *	bp_desc.refs = 1		INT3
1398 	 *	WMB				RMB
1399 	 *	write INT3			if (bp_desc.refs != 0)
1400 	 */
1401 	smp_rmb();
1402 
1403 	desc = try_get_desc();
1404 	if (!desc)
1405 		return 0;
1406 
1407 	/*
1408 	 * Discount the INT3. See text_poke_bp_batch().
1409 	 */
1410 	ip = (void *) regs->ip - INT3_INSN_SIZE;
1411 
1412 	/*
1413 	 * Skip the binary search if there is a single member in the vector.
1414 	 */
1415 	if (unlikely(desc->nr_entries > 1)) {
1416 		tp = __inline_bsearch(ip, desc->vec, desc->nr_entries,
1417 				      sizeof(struct text_poke_loc),
1418 				      patch_cmp);
1419 		if (!tp)
1420 			goto out_put;
1421 	} else {
1422 		tp = desc->vec;
1423 		if (text_poke_addr(tp) != ip)
1424 			goto out_put;
1425 	}
1426 
1427 	ip += tp->len;
1428 
1429 	switch (tp->opcode) {
1430 	case INT3_INSN_OPCODE:
1431 		/*
1432 		 * Someone poked an explicit INT3, they'll want to handle it,
1433 		 * do not consume.
1434 		 */
1435 		goto out_put;
1436 
1437 	case RET_INSN_OPCODE:
1438 		int3_emulate_ret(regs);
1439 		break;
1440 
1441 	case CALL_INSN_OPCODE:
1442 		int3_emulate_call(regs, (long)ip + tp->disp);
1443 		break;
1444 
1445 	case JMP32_INSN_OPCODE:
1446 	case JMP8_INSN_OPCODE:
1447 		int3_emulate_jmp(regs, (long)ip + tp->disp);
1448 		break;
1449 
1450 	default:
1451 		BUG();
1452 	}
1453 
1454 	ret = 1;
1455 
1456 out_put:
1457 	put_desc();
1458 	return ret;
1459 }
1460 
1461 #define TP_VEC_MAX (PAGE_SIZE / sizeof(struct text_poke_loc))
1462 static struct text_poke_loc tp_vec[TP_VEC_MAX];
1463 static int tp_vec_nr;
1464 
1465 /**
1466  * text_poke_bp_batch() -- update instructions on live kernel on SMP
1467  * @tp:			vector of instructions to patch
1468  * @nr_entries:		number of entries in the vector
1469  *
1470  * Modify multi-byte instruction by using int3 breakpoint on SMP.
1471  * We completely avoid stop_machine() here, and achieve the
1472  * synchronization using int3 breakpoint.
1473  *
1474  * The way it is done:
1475  *	- For each entry in the vector:
1476  *		- add a int3 trap to the address that will be patched
1477  *	- sync cores
1478  *	- For each entry in the vector:
1479  *		- update all but the first byte of the patched range
1480  *	- sync cores
1481  *	- For each entry in the vector:
1482  *		- replace the first byte (int3) by the first byte of
1483  *		  replacing opcode
1484  *	- sync cores
1485  */
text_poke_bp_batch(struct text_poke_loc * tp,unsigned int nr_entries)1486 static void text_poke_bp_batch(struct text_poke_loc *tp, unsigned int nr_entries)
1487 {
1488 	unsigned char int3 = INT3_INSN_OPCODE;
1489 	unsigned int i;
1490 	int do_sync;
1491 
1492 	lockdep_assert_held(&text_mutex);
1493 
1494 	bp_desc.vec = tp;
1495 	bp_desc.nr_entries = nr_entries;
1496 
1497 	/*
1498 	 * Corresponds to the implicit memory barrier in try_get_desc() to
1499 	 * ensure reading a non-zero refcount provides up to date bp_desc data.
1500 	 */
1501 	atomic_set_release(&bp_desc.refs, 1);
1502 
1503 	/*
1504 	 * Corresponding read barrier in int3 notifier for making sure the
1505 	 * nr_entries and handler are correctly ordered wrt. patching.
1506 	 */
1507 	smp_wmb();
1508 
1509 	/*
1510 	 * First step: add a int3 trap to the address that will be patched.
1511 	 */
1512 	for (i = 0; i < nr_entries; i++) {
1513 		tp[i].old = *(u8 *)text_poke_addr(&tp[i]);
1514 		text_poke(text_poke_addr(&tp[i]), &int3, INT3_INSN_SIZE);
1515 	}
1516 
1517 	text_poke_sync();
1518 
1519 	/*
1520 	 * Second step: update all but the first byte of the patched range.
1521 	 */
1522 	for (do_sync = 0, i = 0; i < nr_entries; i++) {
1523 		u8 old[POKE_MAX_OPCODE_SIZE] = { tp[i].old, };
1524 		int len = tp[i].len;
1525 
1526 		if (len - INT3_INSN_SIZE > 0) {
1527 			memcpy(old + INT3_INSN_SIZE,
1528 			       text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1529 			       len - INT3_INSN_SIZE);
1530 			text_poke(text_poke_addr(&tp[i]) + INT3_INSN_SIZE,
1531 				  (const char *)tp[i].text + INT3_INSN_SIZE,
1532 				  len - INT3_INSN_SIZE);
1533 			do_sync++;
1534 		}
1535 
1536 		/*
1537 		 * Emit a perf event to record the text poke, primarily to
1538 		 * support Intel PT decoding which must walk the executable code
1539 		 * to reconstruct the trace. The flow up to here is:
1540 		 *   - write INT3 byte
1541 		 *   - IPI-SYNC
1542 		 *   - write instruction tail
1543 		 * At this point the actual control flow will be through the
1544 		 * INT3 and handler and not hit the old or new instruction.
1545 		 * Intel PT outputs FUP/TIP packets for the INT3, so the flow
1546 		 * can still be decoded. Subsequently:
1547 		 *   - emit RECORD_TEXT_POKE with the new instruction
1548 		 *   - IPI-SYNC
1549 		 *   - write first byte
1550 		 *   - IPI-SYNC
1551 		 * So before the text poke event timestamp, the decoder will see
1552 		 * either the old instruction flow or FUP/TIP of INT3. After the
1553 		 * text poke event timestamp, the decoder will see either the
1554 		 * new instruction flow or FUP/TIP of INT3. Thus decoders can
1555 		 * use the timestamp as the point at which to modify the
1556 		 * executable code.
1557 		 * The old instruction is recorded so that the event can be
1558 		 * processed forwards or backwards.
1559 		 */
1560 		perf_event_text_poke(text_poke_addr(&tp[i]), old, len,
1561 				     tp[i].text, len);
1562 	}
1563 
1564 	if (do_sync) {
1565 		/*
1566 		 * According to Intel, this core syncing is very likely
1567 		 * not necessary and we'd be safe even without it. But
1568 		 * better safe than sorry (plus there's not only Intel).
1569 		 */
1570 		text_poke_sync();
1571 	}
1572 
1573 	/*
1574 	 * Third step: replace the first byte (int3) by the first byte of
1575 	 * replacing opcode.
1576 	 */
1577 	for (do_sync = 0, i = 0; i < nr_entries; i++) {
1578 		if (tp[i].text[0] == INT3_INSN_OPCODE)
1579 			continue;
1580 
1581 		text_poke(text_poke_addr(&tp[i]), tp[i].text, INT3_INSN_SIZE);
1582 		do_sync++;
1583 	}
1584 
1585 	if (do_sync)
1586 		text_poke_sync();
1587 
1588 	/*
1589 	 * Remove and wait for refs to be zero.
1590 	 */
1591 	if (!atomic_dec_and_test(&bp_desc.refs))
1592 		atomic_cond_read_acquire(&bp_desc.refs, !VAL);
1593 }
1594 
text_poke_loc_init(struct text_poke_loc * tp,void * addr,const void * opcode,size_t len,const void * emulate)1595 static void text_poke_loc_init(struct text_poke_loc *tp, void *addr,
1596 			       const void *opcode, size_t len, const void *emulate)
1597 {
1598 	struct insn insn;
1599 	int ret, i;
1600 
1601 	memcpy((void *)tp->text, opcode, len);
1602 	if (!emulate)
1603 		emulate = opcode;
1604 
1605 	ret = insn_decode_kernel(&insn, emulate);
1606 	BUG_ON(ret < 0);
1607 
1608 	tp->rel_addr = addr - (void *)_stext;
1609 	tp->len = len;
1610 	tp->opcode = insn.opcode.bytes[0];
1611 
1612 	switch (tp->opcode) {
1613 	case RET_INSN_OPCODE:
1614 	case JMP32_INSN_OPCODE:
1615 	case JMP8_INSN_OPCODE:
1616 		/*
1617 		 * Control flow instructions without implied execution of the
1618 		 * next instruction can be padded with INT3.
1619 		 */
1620 		for (i = insn.length; i < len; i++)
1621 			BUG_ON(tp->text[i] != INT3_INSN_OPCODE);
1622 		break;
1623 
1624 	default:
1625 		BUG_ON(len != insn.length);
1626 	};
1627 
1628 
1629 	switch (tp->opcode) {
1630 	case INT3_INSN_OPCODE:
1631 	case RET_INSN_OPCODE:
1632 		break;
1633 
1634 	case CALL_INSN_OPCODE:
1635 	case JMP32_INSN_OPCODE:
1636 	case JMP8_INSN_OPCODE:
1637 		tp->disp = insn.immediate.value;
1638 		break;
1639 
1640 	default: /* assume NOP */
1641 		switch (len) {
1642 		case 2: /* NOP2 -- emulate as JMP8+0 */
1643 			BUG_ON(memcmp(emulate, ideal_nops[len], len));
1644 			tp->opcode = JMP8_INSN_OPCODE;
1645 			tp->disp = 0;
1646 			break;
1647 
1648 		case 5: /* NOP5 -- emulate as JMP32+0 */
1649 			BUG_ON(memcmp(emulate, ideal_nops[NOP_ATOMIC5], len));
1650 			tp->opcode = JMP32_INSN_OPCODE;
1651 			tp->disp = 0;
1652 			break;
1653 
1654 		default: /* unknown instruction */
1655 			BUG();
1656 		}
1657 		break;
1658 	}
1659 }
1660 
1661 /*
1662  * We hard rely on the tp_vec being ordered; ensure this is so by flushing
1663  * early if needed.
1664  */
tp_order_fail(void * addr)1665 static bool tp_order_fail(void *addr)
1666 {
1667 	struct text_poke_loc *tp;
1668 
1669 	if (!tp_vec_nr)
1670 		return false;
1671 
1672 	if (!addr) /* force */
1673 		return true;
1674 
1675 	tp = &tp_vec[tp_vec_nr - 1];
1676 	if ((unsigned long)text_poke_addr(tp) > (unsigned long)addr)
1677 		return true;
1678 
1679 	return false;
1680 }
1681 
text_poke_flush(void * addr)1682 static void text_poke_flush(void *addr)
1683 {
1684 	if (tp_vec_nr == TP_VEC_MAX || tp_order_fail(addr)) {
1685 		text_poke_bp_batch(tp_vec, tp_vec_nr);
1686 		tp_vec_nr = 0;
1687 	}
1688 }
1689 
text_poke_finish(void)1690 void text_poke_finish(void)
1691 {
1692 	text_poke_flush(NULL);
1693 }
1694 
text_poke_queue(void * addr,const void * opcode,size_t len,const void * emulate)1695 void __ref text_poke_queue(void *addr, const void *opcode, size_t len, const void *emulate)
1696 {
1697 	struct text_poke_loc *tp;
1698 
1699 	if (unlikely(system_state == SYSTEM_BOOTING)) {
1700 		text_poke_early(addr, opcode, len);
1701 		return;
1702 	}
1703 
1704 	text_poke_flush(addr);
1705 
1706 	tp = &tp_vec[tp_vec_nr++];
1707 	text_poke_loc_init(tp, addr, opcode, len, emulate);
1708 }
1709 
1710 /**
1711  * text_poke_bp() -- update instructions on live kernel on SMP
1712  * @addr:	address to patch
1713  * @opcode:	opcode of new instruction
1714  * @len:	length to copy
1715  * @handler:	address to jump to when the temporary breakpoint is hit
1716  *
1717  * Update a single instruction with the vector in the stack, avoiding
1718  * dynamically allocated memory. This function should be used when it is
1719  * not possible to allocate memory.
1720  */
text_poke_bp(void * addr,const void * opcode,size_t len,const void * emulate)1721 void __ref text_poke_bp(void *addr, const void *opcode, size_t len, const void *emulate)
1722 {
1723 	struct text_poke_loc tp;
1724 
1725 	if (unlikely(system_state == SYSTEM_BOOTING)) {
1726 		text_poke_early(addr, opcode, len);
1727 		return;
1728 	}
1729 
1730 	text_poke_loc_init(&tp, addr, opcode, len, emulate);
1731 	text_poke_bp_batch(&tp, 1);
1732 }
1733