xref: /linux/arch/x86/kernel/fpu/core.c (revision 4cbdd58dfa7aaad679bf62f81cdbc96a6cb7c6ae)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  Copyright (C) 1994 Linus Torvalds
4  *
5  *  Pentium III FXSR, SSE support
6  *  General FPU state handling cleanups
7  *	Gareth Hughes <gareth@valinux.com>, May 2000
8  */
9 #include <asm/fpu/api.h>
10 #include <asm/fpu/regset.h>
11 #include <asm/fpu/sched.h>
12 #include <asm/fpu/signal.h>
13 #include <asm/fpu/types.h>
14 #include <asm/msr.h>
15 #include <asm/traps.h>
16 #include <asm/irq_regs.h>
17 
18 #include <uapi/asm/kvm.h>
19 
20 #include <linux/hardirq.h>
21 #include <linux/kvm_types.h>
22 #include <linux/pkeys.h>
23 #include <linux/vmalloc.h>
24 
25 #include "context.h"
26 #include "internal.h"
27 #include "legacy.h"
28 #include "xstate.h"
29 
30 #define CREATE_TRACE_POINTS
31 #include <asm/trace/fpu.h>
32 
33 #ifdef CONFIG_X86_64
34 DEFINE_STATIC_KEY_FALSE(__fpu_state_size_dynamic);
35 DEFINE_PER_CPU(u64, xfd_state);
36 #endif
37 
38 /* The FPU state configuration data for kernel and user space */
39 struct fpu_state_config	fpu_kernel_cfg __ro_after_init;
40 struct fpu_state_config fpu_user_cfg __ro_after_init;
41 struct vcpu_fpu_config guest_default_cfg __ro_after_init;
42 
43 /*
44  * Represents the initial FPU state. It's mostly (but not completely) zeroes,
45  * depending on the FPU hardware format:
46  */
47 struct fpstate init_fpstate __ro_after_init;
48 
49 /*
50  * Track FPU initialization and kernel-mode usage. 'true' means the FPU is
51  * initialized and is not currently being used by the kernel:
52  */
53 DEFINE_PER_CPU(bool, kernel_fpu_allowed);
54 
55 /*
56  * Track which context is using the FPU on the CPU:
57  */
58 DEFINE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
59 
60 #ifdef CONFIG_X86_DEBUG_FPU
x86_task_fpu(struct task_struct * task)61 struct fpu *x86_task_fpu(struct task_struct *task)
62 {
63 	if (WARN_ON_ONCE(task->flags & PF_KTHREAD))
64 		return NULL;
65 
66 	return (void *)task + sizeof(*task);
67 }
68 #endif
69 
70 /*
71  * Can we use the FPU in kernel mode with the
72  * whole "kernel_fpu_begin/end()" sequence?
73  */
irq_fpu_usable(void)74 bool irq_fpu_usable(void)
75 {
76 	if (WARN_ON_ONCE(in_nmi()))
77 		return false;
78 
79 	/*
80 	 * Return false in the following cases:
81 	 *
82 	 * - FPU is not yet initialized. This can happen only when the call is
83 	 *   coming from CPU onlining, for example for microcode checksumming.
84 	 * - The kernel is already using the FPU, either because of explicit
85 	 *   nesting (which should never be done), or because of implicit
86 	 *   nesting when a hardirq interrupted a kernel-mode FPU section.
87 	 *
88 	 * The single boolean check below handles both cases:
89 	 */
90 	if (!this_cpu_read(kernel_fpu_allowed))
91 		return false;
92 
93 	/*
94 	 * When not in NMI or hard interrupt context, FPU can be used in:
95 	 *
96 	 * - Task context except from within fpregs_lock()'ed critical
97 	 *   regions.
98 	 *
99 	 * - Soft interrupt processing context which cannot happen
100 	 *   while in a fpregs_lock()'ed critical region.
101 	 */
102 	if (!in_hardirq())
103 		return true;
104 
105 	/*
106 	 * In hard interrupt context it's safe when soft interrupts
107 	 * are enabled, which means the interrupt did not hit in
108 	 * a fpregs_lock()'ed critical region.
109 	 */
110 	return !softirq_count();
111 }
112 EXPORT_SYMBOL(irq_fpu_usable);
113 
114 /*
115  * Track AVX512 state use because it is known to slow the max clock
116  * speed of the core.
117  */
update_avx_timestamp(struct fpu * fpu)118 static void update_avx_timestamp(struct fpu *fpu)
119 {
120 
121 #define AVX512_TRACKING_MASK	(XFEATURE_MASK_ZMM_Hi256 | XFEATURE_MASK_Hi16_ZMM)
122 
123 	if (fpu->fpstate->regs.xsave.header.xfeatures & AVX512_TRACKING_MASK)
124 		fpu->avx512_timestamp = jiffies;
125 }
126 
127 /*
128  * Save the FPU register state in fpu->fpstate->regs. The register state is
129  * preserved.
130  *
131  * Must be called with fpregs_lock() held.
132  *
133  * The legacy FNSAVE instruction clears all FPU state unconditionally, so
134  * register state has to be reloaded. That might be a pointless exercise
135  * when the FPU is going to be used by another task right after that. But
136  * this only affects 20+ years old 32bit systems and avoids conditionals all
137  * over the place.
138  *
139  * FXSAVE and all XSAVE variants preserve the FPU register state.
140  */
save_fpregs_to_fpstate(struct fpu * fpu)141 void save_fpregs_to_fpstate(struct fpu *fpu)
142 {
143 	if (likely(use_xsave())) {
144 		os_xsave(fpu->fpstate);
145 		update_avx_timestamp(fpu);
146 		return;
147 	}
148 
149 	if (likely(use_fxsr())) {
150 		fxsave(&fpu->fpstate->regs.fxsave);
151 		return;
152 	}
153 
154 	/*
155 	 * Legacy FPU register saving, FNSAVE always clears FPU registers,
156 	 * so we have to reload them from the memory state.
157 	 */
158 	asm volatile("fnsave %[fp]; fwait" : [fp] "=m" (fpu->fpstate->regs.fsave));
159 	frstor(&fpu->fpstate->regs.fsave);
160 }
161 
restore_fpregs_from_fpstate(struct fpstate * fpstate,u64 mask)162 void restore_fpregs_from_fpstate(struct fpstate *fpstate, u64 mask)
163 {
164 	/*
165 	 * AMD K7/K8 and later CPUs up to Zen don't save/restore
166 	 * FDP/FIP/FOP unless an exception is pending. Clear the x87 state
167 	 * here by setting it to fixed values.  "m" is a random variable
168 	 * that should be in L1.
169 	 */
170 	if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {
171 		asm volatile(
172 			"fnclex\n\t"
173 			"emms\n\t"
174 			"fildl %[addr]"	/* set F?P to defined value */
175 			: : [addr] "m" (*fpstate));
176 	}
177 
178 	if (use_xsave()) {
179 		/*
180 		 * Dynamically enabled features are enabled in XCR0, but
181 		 * usage requires also that the corresponding bits in XFD
182 		 * are cleared.  If the bits are set then using a related
183 		 * instruction will raise #NM. This allows to do the
184 		 * allocation of the larger FPU buffer lazy from #NM or if
185 		 * the task has no permission to kill it which would happen
186 		 * via #UD if the feature is disabled in XCR0.
187 		 *
188 		 * XFD state is following the same life time rules as
189 		 * XSTATE and to restore state correctly XFD has to be
190 		 * updated before XRSTORS otherwise the component would
191 		 * stay in or go into init state even if the bits are set
192 		 * in fpstate::regs::xsave::xfeatures.
193 		 */
194 		xfd_update_state(fpstate);
195 
196 		/*
197 		 * Restoring state always needs to modify all features
198 		 * which are in @mask even if the current task cannot use
199 		 * extended features.
200 		 *
201 		 * So fpstate->xfeatures cannot be used here, because then
202 		 * a feature for which the task has no permission but was
203 		 * used by the previous task would not go into init state.
204 		 */
205 		mask = fpu_kernel_cfg.max_features & mask;
206 
207 		os_xrstor(fpstate, mask);
208 	} else {
209 		if (use_fxsr())
210 			fxrstor(&fpstate->regs.fxsave);
211 		else
212 			frstor(&fpstate->regs.fsave);
213 	}
214 }
215 
216 /*
217  * Save the FPU register state in fpu->fpstate->regs and set
218  * TIF_NEED_FPU_LOAD subsequently.
219  *
220  * Must be called with fpregs_lock() held, ensuring flag
221  * TIF_NEED_FPU_LOAD is set last.
222  */
update_fpu_state_and_flag(struct fpu * fpu,struct task_struct * task)223 void update_fpu_state_and_flag(struct fpu *fpu, struct task_struct *task)
224 {
225 	save_fpregs_to_fpstate(fpu);
226 	set_tsk_thread_flag(task, TIF_NEED_FPU_LOAD);
227 }
228 
fpu_reset_from_exception_fixup(void)229 void fpu_reset_from_exception_fixup(void)
230 {
231 	restore_fpregs_from_fpstate(&init_fpstate, XFEATURE_MASK_FPSTATE);
232 }
233 
234 #if IS_ENABLED(CONFIG_KVM)
235 static void __fpstate_reset(struct fpstate *fpstate);
236 
fpu_lock_guest_permissions(void)237 static void fpu_lock_guest_permissions(void)
238 {
239 	struct fpu_state_perm *fpuperm;
240 	u64 perm;
241 
242 	if (!IS_ENABLED(CONFIG_X86_64))
243 		return;
244 
245 	spin_lock_irq(&current->sighand->siglock);
246 	fpuperm = &x86_task_fpu(current->group_leader)->guest_perm;
247 	perm = fpuperm->__state_perm;
248 
249 	/* First fpstate allocation locks down permissions. */
250 	WRITE_ONCE(fpuperm->__state_perm, perm | FPU_GUEST_PERM_LOCKED);
251 
252 	spin_unlock_irq(&current->sighand->siglock);
253 }
254 
fpu_alloc_guest_fpstate(struct fpu_guest * gfpu)255 bool fpu_alloc_guest_fpstate(struct fpu_guest *gfpu)
256 {
257 	struct fpstate *fpstate;
258 	unsigned int size;
259 
260 	size = guest_default_cfg.size + ALIGN(offsetof(struct fpstate, regs), 64);
261 
262 	fpstate = vzalloc(size);
263 	if (!fpstate)
264 		return false;
265 
266 	/* Initialize indicators to reflect properties of the fpstate */
267 	fpstate->is_valloc	= true;
268 	fpstate->is_guest	= true;
269 
270 	__fpstate_reset(fpstate);
271 	fpstate_init_user(fpstate);
272 
273 	gfpu->fpstate		= fpstate;
274 	gfpu->xfeatures		= guest_default_cfg.features;
275 
276 	/*
277 	 * KVM sets the FP+SSE bits in the XSAVE header when copying FPU state
278 	 * to userspace, even when XSAVE is unsupported, so that restoring FPU
279 	 * state on a different CPU that does support XSAVE can cleanly load
280 	 * the incoming state using its natural XSAVE.  In other words, KVM's
281 	 * uABI size may be larger than this host's default size.  Conversely,
282 	 * the default size should never be larger than KVM's base uABI size;
283 	 * all features that can expand the uABI size must be opt-in.
284 	 */
285 	gfpu->uabi_size		= sizeof(struct kvm_xsave);
286 	if (WARN_ON_ONCE(fpu_user_cfg.default_size > gfpu->uabi_size))
287 		gfpu->uabi_size = fpu_user_cfg.default_size;
288 
289 	fpu_lock_guest_permissions();
290 
291 	return true;
292 }
293 EXPORT_SYMBOL_FOR_KVM(fpu_alloc_guest_fpstate);
294 
fpu_free_guest_fpstate(struct fpu_guest * gfpu)295 void fpu_free_guest_fpstate(struct fpu_guest *gfpu)
296 {
297 	struct fpstate *fpstate = gfpu->fpstate;
298 
299 	if (!fpstate)
300 		return;
301 
302 	if (WARN_ON_ONCE(!fpstate->is_valloc || !fpstate->is_guest || fpstate->in_use))
303 		return;
304 
305 	gfpu->fpstate = NULL;
306 	vfree(fpstate);
307 }
308 EXPORT_SYMBOL_FOR_KVM(fpu_free_guest_fpstate);
309 
310 /**
311  * fpu_enable_guest_xfd_features - Check xfeatures against guest perm and enable
312  * @guest_fpu:		Pointer to the guest FPU container
313  * @xfeatures:		Features requested by guest CPUID
314  *
315  * Enable all dynamic xfeatures according to guest perm and requested CPUID.
316  *
317  * Return: 0 on success, error code otherwise
318  */
fpu_enable_guest_xfd_features(struct fpu_guest * guest_fpu,u64 xfeatures)319 int fpu_enable_guest_xfd_features(struct fpu_guest *guest_fpu, u64 xfeatures)
320 {
321 	lockdep_assert_preemption_enabled();
322 
323 	/* Nothing to do if all requested features are already enabled. */
324 	xfeatures &= ~guest_fpu->xfeatures;
325 	if (!xfeatures)
326 		return 0;
327 
328 	return __xfd_enable_feature(xfeatures, guest_fpu);
329 }
330 EXPORT_SYMBOL_FOR_KVM(fpu_enable_guest_xfd_features);
331 
332 #ifdef CONFIG_X86_64
fpu_update_guest_xfd(struct fpu_guest * guest_fpu,u64 xfd)333 void fpu_update_guest_xfd(struct fpu_guest *guest_fpu, u64 xfd)
334 {
335 	struct fpstate *fpstate = guest_fpu->fpstate;
336 
337 	fpregs_lock();
338 
339 	/*
340 	 * KVM's guest ABI is that setting XFD[i]=1 *can* immediately revert the
341 	 * save state to its initial configuration.  Likewise, KVM_GET_XSAVE does
342 	 * the same as XSAVE and returns XSTATE_BV[i]=0 whenever XFD[i]=1.
343 	 *
344 	 * If the guest's FPU state is in hardware, just update XFD: the XSAVE
345 	 * in fpu_swap_kvm_fpstate will clear XSTATE_BV[i] whenever XFD[i]=1.
346 	 *
347 	 * If however the guest's FPU state is NOT resident in hardware, clear
348 	 * disabled components in XSTATE_BV now, or a subsequent XRSTOR will
349 	 * attempt to load disabled components and generate #NM _in the host_.
350 	 */
351 	if (xfd && test_thread_flag(TIF_NEED_FPU_LOAD))
352 		fpstate->regs.xsave.header.xfeatures &= ~xfd;
353 
354 	fpstate->xfd = xfd;
355 	if (fpstate->in_use)
356 		xfd_update_state(fpstate);
357 
358 	fpregs_unlock();
359 }
360 EXPORT_SYMBOL_FOR_KVM(fpu_update_guest_xfd);
361 
362 /**
363  * fpu_sync_guest_vmexit_xfd_state - Synchronize XFD MSR and software state
364  *
365  * Must be invoked from KVM after a VMEXIT before enabling interrupts when
366  * XFD write emulation is disabled. This is required because the guest can
367  * freely modify XFD and the state at VMEXIT is not guaranteed to be the
368  * same as the state on VMENTER. So software state has to be updated before
369  * any operation which depends on it can take place.
370  *
371  * Note: It can be invoked unconditionally even when write emulation is
372  * enabled for the price of a then pointless MSR read.
373  */
fpu_sync_guest_vmexit_xfd_state(void)374 void fpu_sync_guest_vmexit_xfd_state(void)
375 {
376 	struct fpstate *fpstate = x86_task_fpu(current)->fpstate;
377 
378 	lockdep_assert_irqs_disabled();
379 	if (fpu_state_size_dynamic()) {
380 		rdmsrq(MSR_IA32_XFD, fpstate->xfd);
381 		__this_cpu_write(xfd_state, fpstate->xfd);
382 	}
383 }
384 EXPORT_SYMBOL_FOR_KVM(fpu_sync_guest_vmexit_xfd_state);
385 #endif /* CONFIG_X86_64 */
386 
fpu_swap_kvm_fpstate(struct fpu_guest * guest_fpu,bool enter_guest)387 int fpu_swap_kvm_fpstate(struct fpu_guest *guest_fpu, bool enter_guest)
388 {
389 	struct fpstate *guest_fps = guest_fpu->fpstate;
390 	struct fpu *fpu = x86_task_fpu(current);
391 	struct fpstate *cur_fps = fpu->fpstate;
392 
393 	fpregs_lock();
394 	if (!cur_fps->is_confidential && !test_thread_flag(TIF_NEED_FPU_LOAD))
395 		save_fpregs_to_fpstate(fpu);
396 
397 	/* Swap fpstate */
398 	if (enter_guest) {
399 		WRITE_ONCE(fpu->__task_fpstate, cur_fps);
400 		barrier();
401 		fpu->fpstate = guest_fps;
402 		guest_fps->in_use = true;
403 	} else {
404 		guest_fps->in_use = false;
405 		fpu->fpstate = fpu->__task_fpstate;
406 	}
407 
408 	cur_fps = fpu->fpstate;
409 
410 	if (!cur_fps->is_confidential) {
411 		/* Includes XFD update */
412 		restore_fpregs_from_fpstate(cur_fps, XFEATURE_MASK_FPSTATE);
413 	} else {
414 		/*
415 		 * XSTATE is restored by firmware from encrypted
416 		 * memory. Make sure XFD state is correct while
417 		 * running with guest fpstate
418 		 */
419 		xfd_update_state(cur_fps);
420 	}
421 
422 	/*
423 	 * Clear fpu->__task_fpstate after switching back to host state.
424 	 * A non-NULL __task_fpstate means guest state is still resident in
425 	 * hardware; reset it only once host state has been restored.
426 	 */
427 	if (!enter_guest) {
428 		barrier();
429 		WRITE_ONCE(fpu->__task_fpstate, NULL);
430 	}
431 
432 	fpregs_mark_activate();
433 	fpregs_unlock();
434 	return 0;
435 }
436 EXPORT_SYMBOL_FOR_KVM(fpu_swap_kvm_fpstate);
437 
fpu_copy_guest_fpstate_to_uabi(struct fpu_guest * gfpu,void * buf,unsigned int size,u64 xfeatures,u32 pkru)438 void fpu_copy_guest_fpstate_to_uabi(struct fpu_guest *gfpu, void *buf,
439 				    unsigned int size, u64 xfeatures, u32 pkru)
440 {
441 	struct fpstate *kstate = gfpu->fpstate;
442 	union fpregs_state *ustate = buf;
443 	struct membuf mb = { .p = buf, .left = size };
444 
445 	if (cpu_feature_enabled(X86_FEATURE_XSAVE)) {
446 		__copy_xstate_to_uabi_buf(mb, kstate, xfeatures, pkru,
447 					  XSTATE_COPY_XSAVE);
448 	} else {
449 		memcpy(&ustate->fxsave, &kstate->regs.fxsave,
450 		       sizeof(ustate->fxsave));
451 		/* Make it restorable on a XSAVE enabled host */
452 		ustate->xsave.header.xfeatures = XFEATURE_MASK_FPSSE;
453 	}
454 }
455 EXPORT_SYMBOL_FOR_KVM(fpu_copy_guest_fpstate_to_uabi);
456 
fpu_copy_uabi_to_guest_fpstate(struct fpu_guest * gfpu,const void * buf,u64 xcr0,u32 * vpkru)457 int fpu_copy_uabi_to_guest_fpstate(struct fpu_guest *gfpu, const void *buf,
458 				   u64 xcr0, u32 *vpkru)
459 {
460 	struct fpstate *kstate = gfpu->fpstate;
461 	const union fpregs_state *ustate = buf;
462 
463 	if (!cpu_feature_enabled(X86_FEATURE_XSAVE)) {
464 		if (ustate->xsave.header.xfeatures & ~XFEATURE_MASK_FPSSE)
465 			return -EINVAL;
466 		if (ustate->fxsave.mxcsr & ~mxcsr_feature_mask)
467 			return -EINVAL;
468 		memcpy(&kstate->regs.fxsave, &ustate->fxsave, sizeof(ustate->fxsave));
469 		return 0;
470 	}
471 
472 	if (ustate->xsave.header.xfeatures & ~xcr0)
473 		return -EINVAL;
474 
475 	/*
476 	 * Disabled features must be in their initial state, otherwise XRSTOR
477 	 * causes an exception.
478 	 */
479 	if (WARN_ON_ONCE(ustate->xsave.header.xfeatures & kstate->xfd))
480 		return -EINVAL;
481 
482 	/*
483 	 * Nullify @vpkru to preserve its current value if PKRU's bit isn't set
484 	 * in the header.  KVM's odd ABI is to leave PKRU untouched in this
485 	 * case (all other components are eventually re-initialized).
486 	 */
487 	if (!(ustate->xsave.header.xfeatures & XFEATURE_MASK_PKRU))
488 		vpkru = NULL;
489 
490 	return copy_uabi_from_kernel_to_xstate(kstate, ustate, vpkru);
491 }
492 EXPORT_SYMBOL_FOR_KVM(fpu_copy_uabi_to_guest_fpstate);
493 #endif /* CONFIG_KVM */
494 
kernel_fpu_begin_mask(unsigned int kfpu_mask)495 void kernel_fpu_begin_mask(unsigned int kfpu_mask)
496 {
497 	if (!irqs_disabled())
498 		fpregs_lock();
499 
500 	WARN_ON_FPU(!irq_fpu_usable());
501 
502 	/* Toggle kernel_fpu_allowed to false: */
503 	WARN_ON_FPU(!this_cpu_read(kernel_fpu_allowed));
504 	this_cpu_write(kernel_fpu_allowed, false);
505 
506 	if (!(current->flags & (PF_KTHREAD | PF_USER_WORKER)) &&
507 	    !test_thread_flag(TIF_NEED_FPU_LOAD))
508 		update_fpu_state_and_flag(x86_task_fpu(current), current);
509 	__cpu_invalidate_fpregs_state();
510 
511 	/* Put sane initial values into the control registers. */
512 	if (likely(kfpu_mask & KFPU_MXCSR) && boot_cpu_has(X86_FEATURE_XMM))
513 		ldmxcsr(MXCSR_DEFAULT);
514 
515 	if (unlikely(kfpu_mask & KFPU_387))
516 		asm volatile ("fninit");
517 }
518 EXPORT_SYMBOL_GPL(kernel_fpu_begin_mask);
519 
kernel_fpu_end(void)520 void kernel_fpu_end(void)
521 {
522 	/* Toggle kernel_fpu_allowed back to true: */
523 	WARN_ON_FPU(this_cpu_read(kernel_fpu_allowed));
524 	this_cpu_write(kernel_fpu_allowed, true);
525 
526 	if (!irqs_disabled())
527 		fpregs_unlock();
528 }
529 EXPORT_SYMBOL_GPL(kernel_fpu_end);
530 
531 /*
532  * Sync the FPU register state to current's memory register state when the
533  * current task owns the FPU. The hardware register state is preserved.
534  */
fpu_sync_fpstate(struct fpu * fpu)535 void fpu_sync_fpstate(struct fpu *fpu)
536 {
537 	WARN_ON_FPU(fpu != x86_task_fpu(current));
538 
539 	fpregs_lock();
540 	trace_x86_fpu_before_save(fpu);
541 
542 	if (!test_thread_flag(TIF_NEED_FPU_LOAD))
543 		save_fpregs_to_fpstate(fpu);
544 
545 	trace_x86_fpu_after_save(fpu);
546 	fpregs_unlock();
547 }
548 
init_fpstate_copy_size(void)549 static inline unsigned int init_fpstate_copy_size(void)
550 {
551 	if (!use_xsave())
552 		return fpu_kernel_cfg.default_size;
553 
554 	/* XSAVE(S) just needs the legacy and the xstate header part */
555 	return sizeof(init_fpstate.regs.xsave);
556 }
557 
fpstate_init_fxstate(struct fpstate * fpstate)558 static inline void fpstate_init_fxstate(struct fpstate *fpstate)
559 {
560 	fpstate->regs.fxsave.cwd = 0x37f;
561 	fpstate->regs.fxsave.mxcsr = MXCSR_DEFAULT;
562 }
563 
564 /*
565  * Legacy x87 fpstate state init:
566  */
fpstate_init_fstate(struct fpstate * fpstate)567 static inline void fpstate_init_fstate(struct fpstate *fpstate)
568 {
569 	fpstate->regs.fsave.cwd = 0xffff037fu;
570 	fpstate->regs.fsave.swd = 0xffff0000u;
571 	fpstate->regs.fsave.twd = 0xffffffffu;
572 	fpstate->regs.fsave.fos = 0xffff0000u;
573 }
574 
575 /*
576  * Used in two places:
577  * 1) Early boot to setup init_fpstate for non XSAVE systems
578  * 2) fpu_alloc_guest_fpstate() which is invoked from KVM
579  */
fpstate_init_user(struct fpstate * fpstate)580 void fpstate_init_user(struct fpstate *fpstate)
581 {
582 	xstate_init_xcomp_bv(&fpstate->regs.xsave, fpstate->xfeatures);
583 
584 	if (cpu_feature_enabled(X86_FEATURE_FXSR))
585 		fpstate_init_fxstate(fpstate);
586 	else
587 		fpstate_init_fstate(fpstate);
588 }
589 
__fpstate_reset(struct fpstate * fpstate)590 static void __fpstate_reset(struct fpstate *fpstate)
591 {
592 	/*
593 	 * Supervisor features (and thus sizes) may diverge between guest
594 	 * FPUs and host FPUs, as some supervisor features are supported
595 	 * for guests despite not being utilized by the host. User
596 	 * features and sizes are always identical, which allows for
597 	 * common guest and userspace ABI.
598 	 *
599 	 * For the host, set XFD to the kernel's desired initialization
600 	 * value. For guests, set XFD to its architectural RESET value.
601 	 */
602 	if (fpstate->is_guest) {
603 		fpstate->size		= guest_default_cfg.size;
604 		fpstate->xfeatures	= guest_default_cfg.features;
605 		fpstate->xfd		= 0;
606 	} else {
607 		fpstate->size		= fpu_kernel_cfg.default_size;
608 		fpstate->xfeatures	= fpu_kernel_cfg.default_features;
609 		fpstate->xfd		= init_fpstate.xfd;
610 	}
611 
612 	fpstate->user_size	= fpu_user_cfg.default_size;
613 	fpstate->user_xfeatures	= fpu_user_cfg.default_features;
614 }
615 
fpstate_reset(struct fpu * fpu)616 void fpstate_reset(struct fpu *fpu)
617 {
618 	/* Set the fpstate pointer to the default fpstate */
619 	fpu->fpstate = &fpu->__fpstate;
620 	__fpstate_reset(fpu->fpstate);
621 
622 	/* Initialize the permission related info in fpu */
623 	fpu->perm.__state_perm		= fpu_kernel_cfg.default_features;
624 	fpu->perm.__state_size		= fpu_kernel_cfg.default_size;
625 	fpu->perm.__user_state_size	= fpu_user_cfg.default_size;
626 
627 	fpu->guest_perm.__state_perm	= guest_default_cfg.features;
628 	fpu->guest_perm.__state_size	= guest_default_cfg.size;
629 	/*
630 	 * User features and sizes are always identical between host and
631 	 * guest FPUs, which allows for common guest and userspace ABI.
632 	 */
633 	fpu->guest_perm.__user_state_size = fpu_user_cfg.default_size;
634 }
635 
fpu_inherit_perms(struct fpu * dst_fpu)636 static inline void fpu_inherit_perms(struct fpu *dst_fpu)
637 {
638 	if (fpu_state_size_dynamic()) {
639 		struct fpu *src_fpu = x86_task_fpu(current->group_leader);
640 
641 		spin_lock_irq(&current->sighand->siglock);
642 		/* Fork also inherits the permissions of the parent */
643 		dst_fpu->perm = src_fpu->perm;
644 		dst_fpu->guest_perm = src_fpu->guest_perm;
645 		spin_unlock_irq(&current->sighand->siglock);
646 	}
647 }
648 
649 /* A passed ssp of zero will not cause any update */
update_fpu_shstk(struct task_struct * dst,unsigned long ssp)650 static int update_fpu_shstk(struct task_struct *dst, unsigned long ssp)
651 {
652 #ifdef CONFIG_X86_USER_SHADOW_STACK
653 	struct cet_user_state *xstate;
654 
655 	/* If ssp update is not needed. */
656 	if (!ssp)
657 		return 0;
658 
659 	xstate = get_xsave_addr(&x86_task_fpu(dst)->fpstate->regs.xsave,
660 				XFEATURE_CET_USER);
661 
662 	/*
663 	 * If there is a non-zero ssp, then 'dst' must be configured with a shadow
664 	 * stack and the fpu state should be up to date since it was just copied
665 	 * from the parent in fpu_clone(). So there must be a valid non-init CET
666 	 * state location in the buffer.
667 	 */
668 	if (WARN_ON_ONCE(!xstate))
669 		return 1;
670 
671 	xstate->user_ssp = (u64)ssp;
672 #endif
673 	return 0;
674 }
675 
676 /* Clone current's FPU state on fork */
fpu_clone(struct task_struct * dst,u64 clone_flags,bool minimal,unsigned long ssp)677 int fpu_clone(struct task_struct *dst, u64 clone_flags, bool minimal,
678 	      unsigned long ssp)
679 {
680 	/*
681 	 * We allocate the new FPU structure right after the end of the task struct.
682 	 * task allocation size already took this into account.
683 	 *
684 	 * This is safe because task_struct size is a multiple of cacheline size,
685 	 * thus x86_task_fpu() will always be cacheline aligned as well.
686 	 */
687 	struct fpu *dst_fpu = (void *)dst + sizeof(*dst);
688 
689 	BUILD_BUG_ON(sizeof(*dst) % SMP_CACHE_BYTES != 0);
690 
691 	/* The new task's FPU state cannot be valid in the hardware. */
692 	dst_fpu->last_cpu = -1;
693 
694 	fpstate_reset(dst_fpu);
695 
696 	/*
697 	 * Enforce reload for user space tasks and prevent kernel threads
698 	 * from trying to save the FPU registers on context switch.
699 	 */
700 	set_tsk_thread_flag(dst, TIF_NEED_FPU_LOAD);
701 
702 	/*
703 	 * No FPU state inheritance for kernel threads and IO
704 	 * worker threads.
705 	 */
706 	if (minimal) {
707 		/* Clear out the minimal state */
708 		memcpy(&dst_fpu->fpstate->regs, &init_fpstate.regs,
709 		       init_fpstate_copy_size());
710 		return 0;
711 	}
712 
713 	/*
714 	 * If a new feature is added, ensure all dynamic features are
715 	 * caller-saved from here!
716 	 */
717 	BUILD_BUG_ON(XFEATURE_MASK_USER_DYNAMIC != XFEATURE_MASK_XTILE_DATA);
718 
719 	/*
720 	 * Save the default portion of the current FPU state into the
721 	 * clone. Assume all dynamic features to be defined as caller-
722 	 * saved, which enables skipping both the expansion of fpstate
723 	 * and the copying of any dynamic state.
724 	 *
725 	 * Do not use memcpy() when TIF_NEED_FPU_LOAD is set because
726 	 * copying is not valid when current uses non-default states.
727 	 */
728 	fpregs_lock();
729 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
730 		fpregs_restore_userregs();
731 	save_fpregs_to_fpstate(dst_fpu);
732 	fpregs_unlock();
733 	if (!(clone_flags & CLONE_THREAD))
734 		fpu_inherit_perms(dst_fpu);
735 
736 	/*
737 	 * Children never inherit PASID state.
738 	 * Force it to have its init value:
739 	 */
740 	if (use_xsave())
741 		dst_fpu->fpstate->regs.xsave.header.xfeatures &= ~XFEATURE_MASK_PASID;
742 
743 	/*
744 	 * Update shadow stack pointer, in case it changed during clone.
745 	 */
746 	if (update_fpu_shstk(dst, ssp))
747 		return 1;
748 
749 	trace_x86_fpu_copy_dst(dst_fpu);
750 
751 	return 0;
752 }
753 
754 /*
755  * While struct fpu is no longer part of struct thread_struct, it is still
756  * allocated after struct task_struct in the "task_struct" kmem cache. But
757  * since FPU is expected to be part of struct thread_struct, we have to
758  * adjust for it here.
759  */
fpu_thread_struct_whitelist(unsigned long * offset,unsigned long * size)760 void fpu_thread_struct_whitelist(unsigned long *offset, unsigned long *size)
761 {
762 	/* The allocation follows struct task_struct. */
763 	*offset = sizeof(struct task_struct) - offsetof(struct task_struct, thread);
764 	*offset += offsetof(struct fpu, __fpstate.regs);
765 	*size = fpu_kernel_cfg.default_size;
766 }
767 
768 /*
769  * Drops current FPU state: deactivates the fpregs and
770  * the fpstate. NOTE: it still leaves previous contents
771  * in the fpregs in the eager-FPU case.
772  *
773  * This function can be used in cases where we know that
774  * a state-restore is coming: either an explicit one,
775  * or a reschedule.
776  */
fpu__drop(struct task_struct * tsk)777 void fpu__drop(struct task_struct *tsk)
778 {
779 	struct fpu *fpu;
780 
781 	if (test_tsk_thread_flag(tsk, TIF_NEED_FPU_LOAD))
782 		return;
783 
784 	fpu = x86_task_fpu(tsk);
785 
786 	preempt_disable();
787 
788 	if (fpu == x86_task_fpu(current)) {
789 		/* Ignore delayed exceptions from user space */
790 		asm volatile("1: fwait\n"
791 			     "2:\n"
792 			     _ASM_EXTABLE(1b, 2b));
793 		fpregs_deactivate(fpu);
794 	}
795 
796 	trace_x86_fpu_dropped(fpu);
797 
798 	preempt_enable();
799 }
800 
801 /*
802  * Clear FPU registers by setting them up from the init fpstate.
803  * Caller must do fpregs_[un]lock() around it.
804  */
restore_fpregs_from_init_fpstate(u64 features_mask)805 static inline void restore_fpregs_from_init_fpstate(u64 features_mask)
806 {
807 	if (use_xsave())
808 		os_xrstor(&init_fpstate, features_mask);
809 	else if (use_fxsr())
810 		fxrstor(&init_fpstate.regs.fxsave);
811 	else
812 		frstor(&init_fpstate.regs.fsave);
813 
814 	pkru_write_default();
815 }
816 
817 /*
818  * Reset current->fpu memory state to the init values.
819  */
fpu_reset_fpstate_regs(void)820 static void fpu_reset_fpstate_regs(void)
821 {
822 	struct fpu *fpu = x86_task_fpu(current);
823 
824 	fpregs_lock();
825 	__fpu_invalidate_fpregs_state(fpu);
826 	/*
827 	 * This does not change the actual hardware registers. It just
828 	 * resets the memory image and sets TIF_NEED_FPU_LOAD so a
829 	 * subsequent return to usermode will reload the registers from the
830 	 * task's memory image.
831 	 *
832 	 * Do not use fpstate_init() here. Just copy init_fpstate which has
833 	 * the correct content already except for PKRU.
834 	 *
835 	 * PKRU handling does not rely on the xstate when restoring for
836 	 * user space as PKRU is eagerly written in switch_to() and
837 	 * flush_thread().
838 	 */
839 	memcpy(&fpu->fpstate->regs, &init_fpstate.regs, init_fpstate_copy_size());
840 	set_thread_flag(TIF_NEED_FPU_LOAD);
841 	fpregs_unlock();
842 }
843 
844 /*
845  * Reset current's user FPU states to the init states.  current's
846  * supervisor states, if any, are not modified by this function.  The
847  * caller guarantees that the XSTATE header in memory is intact.
848  */
fpu__clear_user_states(struct fpu * fpu)849 void fpu__clear_user_states(struct fpu *fpu)
850 {
851 	WARN_ON_FPU(fpu != x86_task_fpu(current));
852 
853 	fpregs_lock();
854 
855 	/*
856 	 * Ensure that current's supervisor states are loaded into their
857 	 * corresponding registers.
858 	 */
859 	if (xfeatures_mask_supervisor() &&
860 	    !fpregs_state_valid(fpu, smp_processor_id()))
861 		os_xrstor_supervisor(fpu->fpstate);
862 
863 	/* Ensure XFD state is in sync before reloading XSTATE */
864 	xfd_update_state(fpu->fpstate);
865 
866 	/* Reset user states in registers. */
867 	restore_fpregs_from_init_fpstate(XFEATURE_MASK_USER_RESTORE);
868 
869 	/*
870 	 * Now all FPU registers have their desired values.  Inform the FPU
871 	 * state machine that current's FPU registers are in the hardware
872 	 * registers. The memory image does not need to be updated because
873 	 * any operation relying on it has to save the registers first when
874 	 * current's FPU is marked active.
875 	 */
876 	fpregs_mark_activate();
877 	fpregs_unlock();
878 }
879 
fpu_flush_thread(void)880 void fpu_flush_thread(void)
881 {
882 	fpstate_reset(x86_task_fpu(current));
883 	fpu_reset_fpstate_regs();
884 }
885 /*
886  * Load FPU context before returning to userspace.
887  */
switch_fpu_return(void)888 void switch_fpu_return(void)
889 {
890 	fpregs_restore_userregs();
891 }
892 EXPORT_SYMBOL_FOR_KVM(switch_fpu_return);
893 
fpregs_lock_and_load(void)894 void fpregs_lock_and_load(void)
895 {
896 	/*
897 	 * fpregs_lock() only disables preemption (mostly). So modifying state
898 	 * in an interrupt could screw up some in progress fpregs operation.
899 	 * Warn about it.
900 	 */
901 	WARN_ON_ONCE(!irq_fpu_usable());
902 	WARN_ON_ONCE(current->flags & PF_KTHREAD);
903 
904 	fpregs_lock();
905 
906 	fpregs_assert_state_consistent();
907 
908 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
909 		fpregs_restore_userregs();
910 }
911 
912 #ifdef CONFIG_X86_DEBUG_FPU
913 /*
914  * If current FPU state according to its tracking (loaded FPU context on this
915  * CPU) is not valid then we must have TIF_NEED_FPU_LOAD set so the context is
916  * loaded on return to userland.
917  */
fpregs_assert_state_consistent(void)918 void fpregs_assert_state_consistent(void)
919 {
920 	struct fpu *fpu = x86_task_fpu(current);
921 
922 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
923 		return;
924 
925 	WARN_ON_FPU(!fpregs_state_valid(fpu, smp_processor_id()));
926 }
927 EXPORT_SYMBOL_FOR_KVM(fpregs_assert_state_consistent);
928 #endif
929 
fpregs_mark_activate(void)930 void fpregs_mark_activate(void)
931 {
932 	struct fpu *fpu = x86_task_fpu(current);
933 
934 	fpregs_activate(fpu);
935 	fpu->last_cpu = smp_processor_id();
936 	clear_thread_flag(TIF_NEED_FPU_LOAD);
937 }
938 
939 /*
940  * x87 math exception handling:
941  */
942 
fpu__exception_code(struct fpu * fpu,int trap_nr)943 int fpu__exception_code(struct fpu *fpu, int trap_nr)
944 {
945 	int err;
946 
947 	if (trap_nr == X86_TRAP_MF) {
948 		unsigned short cwd, swd;
949 		/*
950 		 * (~cwd & swd) will mask out exceptions that are not set to unmasked
951 		 * status.  0x3f is the exception bits in these regs, 0x200 is the
952 		 * C1 reg you need in case of a stack fault, 0x040 is the stack
953 		 * fault bit.  We should only be taking one exception at a time,
954 		 * so if this combination doesn't produce any single exception,
955 		 * then we have a bad program that isn't synchronizing its FPU usage
956 		 * and it will suffer the consequences since we won't be able to
957 		 * fully reproduce the context of the exception.
958 		 */
959 		if (boot_cpu_has(X86_FEATURE_FXSR)) {
960 			cwd = fpu->fpstate->regs.fxsave.cwd;
961 			swd = fpu->fpstate->regs.fxsave.swd;
962 		} else {
963 			cwd = (unsigned short)fpu->fpstate->regs.fsave.cwd;
964 			swd = (unsigned short)fpu->fpstate->regs.fsave.swd;
965 		}
966 
967 		err = swd & ~cwd;
968 	} else {
969 		/*
970 		 * The SIMD FPU exceptions are handled a little differently, as there
971 		 * is only a single status/control register.  Thus, to determine which
972 		 * unmasked exception was caught we must mask the exception mask bits
973 		 * at 0x1f80, and then use these to mask the exception bits at 0x3f.
974 		 */
975 		unsigned short mxcsr = MXCSR_DEFAULT;
976 
977 		if (boot_cpu_has(X86_FEATURE_XMM))
978 			mxcsr = fpu->fpstate->regs.fxsave.mxcsr;
979 
980 		err = ~(mxcsr >> 7) & mxcsr;
981 	}
982 
983 	if (err & 0x001) {	/* Invalid op */
984 		/*
985 		 * swd & 0x240 == 0x040: Stack Underflow
986 		 * swd & 0x240 == 0x240: Stack Overflow
987 		 * User must clear the SF bit (0x40) if set
988 		 */
989 		return FPE_FLTINV;
990 	} else if (err & 0x004) { /* Divide by Zero */
991 		return FPE_FLTDIV;
992 	} else if (err & 0x008) { /* Overflow */
993 		return FPE_FLTOVF;
994 	} else if (err & 0x012) { /* Denormal, Underflow */
995 		return FPE_FLTUND;
996 	} else if (err & 0x020) { /* Precision */
997 		return FPE_FLTRES;
998 	}
999 
1000 	/*
1001 	 * If we're using IRQ 13, or supposedly even some trap
1002 	 * X86_TRAP_MF implementations, it's possible
1003 	 * we get a spurious trap, which is not an error.
1004 	 */
1005 	return 0;
1006 }
1007 
1008 /*
1009  * Initialize register state that may prevent from entering low-power idle.
1010  * This function will be invoked from the cpuidle driver only when needed.
1011  */
fpu_idle_fpregs(void)1012 noinstr void fpu_idle_fpregs(void)
1013 {
1014 	/* Note: AMX_TILE being enabled implies XGETBV1 support */
1015 	if (cpu_feature_enabled(X86_FEATURE_AMX_TILE) &&
1016 	    (xfeatures_in_use() & XFEATURE_MASK_XTILE)) {
1017 		tile_release();
1018 		__this_cpu_write(fpu_fpregs_owner_ctx, NULL);
1019 	}
1020 }
1021