blob: 330841bad6167be98eb1b2a6dfd3dda0580f178e [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001/* SPDX-License-Identifier: GPL-2.0 */
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 * x86-64 work by Andi Kleen 2002
9 */
10
11#ifndef _ASM_X86_FPU_INTERNAL_H
12#define _ASM_X86_FPU_INTERNAL_H
13
14#include <linux/compat.h>
15#include <linux/sched.h>
16#include <linux/slab.h>
17#include <linux/mm.h>
18
19#include <asm/user.h>
20#include <asm/fpu/api.h>
21#include <asm/fpu/xstate.h>
22#include <asm/cpufeature.h>
23#include <asm/trace/fpu.h>
24
25/*
26 * High level FPU state handling functions:
27 */
28extern void fpu__prepare_read(struct fpu *fpu);
29extern void fpu__prepare_write(struct fpu *fpu);
30extern void fpu__save(struct fpu *fpu);
31extern int fpu__restore_sig(void __user *buf, int ia32_frame);
32extern void fpu__drop(struct fpu *fpu);
33extern int fpu__copy(struct task_struct *dst, struct task_struct *src);
34extern void fpu__clear(struct fpu *fpu);
35extern int fpu__exception_code(struct fpu *fpu, int trap_nr);
36extern int dump_fpu(struct pt_regs *ptregs, struct user_i387_struct *fpstate);
37
38/*
39 * Boot time FPU initialization functions:
40 */
41extern void fpu__init_cpu(void);
42extern void fpu__init_system_xstate(void);
43extern void fpu__init_cpu_xstate(void);
44extern void fpu__init_system(void);
45extern void fpu__init_check_bugs(void);
46extern void fpu__resume_cpu(void);
47extern u64 fpu__get_supported_xfeatures_mask(void);
48
49/*
50 * Debugging facility:
51 */
52#ifdef CONFIG_X86_DEBUG_FPU
53# define WARN_ON_FPU(x) WARN_ON_ONCE(x)
54#else
55# define WARN_ON_FPU(x) ({ (void)(x); 0; })
56#endif
57
58/*
59 * FPU related CPU feature flag helper routines:
60 */
61static __always_inline __pure bool use_xsaveopt(void)
62{
63 return static_cpu_has(X86_FEATURE_XSAVEOPT);
64}
65
66static __always_inline __pure bool use_xsave(void)
67{
68 return static_cpu_has(X86_FEATURE_XSAVE);
69}
70
71static __always_inline __pure bool use_fxsr(void)
72{
73 return static_cpu_has(X86_FEATURE_FXSR);
74}
75
76/*
77 * fpstate handling functions:
78 */
79
80extern union fpregs_state init_fpstate;
81
82extern void fpstate_init(union fpregs_state *state);
83#ifdef CONFIG_MATH_EMULATION
84extern void fpstate_init_soft(struct swregs_state *soft);
85#else
86static inline void fpstate_init_soft(struct swregs_state *soft) {}
87#endif
88
89static inline void fpstate_init_xstate(struct xregs_state *xsave)
90{
91 /*
92 * XRSTORS requires these bits set in xcomp_bv, or it will
93 * trigger #GP:
94 */
95 xsave->header.xcomp_bv = XCOMP_BV_COMPACTED_FORMAT | xfeatures_mask;
96}
97
98static inline void fpstate_init_fxstate(struct fxregs_state *fx)
99{
100 fx->cwd = 0x37f;
101 fx->mxcsr = MXCSR_DEFAULT;
102}
103extern void fpstate_sanitize_xstate(struct fpu *fpu);
104
105/* Returns 0 or the negated trap number, which results in -EFAULT for #PF */
106#define user_insn(insn, output, input...) \
107({ \
108 int err; \
109 \
110 might_fault(); \
111 \
112 asm volatile(ASM_STAC "\n" \
113 "1: " #insn "\n" \
114 "2: " ASM_CLAC "\n" \
115 ".section .fixup,\"ax\"\n" \
116 "3: negl %%eax\n" \
117 " jmp 2b\n" \
118 ".previous\n" \
119 _ASM_EXTABLE_FAULT(1b, 3b) \
120 : [err] "=a" (err), output \
121 : "0"(0), input); \
122 err; \
123})
124
125#define kernel_insn_err(insn, output, input...) \
126({ \
127 int err; \
128 asm volatile("1:" #insn "\n\t" \
129 "2:\n" \
130 ".section .fixup,\"ax\"\n" \
131 "3: movl $-1,%[err]\n" \
132 " jmp 2b\n" \
133 ".previous\n" \
134 _ASM_EXTABLE(1b, 3b) \
135 : [err] "=r" (err), output \
136 : "0"(0), input); \
137 err; \
138})
139
140#define kernel_insn(insn, output, input...) \
141 asm volatile("1:" #insn "\n\t" \
142 "2:\n" \
143 _ASM_EXTABLE_HANDLE(1b, 2b, ex_handler_fprestore) \
144 : output : input)
145
146static inline int copy_fregs_to_user(struct fregs_state __user *fx)
147{
148 return user_insn(fnsave %[fx]; fwait, [fx] "=m" (*fx), "m" (*fx));
149}
150
151static inline int copy_fxregs_to_user(struct fxregs_state __user *fx)
152{
153 if (IS_ENABLED(CONFIG_X86_32))
154 return user_insn(fxsave %[fx], [fx] "=m" (*fx), "m" (*fx));
155 else
156 return user_insn(fxsaveq %[fx], [fx] "=m" (*fx), "m" (*fx));
157
158}
159
160static inline void copy_kernel_to_fxregs(struct fxregs_state *fx)
161{
162 if (IS_ENABLED(CONFIG_X86_32))
163 kernel_insn(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
164 else
165 kernel_insn(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
166}
167
168static inline int copy_kernel_to_fxregs_err(struct fxregs_state *fx)
169{
170 if (IS_ENABLED(CONFIG_X86_32))
171 return kernel_insn_err(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
172 else
173 return kernel_insn_err(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
174}
175
176static inline int copy_user_to_fxregs(struct fxregs_state __user *fx)
177{
178 if (IS_ENABLED(CONFIG_X86_32))
179 return user_insn(fxrstor %[fx], "=m" (*fx), [fx] "m" (*fx));
180 else
181 return user_insn(fxrstorq %[fx], "=m" (*fx), [fx] "m" (*fx));
182}
183
184static inline void copy_kernel_to_fregs(struct fregs_state *fx)
185{
186 kernel_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
187}
188
189static inline int copy_kernel_to_fregs_err(struct fregs_state *fx)
190{
191 return kernel_insn_err(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
192}
193
194static inline int copy_user_to_fregs(struct fregs_state __user *fx)
195{
196 return user_insn(frstor %[fx], "=m" (*fx), [fx] "m" (*fx));
197}
198
199static inline void copy_fxregs_to_kernel(struct fpu *fpu)
200{
201 if (IS_ENABLED(CONFIG_X86_32))
202 asm volatile( "fxsave %[fx]" : [fx] "=m" (fpu->state.fxsave));
203 else
204 asm volatile("fxsaveq %[fx]" : [fx] "=m" (fpu->state.fxsave));
205}
206
207static inline void fxsave(struct fxregs_state *fx)
208{
209 if (IS_ENABLED(CONFIG_X86_32))
210 asm volatile( "fxsave %[fx]" : [fx] "=m" (*fx));
211 else
212 asm volatile("fxsaveq %[fx]" : [fx] "=m" (*fx));
213}
214
215/* These macros all use (%edi)/(%rdi) as the single memory argument. */
216#define XSAVE ".byte " REX_PREFIX "0x0f,0xae,0x27"
217#define XSAVEOPT ".byte " REX_PREFIX "0x0f,0xae,0x37"
218#define XSAVES ".byte " REX_PREFIX "0x0f,0xc7,0x2f"
219#define XRSTOR ".byte " REX_PREFIX "0x0f,0xae,0x2f"
220#define XRSTORS ".byte " REX_PREFIX "0x0f,0xc7,0x1f"
221
222/*
223 * After this @err contains 0 on success or the negated trap number when
224 * the operation raises an exception. For faults this results in -EFAULT.
225 */
226#define XSTATE_OP(op, st, lmask, hmask, err) \
227 asm volatile("1:" op "\n\t" \
228 "xor %[err], %[err]\n" \
229 "2:\n\t" \
230 ".pushsection .fixup,\"ax\"\n\t" \
231 "3: negl %%eax\n\t" \
232 "jmp 2b\n\t" \
233 ".popsection\n\t" \
234 _ASM_EXTABLE_FAULT(1b, 3b) \
235 : [err] "=a" (err) \
236 : "D" (st), "m" (*st), "a" (lmask), "d" (hmask) \
237 : "memory")
238
239/*
240 * If XSAVES is enabled, it replaces XSAVEOPT because it supports a compact
241 * format and supervisor states in addition to modified optimization in
242 * XSAVEOPT.
243 *
244 * Otherwise, if XSAVEOPT is enabled, XSAVEOPT replaces XSAVE because XSAVEOPT
245 * supports modified optimization which is not supported by XSAVE.
246 *
247 * We use XSAVE as a fallback.
248 *
249 * The 661 label is defined in the ALTERNATIVE* macros as the address of the
250 * original instruction which gets replaced. We need to use it here as the
251 * address of the instruction where we might get an exception at.
252 */
253#define XSTATE_XSAVE(st, lmask, hmask, err) \
254 asm volatile(ALTERNATIVE_2(XSAVE, \
255 XSAVEOPT, X86_FEATURE_XSAVEOPT, \
256 XSAVES, X86_FEATURE_XSAVES) \
257 "\n" \
258 "xor %[err], %[err]\n" \
259 "3:\n" \
260 ".pushsection .fixup,\"ax\"\n" \
261 "4: movl $-2, %[err]\n" \
262 "jmp 3b\n" \
263 ".popsection\n" \
264 _ASM_EXTABLE(661b, 4b) \
265 : [err] "=r" (err) \
266 : "D" (st), "m" (*st), "a" (lmask), "d" (hmask) \
267 : "memory")
268
269/*
270 * Use XRSTORS to restore context if it is enabled. XRSTORS supports compact
271 * XSAVE area format.
272 */
273#define XSTATE_XRESTORE(st, lmask, hmask) \
274 asm volatile(ALTERNATIVE(XRSTOR, \
275 XRSTORS, X86_FEATURE_XSAVES) \
276 "\n" \
277 "3:\n" \
278 _ASM_EXTABLE_HANDLE(661b, 3b, ex_handler_fprestore)\
279 : \
280 : "D" (st), "m" (*st), "a" (lmask), "d" (hmask) \
281 : "memory")
282
283/*
284 * This function is called only during boot time when x86 caps are not set
285 * up and alternative can not be used yet.
286 */
287static inline void copy_kernel_to_xregs_booting(struct xregs_state *xstate)
288{
289 u64 mask = -1;
290 u32 lmask = mask;
291 u32 hmask = mask >> 32;
292 int err;
293
294 WARN_ON(system_state != SYSTEM_BOOTING);
295
296 if (boot_cpu_has(X86_FEATURE_XSAVES))
297 XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
298 else
299 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
300
301 /*
302 * We should never fault when copying from a kernel buffer, and the FPU
303 * state we set at boot time should be valid.
304 */
305 WARN_ON_FPU(err);
306}
307
308/*
309 * Save processor xstate to xsave area.
310 */
311static inline void copy_xregs_to_kernel(struct xregs_state *xstate)
312{
313 u64 mask = -1;
314 u32 lmask = mask;
315 u32 hmask = mask >> 32;
316 int err;
317
318 WARN_ON_FPU(!alternatives_patched);
319
320 XSTATE_XSAVE(xstate, lmask, hmask, err);
321
322 /* We should never fault when copying to a kernel buffer: */
323 WARN_ON_FPU(err);
324}
325
326/*
327 * Restore processor xstate from xsave area.
328 */
329static inline void copy_kernel_to_xregs(struct xregs_state *xstate, u64 mask)
330{
331 u32 lmask = mask;
332 u32 hmask = mask >> 32;
333
334 XSTATE_XRESTORE(xstate, lmask, hmask);
335}
336
337/*
338 * Save xstate to user space xsave area.
339 *
340 * We don't use modified optimization because xrstor/xrstors might track
341 * a different application.
342 *
343 * We don't use compacted format xsave area for
344 * backward compatibility for old applications which don't understand
345 * compacted format of xsave area.
346 */
347static inline int copy_xregs_to_user(struct xregs_state __user *buf)
348{
349 int err;
350
351 /*
352 * Clear the xsave header first, so that reserved fields are
353 * initialized to zero.
354 */
355 err = __clear_user(&buf->header, sizeof(buf->header));
356 if (unlikely(err))
357 return -EFAULT;
358
359 stac();
360 XSTATE_OP(XSAVE, buf, -1, -1, err);
361 clac();
362
363 return err;
364}
365
366/*
367 * Restore xstate from user space xsave area.
368 */
369static inline int copy_user_to_xregs(struct xregs_state __user *buf, u64 mask)
370{
371 struct xregs_state *xstate = ((__force struct xregs_state *)buf);
372 u32 lmask = mask;
373 u32 hmask = mask >> 32;
374 int err;
375
376 stac();
377 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
378 clac();
379
380 return err;
381}
382
383/*
384 * Restore xstate from kernel space xsave area, return an error code instead of
385 * an exception.
386 */
387static inline int copy_kernel_to_xregs_err(struct xregs_state *xstate, u64 mask)
388{
389 u32 lmask = mask;
390 u32 hmask = mask >> 32;
391 int err;
392
393 XSTATE_OP(XRSTOR, xstate, lmask, hmask, err);
394
395 return err;
396}
397
398/*
399 * These must be called with preempt disabled. Returns
400 * 'true' if the FPU state is still intact and we can
401 * keep registers active.
402 *
403 * The legacy FNSAVE instruction cleared all FPU state
404 * unconditionally, so registers are essentially destroyed.
405 * Modern FPU state can be kept in registers, if there are
406 * no pending FP exceptions.
407 */
408static inline int copy_fpregs_to_fpstate(struct fpu *fpu)
409{
410 if (likely(use_xsave())) {
411 copy_xregs_to_kernel(&fpu->state.xsave);
412
413 /*
414 * AVX512 state is tracked here because its use is
415 * known to slow the max clock speed of the core.
416 */
417 if (fpu->state.xsave.header.xfeatures & XFEATURE_MASK_AVX512)
418 fpu->avx512_timestamp = jiffies;
419 return 1;
420 }
421
422 if (likely(use_fxsr())) {
423 copy_fxregs_to_kernel(fpu);
424 return 1;
425 }
426
427 /*
428 * Legacy FPU register saving, FNSAVE always clears FPU registers,
429 * so we have to mark them inactive:
430 */
431 asm volatile("fnsave %[fp]; fwait" : [fp] "=m" (fpu->state.fsave));
432
433 return 0;
434}
435
436static inline void __copy_kernel_to_fpregs(union fpregs_state *fpstate, u64 mask)
437{
438 if (use_xsave()) {
439 copy_kernel_to_xregs(&fpstate->xsave, mask);
440 } else {
441 if (use_fxsr())
442 copy_kernel_to_fxregs(&fpstate->fxsave);
443 else
444 copy_kernel_to_fregs(&fpstate->fsave);
445 }
446}
447
448static inline void copy_kernel_to_fpregs(union fpregs_state *fpstate)
449{
450 /*
451 * AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception is
452 * pending. Clear the x87 state here by setting it to fixed values.
453 * "m" is a random variable that should be in L1.
454 */
455 if (unlikely(static_cpu_has_bug(X86_BUG_FXSAVE_LEAK))) {
456 asm volatile(
457 "fnclex\n\t"
458 "emms\n\t"
459 "fildl %P[addr]" /* set F?P to defined value */
460 : : [addr] "m" (fpstate));
461 }
462
463 __copy_kernel_to_fpregs(fpstate, -1);
464}
465
466extern int copy_fpstate_to_sigframe(void __user *buf, void __user *fp, int size);
467
468/*
469 * FPU context switch related helper methods:
470 */
471
472DECLARE_PER_CPU(struct fpu *, fpu_fpregs_owner_ctx);
473
474/*
475 * The in-register FPU state for an FPU context on a CPU is assumed to be
476 * valid if the fpu->last_cpu matches the CPU, and the fpu_fpregs_owner_ctx
477 * matches the FPU.
478 *
479 * If the FPU register state is valid, the kernel can skip restoring the
480 * FPU state from memory.
481 *
482 * Any code that clobbers the FPU registers or updates the in-memory
483 * FPU state for a task MUST let the rest of the kernel know that the
484 * FPU registers are no longer valid for this task.
485 *
486 * Either one of these invalidation functions is enough. Invalidate
487 * a resource you control: CPU if using the CPU for something else
488 * (with preemption disabled), FPU for the current task, or a task that
489 * is prevented from running by the current task.
490 */
491static inline void __cpu_invalidate_fpregs_state(void)
492{
493 __this_cpu_write(fpu_fpregs_owner_ctx, NULL);
494}
495
496static inline void __fpu_invalidate_fpregs_state(struct fpu *fpu)
497{
498 fpu->last_cpu = -1;
499}
500
501static inline int fpregs_state_valid(struct fpu *fpu, unsigned int cpu)
502{
503 return fpu == this_cpu_read(fpu_fpregs_owner_ctx) && cpu == fpu->last_cpu;
504}
505
506/*
507 * These generally need preemption protection to work,
508 * do try to avoid using these on their own:
509 */
510static inline void fpregs_deactivate(struct fpu *fpu)
511{
512 this_cpu_write(fpu_fpregs_owner_ctx, NULL);
513 trace_x86_fpu_regs_deactivated(fpu);
514}
515
516static inline void fpregs_activate(struct fpu *fpu)
517{
518 this_cpu_write(fpu_fpregs_owner_ctx, fpu);
519 trace_x86_fpu_regs_activated(fpu);
520}
521
522/*
523 * Internal helper, do not use directly. Use switch_fpu_return() instead.
524 */
525static inline void __fpregs_load_activate(void)
526{
527 struct fpu *fpu = &current->thread.fpu;
528 int cpu = smp_processor_id();
529
530 if (WARN_ON_ONCE(current->flags & PF_KTHREAD))
531 return;
532
533 if (!fpregs_state_valid(fpu, cpu)) {
534 copy_kernel_to_fpregs(&fpu->state);
535 fpregs_activate(fpu);
536 fpu->last_cpu = cpu;
537 }
538 clear_thread_flag(TIF_NEED_FPU_LOAD);
539}
540
541/*
542 * FPU state switching for scheduling.
543 *
544 * This is a two-stage process:
545 *
546 * - switch_fpu_prepare() saves the old state.
547 * This is done within the context of the old process.
548 *
549 * - switch_fpu_finish() sets TIF_NEED_FPU_LOAD; the floating point state
550 * will get loaded on return to userspace, or when the kernel needs it.
551 *
552 * If TIF_NEED_FPU_LOAD is cleared then the CPU's FPU registers
553 * are saved in the current thread's FPU register state.
554 *
555 * If TIF_NEED_FPU_LOAD is set then CPU's FPU registers may not
556 * hold current()'s FPU registers. It is required to load the
557 * registers before returning to userland or using the content
558 * otherwise.
559 *
560 * The FPU context is only stored/restored for a user task and
561 * PF_KTHREAD is used to distinguish between kernel and user threads.
562 */
563static inline void switch_fpu_prepare(struct task_struct *prev, int cpu)
564{
565 struct fpu *old_fpu = &prev->thread.fpu;
566
567 if (static_cpu_has(X86_FEATURE_FPU) && !(prev->flags & PF_KTHREAD)) {
568 if (!copy_fpregs_to_fpstate(old_fpu))
569 old_fpu->last_cpu = -1;
570 else
571 old_fpu->last_cpu = cpu;
572
573 /* But leave fpu_fpregs_owner_ctx! */
574 trace_x86_fpu_regs_deactivated(old_fpu);
575 }
576}
577
578/*
579 * Misc helper functions:
580 */
581
582/*
583 * Load PKRU from the FPU context if available. Delay loading of the
584 * complete FPU state until the return to userland.
585 */
586static inline void switch_fpu_finish(struct task_struct *next)
587{
588 u32 pkru_val = init_pkru_value;
589 struct pkru_state *pk;
590 struct fpu *next_fpu = &next->thread.fpu;
591
592 if (!static_cpu_has(X86_FEATURE_FPU))
593 return;
594
595 set_thread_flag(TIF_NEED_FPU_LOAD);
596
597 if (!cpu_feature_enabled(X86_FEATURE_OSPKE))
598 return;
599
600 /*
601 * PKRU state is switched eagerly because it needs to be valid before we
602 * return to userland e.g. for a copy_to_user() operation.
603 */
604 if (!(next->flags & PF_KTHREAD)) {
605 /*
606 * If the PKRU bit in xsave.header.xfeatures is not set,
607 * then the PKRU component was in init state, which means
608 * XRSTOR will set PKRU to 0. If the bit is not set then
609 * get_xsave_addr() will return NULL because the PKRU value
610 * in memory is not valid. This means pkru_val has to be
611 * set to 0 and not to init_pkru_value.
612 */
613 pk = get_xsave_addr(&next_fpu->state.xsave, XFEATURE_PKRU);
614 pkru_val = pk ? pk->pkru : 0;
615 }
616 __write_pkru(pkru_val);
617}
618
619/*
620 * MXCSR and XCR definitions:
621 */
622
623static inline void ldmxcsr(u32 mxcsr)
624{
625 asm volatile("ldmxcsr %0" :: "m" (mxcsr));
626}
627
628extern unsigned int mxcsr_feature_mask;
629
630#define XCR_XFEATURE_ENABLED_MASK 0x00000000
631
632static inline u64 xgetbv(u32 index)
633{
634 u32 eax, edx;
635
636 asm volatile(".byte 0x0f,0x01,0xd0" /* xgetbv */
637 : "=a" (eax), "=d" (edx)
638 : "c" (index));
639 return eax + ((u64)edx << 32);
640}
641
642static inline void xsetbv(u32 index, u64 value)
643{
644 u32 eax = value;
645 u32 edx = value >> 32;
646
647 asm volatile(".byte 0x0f,0x01,0xd1" /* xsetbv */
648 : : "a" (eax), "d" (edx), "c" (index));
649}
650
651#endif /* _ASM_X86_FPU_INTERNAL_H */