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