core.c 25 KB

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