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