xref: /linux/arch/x86/kernel/process.c (revision dd093fb0)
1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3 
4 #include <linux/errno.h>
5 #include <linux/kernel.h>
6 #include <linux/mm.h>
7 #include <linux/smp.h>
8 #include <linux/prctl.h>
9 #include <linux/slab.h>
10 #include <linux/sched.h>
11 #include <linux/sched/idle.h>
12 #include <linux/sched/debug.h>
13 #include <linux/sched/task.h>
14 #include <linux/sched/task_stack.h>
15 #include <linux/init.h>
16 #include <linux/export.h>
17 #include <linux/pm.h>
18 #include <linux/tick.h>
19 #include <linux/random.h>
20 #include <linux/user-return-notifier.h>
21 #include <linux/dmi.h>
22 #include <linux/utsname.h>
23 #include <linux/stackprotector.h>
24 #include <linux/cpuidle.h>
25 #include <linux/acpi.h>
26 #include <linux/elf-randomize.h>
27 #include <linux/static_call.h>
28 #include <trace/events/power.h>
29 #include <linux/hw_breakpoint.h>
30 #include <asm/cpu.h>
31 #include <asm/apic.h>
32 #include <linux/uaccess.h>
33 #include <asm/mwait.h>
34 #include <asm/fpu/api.h>
35 #include <asm/fpu/sched.h>
36 #include <asm/fpu/xstate.h>
37 #include <asm/debugreg.h>
38 #include <asm/nmi.h>
39 #include <asm/tlbflush.h>
40 #include <asm/mce.h>
41 #include <asm/vm86.h>
42 #include <asm/switch_to.h>
43 #include <asm/desc.h>
44 #include <asm/prctl.h>
45 #include <asm/spec-ctrl.h>
46 #include <asm/io_bitmap.h>
47 #include <asm/proto.h>
48 #include <asm/frame.h>
49 #include <asm/unwind.h>
50 #include <asm/tdx.h>
51 
52 #include "process.h"
53 
54 /*
55  * per-CPU TSS segments. Threads are completely 'soft' on Linux,
56  * no more per-task TSS's. The TSS size is kept cacheline-aligned
57  * so they are allowed to end up in the .data..cacheline_aligned
58  * section. Since TSS's are completely CPU-local, we want them
59  * on exact cacheline boundaries, to eliminate cacheline ping-pong.
60  */
61 __visible DEFINE_PER_CPU_PAGE_ALIGNED(struct tss_struct, cpu_tss_rw) = {
62 	.x86_tss = {
63 		/*
64 		 * .sp0 is only used when entering ring 0 from a lower
65 		 * privilege level.  Since the init task never runs anything
66 		 * but ring 0 code, there is no need for a valid value here.
67 		 * Poison it.
68 		 */
69 		.sp0 = (1UL << (BITS_PER_LONG-1)) + 1,
70 
71 #ifdef CONFIG_X86_32
72 		.sp1 = TOP_OF_INIT_STACK,
73 
74 		.ss0 = __KERNEL_DS,
75 		.ss1 = __KERNEL_CS,
76 #endif
77 		.io_bitmap_base	= IO_BITMAP_OFFSET_INVALID,
78 	 },
79 };
80 EXPORT_PER_CPU_SYMBOL(cpu_tss_rw);
81 
82 DEFINE_PER_CPU(bool, __tss_limit_invalid);
83 EXPORT_PER_CPU_SYMBOL_GPL(__tss_limit_invalid);
84 
85 /*
86  * this gets called so that we can store lazy state into memory and copy the
87  * current task into the new thread.
88  */
89 int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src)
90 {
91 	memcpy(dst, src, arch_task_struct_size);
92 #ifdef CONFIG_VM86
93 	dst->thread.vm86 = NULL;
94 #endif
95 	/* Drop the copied pointer to current's fpstate */
96 	dst->thread.fpu.fpstate = NULL;
97 
98 	return 0;
99 }
100 
101 #ifdef CONFIG_X86_64
102 void arch_release_task_struct(struct task_struct *tsk)
103 {
104 	if (fpu_state_size_dynamic())
105 		fpstate_free(&tsk->thread.fpu);
106 }
107 #endif
108 
109 /*
110  * Free thread data structures etc..
111  */
112 void exit_thread(struct task_struct *tsk)
113 {
114 	struct thread_struct *t = &tsk->thread;
115 	struct fpu *fpu = &t->fpu;
116 
117 	if (test_thread_flag(TIF_IO_BITMAP))
118 		io_bitmap_exit(tsk);
119 
120 	free_vm86(t);
121 
122 	fpu__drop(fpu);
123 }
124 
125 static int set_new_tls(struct task_struct *p, unsigned long tls)
126 {
127 	struct user_desc __user *utls = (struct user_desc __user *)tls;
128 
129 	if (in_ia32_syscall())
130 		return do_set_thread_area(p, -1, utls, 0);
131 	else
132 		return do_set_thread_area_64(p, ARCH_SET_FS, tls);
133 }
134 
135 int copy_thread(struct task_struct *p, const struct kernel_clone_args *args)
136 {
137 	unsigned long clone_flags = args->flags;
138 	unsigned long sp = args->stack;
139 	unsigned long tls = args->tls;
140 	struct inactive_task_frame *frame;
141 	struct fork_frame *fork_frame;
142 	struct pt_regs *childregs;
143 	int ret = 0;
144 
145 	childregs = task_pt_regs(p);
146 	fork_frame = container_of(childregs, struct fork_frame, regs);
147 	frame = &fork_frame->frame;
148 
149 	frame->bp = encode_frame_pointer(childregs);
150 	frame->ret_addr = (unsigned long) ret_from_fork;
151 	p->thread.sp = (unsigned long) fork_frame;
152 	p->thread.io_bitmap = NULL;
153 	p->thread.iopl_warn = 0;
154 	memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
155 
156 #ifdef CONFIG_X86_64
157 	current_save_fsgs();
158 	p->thread.fsindex = current->thread.fsindex;
159 	p->thread.fsbase = current->thread.fsbase;
160 	p->thread.gsindex = current->thread.gsindex;
161 	p->thread.gsbase = current->thread.gsbase;
162 
163 	savesegment(es, p->thread.es);
164 	savesegment(ds, p->thread.ds);
165 #else
166 	p->thread.sp0 = (unsigned long) (childregs + 1);
167 	savesegment(gs, p->thread.gs);
168 	/*
169 	 * Clear all status flags including IF and set fixed bit. 64bit
170 	 * does not have this initialization as the frame does not contain
171 	 * flags. The flags consistency (especially vs. AC) is there
172 	 * ensured via objtool, which lacks 32bit support.
173 	 */
174 	frame->flags = X86_EFLAGS_FIXED;
175 #endif
176 
177 	fpu_clone(p, clone_flags, args->fn);
178 
179 	/* Kernel thread ? */
180 	if (unlikely(p->flags & PF_KTHREAD)) {
181 		p->thread.pkru = pkru_get_init_value();
182 		memset(childregs, 0, sizeof(struct pt_regs));
183 		kthread_frame_init(frame, args->fn, args->fn_arg);
184 		return 0;
185 	}
186 
187 	/*
188 	 * Clone current's PKRU value from hardware. tsk->thread.pkru
189 	 * is only valid when scheduled out.
190 	 */
191 	p->thread.pkru = read_pkru();
192 
193 	frame->bx = 0;
194 	*childregs = *current_pt_regs();
195 	childregs->ax = 0;
196 	if (sp)
197 		childregs->sp = sp;
198 
199 	if (unlikely(args->fn)) {
200 		/*
201 		 * A user space thread, but it doesn't return to
202 		 * ret_after_fork().
203 		 *
204 		 * In order to indicate that to tools like gdb,
205 		 * we reset the stack and instruction pointers.
206 		 *
207 		 * It does the same kernel frame setup to return to a kernel
208 		 * function that a kernel thread does.
209 		 */
210 		childregs->sp = 0;
211 		childregs->ip = 0;
212 		kthread_frame_init(frame, args->fn, args->fn_arg);
213 		return 0;
214 	}
215 
216 	/* Set a new TLS for the child thread? */
217 	if (clone_flags & CLONE_SETTLS)
218 		ret = set_new_tls(p, tls);
219 
220 	if (!ret && unlikely(test_tsk_thread_flag(current, TIF_IO_BITMAP)))
221 		io_bitmap_share(p);
222 
223 	return ret;
224 }
225 
226 static void pkru_flush_thread(void)
227 {
228 	/*
229 	 * If PKRU is enabled the default PKRU value has to be loaded into
230 	 * the hardware right here (similar to context switch).
231 	 */
232 	pkru_write_default();
233 }
234 
235 void flush_thread(void)
236 {
237 	struct task_struct *tsk = current;
238 
239 	flush_ptrace_hw_breakpoint(tsk);
240 	memset(tsk->thread.tls_array, 0, sizeof(tsk->thread.tls_array));
241 
242 	fpu_flush_thread();
243 	pkru_flush_thread();
244 }
245 
246 void disable_TSC(void)
247 {
248 	preempt_disable();
249 	if (!test_and_set_thread_flag(TIF_NOTSC))
250 		/*
251 		 * Must flip the CPU state synchronously with
252 		 * TIF_NOTSC in the current running context.
253 		 */
254 		cr4_set_bits(X86_CR4_TSD);
255 	preempt_enable();
256 }
257 
258 static void enable_TSC(void)
259 {
260 	preempt_disable();
261 	if (test_and_clear_thread_flag(TIF_NOTSC))
262 		/*
263 		 * Must flip the CPU state synchronously with
264 		 * TIF_NOTSC in the current running context.
265 		 */
266 		cr4_clear_bits(X86_CR4_TSD);
267 	preempt_enable();
268 }
269 
270 int get_tsc_mode(unsigned long adr)
271 {
272 	unsigned int val;
273 
274 	if (test_thread_flag(TIF_NOTSC))
275 		val = PR_TSC_SIGSEGV;
276 	else
277 		val = PR_TSC_ENABLE;
278 
279 	return put_user(val, (unsigned int __user *)adr);
280 }
281 
282 int set_tsc_mode(unsigned int val)
283 {
284 	if (val == PR_TSC_SIGSEGV)
285 		disable_TSC();
286 	else if (val == PR_TSC_ENABLE)
287 		enable_TSC();
288 	else
289 		return -EINVAL;
290 
291 	return 0;
292 }
293 
294 DEFINE_PER_CPU(u64, msr_misc_features_shadow);
295 
296 static void set_cpuid_faulting(bool on)
297 {
298 	u64 msrval;
299 
300 	msrval = this_cpu_read(msr_misc_features_shadow);
301 	msrval &= ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT;
302 	msrval |= (on << MSR_MISC_FEATURES_ENABLES_CPUID_FAULT_BIT);
303 	this_cpu_write(msr_misc_features_shadow, msrval);
304 	wrmsrl(MSR_MISC_FEATURES_ENABLES, msrval);
305 }
306 
307 static void disable_cpuid(void)
308 {
309 	preempt_disable();
310 	if (!test_and_set_thread_flag(TIF_NOCPUID)) {
311 		/*
312 		 * Must flip the CPU state synchronously with
313 		 * TIF_NOCPUID in the current running context.
314 		 */
315 		set_cpuid_faulting(true);
316 	}
317 	preempt_enable();
318 }
319 
320 static void enable_cpuid(void)
321 {
322 	preempt_disable();
323 	if (test_and_clear_thread_flag(TIF_NOCPUID)) {
324 		/*
325 		 * Must flip the CPU state synchronously with
326 		 * TIF_NOCPUID in the current running context.
327 		 */
328 		set_cpuid_faulting(false);
329 	}
330 	preempt_enable();
331 }
332 
333 static int get_cpuid_mode(void)
334 {
335 	return !test_thread_flag(TIF_NOCPUID);
336 }
337 
338 static int set_cpuid_mode(unsigned long cpuid_enabled)
339 {
340 	if (!boot_cpu_has(X86_FEATURE_CPUID_FAULT))
341 		return -ENODEV;
342 
343 	if (cpuid_enabled)
344 		enable_cpuid();
345 	else
346 		disable_cpuid();
347 
348 	return 0;
349 }
350 
351 /*
352  * Called immediately after a successful exec.
353  */
354 void arch_setup_new_exec(void)
355 {
356 	/* If cpuid was previously disabled for this task, re-enable it. */
357 	if (test_thread_flag(TIF_NOCPUID))
358 		enable_cpuid();
359 
360 	/*
361 	 * Don't inherit TIF_SSBD across exec boundary when
362 	 * PR_SPEC_DISABLE_NOEXEC is used.
363 	 */
364 	if (test_thread_flag(TIF_SSBD) &&
365 	    task_spec_ssb_noexec(current)) {
366 		clear_thread_flag(TIF_SSBD);
367 		task_clear_spec_ssb_disable(current);
368 		task_clear_spec_ssb_noexec(current);
369 		speculation_ctrl_update(read_thread_flags());
370 	}
371 }
372 
373 #ifdef CONFIG_X86_IOPL_IOPERM
374 static inline void switch_to_bitmap(unsigned long tifp)
375 {
376 	/*
377 	 * Invalidate I/O bitmap if the previous task used it. This prevents
378 	 * any possible leakage of an active I/O bitmap.
379 	 *
380 	 * If the next task has an I/O bitmap it will handle it on exit to
381 	 * user mode.
382 	 */
383 	if (tifp & _TIF_IO_BITMAP)
384 		tss_invalidate_io_bitmap();
385 }
386 
387 static void tss_copy_io_bitmap(struct tss_struct *tss, struct io_bitmap *iobm)
388 {
389 	/*
390 	 * Copy at least the byte range of the incoming tasks bitmap which
391 	 * covers the permitted I/O ports.
392 	 *
393 	 * If the previous task which used an I/O bitmap had more bits
394 	 * permitted, then the copy needs to cover those as well so they
395 	 * get turned off.
396 	 */
397 	memcpy(tss->io_bitmap.bitmap, iobm->bitmap,
398 	       max(tss->io_bitmap.prev_max, iobm->max));
399 
400 	/*
401 	 * Store the new max and the sequence number of this bitmap
402 	 * and a pointer to the bitmap itself.
403 	 */
404 	tss->io_bitmap.prev_max = iobm->max;
405 	tss->io_bitmap.prev_sequence = iobm->sequence;
406 }
407 
408 /**
409  * native_tss_update_io_bitmap - Update I/O bitmap before exiting to user mode
410  */
411 void native_tss_update_io_bitmap(void)
412 {
413 	struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw);
414 	struct thread_struct *t = &current->thread;
415 	u16 *base = &tss->x86_tss.io_bitmap_base;
416 
417 	if (!test_thread_flag(TIF_IO_BITMAP)) {
418 		native_tss_invalidate_io_bitmap();
419 		return;
420 	}
421 
422 	if (IS_ENABLED(CONFIG_X86_IOPL_IOPERM) && t->iopl_emul == 3) {
423 		*base = IO_BITMAP_OFFSET_VALID_ALL;
424 	} else {
425 		struct io_bitmap *iobm = t->io_bitmap;
426 
427 		/*
428 		 * Only copy bitmap data when the sequence number differs. The
429 		 * update time is accounted to the incoming task.
430 		 */
431 		if (tss->io_bitmap.prev_sequence != iobm->sequence)
432 			tss_copy_io_bitmap(tss, iobm);
433 
434 		/* Enable the bitmap */
435 		*base = IO_BITMAP_OFFSET_VALID_MAP;
436 	}
437 
438 	/*
439 	 * Make sure that the TSS limit is covering the IO bitmap. It might have
440 	 * been cut down by a VMEXIT to 0x67 which would cause a subsequent I/O
441 	 * access from user space to trigger a #GP because tbe bitmap is outside
442 	 * the TSS limit.
443 	 */
444 	refresh_tss_limit();
445 }
446 #else /* CONFIG_X86_IOPL_IOPERM */
447 static inline void switch_to_bitmap(unsigned long tifp) { }
448 #endif
449 
450 #ifdef CONFIG_SMP
451 
452 struct ssb_state {
453 	struct ssb_state	*shared_state;
454 	raw_spinlock_t		lock;
455 	unsigned int		disable_state;
456 	unsigned long		local_state;
457 };
458 
459 #define LSTATE_SSB	0
460 
461 static DEFINE_PER_CPU(struct ssb_state, ssb_state);
462 
463 void speculative_store_bypass_ht_init(void)
464 {
465 	struct ssb_state *st = this_cpu_ptr(&ssb_state);
466 	unsigned int this_cpu = smp_processor_id();
467 	unsigned int cpu;
468 
469 	st->local_state = 0;
470 
471 	/*
472 	 * Shared state setup happens once on the first bringup
473 	 * of the CPU. It's not destroyed on CPU hotunplug.
474 	 */
475 	if (st->shared_state)
476 		return;
477 
478 	raw_spin_lock_init(&st->lock);
479 
480 	/*
481 	 * Go over HT siblings and check whether one of them has set up the
482 	 * shared state pointer already.
483 	 */
484 	for_each_cpu(cpu, topology_sibling_cpumask(this_cpu)) {
485 		if (cpu == this_cpu)
486 			continue;
487 
488 		if (!per_cpu(ssb_state, cpu).shared_state)
489 			continue;
490 
491 		/* Link it to the state of the sibling: */
492 		st->shared_state = per_cpu(ssb_state, cpu).shared_state;
493 		return;
494 	}
495 
496 	/*
497 	 * First HT sibling to come up on the core.  Link shared state of
498 	 * the first HT sibling to itself. The siblings on the same core
499 	 * which come up later will see the shared state pointer and link
500 	 * themselves to the state of this CPU.
501 	 */
502 	st->shared_state = st;
503 }
504 
505 /*
506  * Logic is: First HT sibling enables SSBD for both siblings in the core
507  * and last sibling to disable it, disables it for the whole core. This how
508  * MSR_SPEC_CTRL works in "hardware":
509  *
510  *  CORE_SPEC_CTRL = THREAD0_SPEC_CTRL | THREAD1_SPEC_CTRL
511  */
512 static __always_inline void amd_set_core_ssb_state(unsigned long tifn)
513 {
514 	struct ssb_state *st = this_cpu_ptr(&ssb_state);
515 	u64 msr = x86_amd_ls_cfg_base;
516 
517 	if (!static_cpu_has(X86_FEATURE_ZEN)) {
518 		msr |= ssbd_tif_to_amd_ls_cfg(tifn);
519 		wrmsrl(MSR_AMD64_LS_CFG, msr);
520 		return;
521 	}
522 
523 	if (tifn & _TIF_SSBD) {
524 		/*
525 		 * Since this can race with prctl(), block reentry on the
526 		 * same CPU.
527 		 */
528 		if (__test_and_set_bit(LSTATE_SSB, &st->local_state))
529 			return;
530 
531 		msr |= x86_amd_ls_cfg_ssbd_mask;
532 
533 		raw_spin_lock(&st->shared_state->lock);
534 		/* First sibling enables SSBD: */
535 		if (!st->shared_state->disable_state)
536 			wrmsrl(MSR_AMD64_LS_CFG, msr);
537 		st->shared_state->disable_state++;
538 		raw_spin_unlock(&st->shared_state->lock);
539 	} else {
540 		if (!__test_and_clear_bit(LSTATE_SSB, &st->local_state))
541 			return;
542 
543 		raw_spin_lock(&st->shared_state->lock);
544 		st->shared_state->disable_state--;
545 		if (!st->shared_state->disable_state)
546 			wrmsrl(MSR_AMD64_LS_CFG, msr);
547 		raw_spin_unlock(&st->shared_state->lock);
548 	}
549 }
550 #else
551 static __always_inline void amd_set_core_ssb_state(unsigned long tifn)
552 {
553 	u64 msr = x86_amd_ls_cfg_base | ssbd_tif_to_amd_ls_cfg(tifn);
554 
555 	wrmsrl(MSR_AMD64_LS_CFG, msr);
556 }
557 #endif
558 
559 static __always_inline void amd_set_ssb_virt_state(unsigned long tifn)
560 {
561 	/*
562 	 * SSBD has the same definition in SPEC_CTRL and VIRT_SPEC_CTRL,
563 	 * so ssbd_tif_to_spec_ctrl() just works.
564 	 */
565 	wrmsrl(MSR_AMD64_VIRT_SPEC_CTRL, ssbd_tif_to_spec_ctrl(tifn));
566 }
567 
568 /*
569  * Update the MSRs managing speculation control, during context switch.
570  *
571  * tifp: Previous task's thread flags
572  * tifn: Next task's thread flags
573  */
574 static __always_inline void __speculation_ctrl_update(unsigned long tifp,
575 						      unsigned long tifn)
576 {
577 	unsigned long tif_diff = tifp ^ tifn;
578 	u64 msr = x86_spec_ctrl_base;
579 	bool updmsr = false;
580 
581 	lockdep_assert_irqs_disabled();
582 
583 	/* Handle change of TIF_SSBD depending on the mitigation method. */
584 	if (static_cpu_has(X86_FEATURE_VIRT_SSBD)) {
585 		if (tif_diff & _TIF_SSBD)
586 			amd_set_ssb_virt_state(tifn);
587 	} else if (static_cpu_has(X86_FEATURE_LS_CFG_SSBD)) {
588 		if (tif_diff & _TIF_SSBD)
589 			amd_set_core_ssb_state(tifn);
590 	} else if (static_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) ||
591 		   static_cpu_has(X86_FEATURE_AMD_SSBD)) {
592 		updmsr |= !!(tif_diff & _TIF_SSBD);
593 		msr |= ssbd_tif_to_spec_ctrl(tifn);
594 	}
595 
596 	/* Only evaluate TIF_SPEC_IB if conditional STIBP is enabled. */
597 	if (IS_ENABLED(CONFIG_SMP) &&
598 	    static_branch_unlikely(&switch_to_cond_stibp)) {
599 		updmsr |= !!(tif_diff & _TIF_SPEC_IB);
600 		msr |= stibp_tif_to_spec_ctrl(tifn);
601 	}
602 
603 	if (updmsr)
604 		update_spec_ctrl_cond(msr);
605 }
606 
607 static unsigned long speculation_ctrl_update_tif(struct task_struct *tsk)
608 {
609 	if (test_and_clear_tsk_thread_flag(tsk, TIF_SPEC_FORCE_UPDATE)) {
610 		if (task_spec_ssb_disable(tsk))
611 			set_tsk_thread_flag(tsk, TIF_SSBD);
612 		else
613 			clear_tsk_thread_flag(tsk, TIF_SSBD);
614 
615 		if (task_spec_ib_disable(tsk))
616 			set_tsk_thread_flag(tsk, TIF_SPEC_IB);
617 		else
618 			clear_tsk_thread_flag(tsk, TIF_SPEC_IB);
619 	}
620 	/* Return the updated threadinfo flags*/
621 	return read_task_thread_flags(tsk);
622 }
623 
624 void speculation_ctrl_update(unsigned long tif)
625 {
626 	unsigned long flags;
627 
628 	/* Forced update. Make sure all relevant TIF flags are different */
629 	local_irq_save(flags);
630 	__speculation_ctrl_update(~tif, tif);
631 	local_irq_restore(flags);
632 }
633 
634 /* Called from seccomp/prctl update */
635 void speculation_ctrl_update_current(void)
636 {
637 	preempt_disable();
638 	speculation_ctrl_update(speculation_ctrl_update_tif(current));
639 	preempt_enable();
640 }
641 
642 static inline void cr4_toggle_bits_irqsoff(unsigned long mask)
643 {
644 	unsigned long newval, cr4 = this_cpu_read(cpu_tlbstate.cr4);
645 
646 	newval = cr4 ^ mask;
647 	if (newval != cr4) {
648 		this_cpu_write(cpu_tlbstate.cr4, newval);
649 		__write_cr4(newval);
650 	}
651 }
652 
653 void __switch_to_xtra(struct task_struct *prev_p, struct task_struct *next_p)
654 {
655 	unsigned long tifp, tifn;
656 
657 	tifn = read_task_thread_flags(next_p);
658 	tifp = read_task_thread_flags(prev_p);
659 
660 	switch_to_bitmap(tifp);
661 
662 	propagate_user_return_notify(prev_p, next_p);
663 
664 	if ((tifp & _TIF_BLOCKSTEP || tifn & _TIF_BLOCKSTEP) &&
665 	    arch_has_block_step()) {
666 		unsigned long debugctl, msk;
667 
668 		rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
669 		debugctl &= ~DEBUGCTLMSR_BTF;
670 		msk = tifn & _TIF_BLOCKSTEP;
671 		debugctl |= (msk >> TIF_BLOCKSTEP) << DEBUGCTLMSR_BTF_SHIFT;
672 		wrmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
673 	}
674 
675 	if ((tifp ^ tifn) & _TIF_NOTSC)
676 		cr4_toggle_bits_irqsoff(X86_CR4_TSD);
677 
678 	if ((tifp ^ tifn) & _TIF_NOCPUID)
679 		set_cpuid_faulting(!!(tifn & _TIF_NOCPUID));
680 
681 	if (likely(!((tifp | tifn) & _TIF_SPEC_FORCE_UPDATE))) {
682 		__speculation_ctrl_update(tifp, tifn);
683 	} else {
684 		speculation_ctrl_update_tif(prev_p);
685 		tifn = speculation_ctrl_update_tif(next_p);
686 
687 		/* Enforce MSR update to ensure consistent state */
688 		__speculation_ctrl_update(~tifn, tifn);
689 	}
690 }
691 
692 /*
693  * Idle related variables and functions
694  */
695 unsigned long boot_option_idle_override = IDLE_NO_OVERRIDE;
696 EXPORT_SYMBOL(boot_option_idle_override);
697 
698 /*
699  * We use this if we don't have any better idle routine..
700  */
701 void __cpuidle default_idle(void)
702 {
703 	raw_safe_halt();
704 	raw_local_irq_disable();
705 }
706 #if defined(CONFIG_APM_MODULE) || defined(CONFIG_HALTPOLL_CPUIDLE_MODULE)
707 EXPORT_SYMBOL(default_idle);
708 #endif
709 
710 DEFINE_STATIC_CALL_NULL(x86_idle, default_idle);
711 
712 static bool x86_idle_set(void)
713 {
714 	return !!static_call_query(x86_idle);
715 }
716 
717 #ifndef CONFIG_SMP
718 static inline void play_dead(void)
719 {
720 	BUG();
721 }
722 #endif
723 
724 void arch_cpu_idle_enter(void)
725 {
726 	tsc_verify_tsc_adjust(false);
727 	local_touch_nmi();
728 }
729 
730 void arch_cpu_idle_dead(void)
731 {
732 	play_dead();
733 }
734 
735 /*
736  * Called from the generic idle code.
737  */
738 void __cpuidle arch_cpu_idle(void)
739 {
740 	static_call(x86_idle)();
741 }
742 EXPORT_SYMBOL_GPL(arch_cpu_idle);
743 
744 #ifdef CONFIG_XEN
745 bool xen_set_default_idle(void)
746 {
747 	bool ret = x86_idle_set();
748 
749 	static_call_update(x86_idle, default_idle);
750 
751 	return ret;
752 }
753 #endif
754 
755 void __noreturn stop_this_cpu(void *dummy)
756 {
757 	local_irq_disable();
758 	/*
759 	 * Remove this CPU:
760 	 */
761 	set_cpu_online(smp_processor_id(), false);
762 	disable_local_APIC();
763 	mcheck_cpu_clear(this_cpu_ptr(&cpu_info));
764 
765 	/*
766 	 * Use wbinvd on processors that support SME. This provides support
767 	 * for performing a successful kexec when going from SME inactive
768 	 * to SME active (or vice-versa). The cache must be cleared so that
769 	 * if there are entries with the same physical address, both with and
770 	 * without the encryption bit, they don't race each other when flushed
771 	 * and potentially end up with the wrong entry being committed to
772 	 * memory.
773 	 *
774 	 * Test the CPUID bit directly because the machine might've cleared
775 	 * X86_FEATURE_SME due to cmdline options.
776 	 */
777 	if (cpuid_eax(0x8000001f) & BIT(0))
778 		native_wbinvd();
779 	for (;;) {
780 		/*
781 		 * Use native_halt() so that memory contents don't change
782 		 * (stack usage and variables) after possibly issuing the
783 		 * native_wbinvd() above.
784 		 */
785 		native_halt();
786 	}
787 }
788 
789 /*
790  * AMD Erratum 400 aware idle routine. We handle it the same way as C3 power
791  * states (local apic timer and TSC stop).
792  *
793  * XXX this function is completely buggered vs RCU and tracing.
794  */
795 static void amd_e400_idle(void)
796 {
797 	/*
798 	 * We cannot use static_cpu_has_bug() here because X86_BUG_AMD_APIC_C1E
799 	 * gets set after static_cpu_has() places have been converted via
800 	 * alternatives.
801 	 */
802 	if (!boot_cpu_has_bug(X86_BUG_AMD_APIC_C1E)) {
803 		default_idle();
804 		return;
805 	}
806 
807 	tick_broadcast_enter();
808 
809 	default_idle();
810 
811 	tick_broadcast_exit();
812 }
813 
814 /*
815  * Prefer MWAIT over HALT if MWAIT is supported, MWAIT_CPUID leaf
816  * exists and whenever MONITOR/MWAIT extensions are present there is at
817  * least one C1 substate.
818  *
819  * Do not prefer MWAIT if MONITOR instruction has a bug or idle=nomwait
820  * is passed to kernel commandline parameter.
821  */
822 static int prefer_mwait_c1_over_halt(const struct cpuinfo_x86 *c)
823 {
824 	u32 eax, ebx, ecx, edx;
825 
826 	/* User has disallowed the use of MWAIT. Fallback to HALT */
827 	if (boot_option_idle_override == IDLE_NOMWAIT)
828 		return 0;
829 
830 	/* MWAIT is not supported on this platform. Fallback to HALT */
831 	if (!cpu_has(c, X86_FEATURE_MWAIT))
832 		return 0;
833 
834 	/* Monitor has a bug. Fallback to HALT */
835 	if (boot_cpu_has_bug(X86_BUG_MONITOR))
836 		return 0;
837 
838 	cpuid(CPUID_MWAIT_LEAF, &eax, &ebx, &ecx, &edx);
839 
840 	/*
841 	 * If MWAIT extensions are not available, it is safe to use MWAIT
842 	 * with EAX=0, ECX=0.
843 	 */
844 	if (!(ecx & CPUID5_ECX_EXTENSIONS_SUPPORTED))
845 		return 1;
846 
847 	/*
848 	 * If MWAIT extensions are available, there should be at least one
849 	 * MWAIT C1 substate present.
850 	 */
851 	return (edx & MWAIT_C1_SUBSTATE_MASK);
852 }
853 
854 /*
855  * MONITOR/MWAIT with no hints, used for default C1 state. This invokes MWAIT
856  * with interrupts enabled and no flags, which is backwards compatible with the
857  * original MWAIT implementation.
858  */
859 static __cpuidle void mwait_idle(void)
860 {
861 	if (!current_set_polling_and_test()) {
862 		if (this_cpu_has(X86_BUG_CLFLUSH_MONITOR)) {
863 			mb(); /* quirk */
864 			clflush((void *)&current_thread_info()->flags);
865 			mb(); /* quirk */
866 		}
867 
868 		__monitor((void *)&current_thread_info()->flags, 0, 0);
869 		if (!need_resched()) {
870 			__sti_mwait(0, 0);
871 			raw_local_irq_disable();
872 		}
873 	}
874 	__current_clr_polling();
875 }
876 
877 void select_idle_routine(const struct cpuinfo_x86 *c)
878 {
879 #ifdef CONFIG_SMP
880 	if (boot_option_idle_override == IDLE_POLL && smp_num_siblings > 1)
881 		pr_warn_once("WARNING: polling idle and HT enabled, performance may degrade\n");
882 #endif
883 	if (x86_idle_set() || boot_option_idle_override == IDLE_POLL)
884 		return;
885 
886 	if (boot_cpu_has_bug(X86_BUG_AMD_E400)) {
887 		pr_info("using AMD E400 aware idle routine\n");
888 		static_call_update(x86_idle, amd_e400_idle);
889 	} else if (prefer_mwait_c1_over_halt(c)) {
890 		pr_info("using mwait in idle threads\n");
891 		static_call_update(x86_idle, mwait_idle);
892 	} else if (cpu_feature_enabled(X86_FEATURE_TDX_GUEST)) {
893 		pr_info("using TDX aware idle routine\n");
894 		static_call_update(x86_idle, tdx_safe_halt);
895 	} else
896 		static_call_update(x86_idle, default_idle);
897 }
898 
899 void amd_e400_c1e_apic_setup(void)
900 {
901 	if (boot_cpu_has_bug(X86_BUG_AMD_APIC_C1E)) {
902 		pr_info("Switch to broadcast mode on CPU%d\n", smp_processor_id());
903 		local_irq_disable();
904 		tick_broadcast_force();
905 		local_irq_enable();
906 	}
907 }
908 
909 void __init arch_post_acpi_subsys_init(void)
910 {
911 	u32 lo, hi;
912 
913 	if (!boot_cpu_has_bug(X86_BUG_AMD_E400))
914 		return;
915 
916 	/*
917 	 * AMD E400 detection needs to happen after ACPI has been enabled. If
918 	 * the machine is affected K8_INTP_C1E_ACTIVE_MASK bits are set in
919 	 * MSR_K8_INT_PENDING_MSG.
920 	 */
921 	rdmsr(MSR_K8_INT_PENDING_MSG, lo, hi);
922 	if (!(lo & K8_INTP_C1E_ACTIVE_MASK))
923 		return;
924 
925 	boot_cpu_set_bug(X86_BUG_AMD_APIC_C1E);
926 
927 	if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC))
928 		mark_tsc_unstable("TSC halt in AMD C1E");
929 	pr_info("System has AMD C1E enabled\n");
930 }
931 
932 static int __init idle_setup(char *str)
933 {
934 	if (!str)
935 		return -EINVAL;
936 
937 	if (!strcmp(str, "poll")) {
938 		pr_info("using polling idle threads\n");
939 		boot_option_idle_override = IDLE_POLL;
940 		cpu_idle_poll_ctrl(true);
941 	} else if (!strcmp(str, "halt")) {
942 		/*
943 		 * When the boot option of idle=halt is added, halt is
944 		 * forced to be used for CPU idle. In such case CPU C2/C3
945 		 * won't be used again.
946 		 * To continue to load the CPU idle driver, don't touch
947 		 * the boot_option_idle_override.
948 		 */
949 		static_call_update(x86_idle, default_idle);
950 		boot_option_idle_override = IDLE_HALT;
951 	} else if (!strcmp(str, "nomwait")) {
952 		/*
953 		 * If the boot option of "idle=nomwait" is added,
954 		 * it means that mwait will be disabled for CPU C1/C2/C3
955 		 * states.
956 		 */
957 		boot_option_idle_override = IDLE_NOMWAIT;
958 	} else
959 		return -1;
960 
961 	return 0;
962 }
963 early_param("idle", idle_setup);
964 
965 unsigned long arch_align_stack(unsigned long sp)
966 {
967 	if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space)
968 		sp -= get_random_u32_below(8192);
969 	return sp & ~0xf;
970 }
971 
972 unsigned long arch_randomize_brk(struct mm_struct *mm)
973 {
974 	return randomize_page(mm->brk, 0x02000000);
975 }
976 
977 /*
978  * Called from fs/proc with a reference on @p to find the function
979  * which called into schedule(). This needs to be done carefully
980  * because the task might wake up and we might look at a stack
981  * changing under us.
982  */
983 unsigned long __get_wchan(struct task_struct *p)
984 {
985 	struct unwind_state state;
986 	unsigned long addr = 0;
987 
988 	if (!try_get_task_stack(p))
989 		return 0;
990 
991 	for (unwind_start(&state, p, NULL, NULL); !unwind_done(&state);
992 	     unwind_next_frame(&state)) {
993 		addr = unwind_get_return_address(&state);
994 		if (!addr)
995 			break;
996 		if (in_sched_functions(addr))
997 			continue;
998 		break;
999 	}
1000 
1001 	put_task_stack(p);
1002 
1003 	return addr;
1004 }
1005 
1006 long do_arch_prctl_common(int option, unsigned long arg2)
1007 {
1008 	switch (option) {
1009 	case ARCH_GET_CPUID:
1010 		return get_cpuid_mode();
1011 	case ARCH_SET_CPUID:
1012 		return set_cpuid_mode(arg2);
1013 	case ARCH_GET_XCOMP_SUPP:
1014 	case ARCH_GET_XCOMP_PERM:
1015 	case ARCH_REQ_XCOMP_PERM:
1016 	case ARCH_GET_XCOMP_GUEST_PERM:
1017 	case ARCH_REQ_XCOMP_GUEST_PERM:
1018 		return fpu_xstate_prctl(option, arg2);
1019 	}
1020 
1021 	return -EINVAL;
1022 }
1023