x86/fpu: Remove unused get_xsave_field_ptr()
[linux-2.6-microblaze.git] / arch / x86 / kernel / fpu / xstate.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * xsave/xrstor support.
4  *
5  * Author: Suresh Siddha <suresh.b.siddha@intel.com>
6  */
7 #include <linux/compat.h>
8 #include <linux/cpu.h>
9 #include <linux/mman.h>
10 #include <linux/pkeys.h>
11 #include <linux/seq_file.h>
12 #include <linux/proc_fs.h>
13
14 #include <asm/fpu/api.h>
15 #include <asm/fpu/internal.h>
16 #include <asm/fpu/signal.h>
17 #include <asm/fpu/regset.h>
18 #include <asm/fpu/xstate.h>
19
20 #include <asm/tlbflush.h>
21 #include <asm/cpufeature.h>
22
23 /*
24  * Although we spell it out in here, the Processor Trace
25  * xfeature is completely unused.  We use other mechanisms
26  * to save/restore PT state in Linux.
27  */
28 static const char *xfeature_names[] =
29 {
30         "x87 floating point registers"  ,
31         "SSE registers"                 ,
32         "AVX registers"                 ,
33         "MPX bounds registers"          ,
34         "MPX CSR"                       ,
35         "AVX-512 opmask"                ,
36         "AVX-512 Hi256"                 ,
37         "AVX-512 ZMM_Hi256"             ,
38         "Processor Trace (unused)"      ,
39         "Protection Keys User registers",
40         "PASID state",
41         "unknown xstate feature"        ,
42 };
43
44 static short xsave_cpuid_features[] __initdata = {
45         X86_FEATURE_FPU,
46         X86_FEATURE_XMM,
47         X86_FEATURE_AVX,
48         X86_FEATURE_MPX,
49         X86_FEATURE_MPX,
50         X86_FEATURE_AVX512F,
51         X86_FEATURE_AVX512F,
52         X86_FEATURE_AVX512F,
53         X86_FEATURE_INTEL_PT,
54         X86_FEATURE_PKU,
55         X86_FEATURE_ENQCMD,
56 };
57
58 /*
59  * This represents the full set of bits that should ever be set in a kernel
60  * XSAVE buffer, both supervisor and user xstates.
61  */
62 u64 xfeatures_mask_all __ro_after_init;
63
64 static unsigned int xstate_offsets[XFEATURE_MAX] __ro_after_init =
65         { [ 0 ... XFEATURE_MAX - 1] = -1};
66 static unsigned int xstate_sizes[XFEATURE_MAX] __ro_after_init =
67         { [ 0 ... XFEATURE_MAX - 1] = -1};
68 static unsigned int xstate_comp_offsets[XFEATURE_MAX] __ro_after_init =
69         { [ 0 ... XFEATURE_MAX - 1] = -1};
70 static unsigned int xstate_supervisor_only_offsets[XFEATURE_MAX] __ro_after_init =
71         { [ 0 ... XFEATURE_MAX - 1] = -1};
72
73 /*
74  * The XSAVE area of kernel can be in standard or compacted format;
75  * it is always in standard format for user mode. This is the user
76  * mode standard format size used for signal and ptrace frames.
77  */
78 unsigned int fpu_user_xstate_size __ro_after_init;
79
80 /*
81  * Return whether the system supports a given xfeature.
82  *
83  * Also return the name of the (most advanced) feature that the caller requested:
84  */
85 int cpu_has_xfeatures(u64 xfeatures_needed, const char **feature_name)
86 {
87         u64 xfeatures_missing = xfeatures_needed & ~xfeatures_mask_all;
88
89         if (unlikely(feature_name)) {
90                 long xfeature_idx, max_idx;
91                 u64 xfeatures_print;
92                 /*
93                  * So we use FLS here to be able to print the most advanced
94                  * feature that was requested but is missing. So if a driver
95                  * asks about "XFEATURE_MASK_SSE | XFEATURE_MASK_YMM" we'll print the
96                  * missing AVX feature - this is the most informative message
97                  * to users:
98                  */
99                 if (xfeatures_missing)
100                         xfeatures_print = xfeatures_missing;
101                 else
102                         xfeatures_print = xfeatures_needed;
103
104                 xfeature_idx = fls64(xfeatures_print)-1;
105                 max_idx = ARRAY_SIZE(xfeature_names)-1;
106                 xfeature_idx = min(xfeature_idx, max_idx);
107
108                 *feature_name = xfeature_names[xfeature_idx];
109         }
110
111         if (xfeatures_missing)
112                 return 0;
113
114         return 1;
115 }
116 EXPORT_SYMBOL_GPL(cpu_has_xfeatures);
117
118 static bool xfeature_is_supervisor(int xfeature_nr)
119 {
120         /*
121          * Extended State Enumeration Sub-leaves (EAX = 0DH, ECX = n, n > 1)
122          * returns ECX[0] set to (1) for a supervisor state, and cleared (0)
123          * for a user state.
124          */
125         u32 eax, ebx, ecx, edx;
126
127         cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
128         return ecx & 1;
129 }
130
131 /*
132  * When executing XSAVEOPT (or other optimized XSAVE instructions), if
133  * a processor implementation detects that an FPU state component is still
134  * (or is again) in its initialized state, it may clear the corresponding
135  * bit in the header.xfeatures field, and can skip the writeout of registers
136  * to the corresponding memory layout.
137  *
138  * This means that when the bit is zero, the state component might still contain
139  * some previous - non-initialized register state.
140  *
141  * Before writing xstate information to user-space we sanitize those components,
142  * to always ensure that the memory layout of a feature will be in the init state
143  * if the corresponding header bit is zero. This is to ensure that user-space doesn't
144  * see some stale state in the memory layout during signal handling, debugging etc.
145  */
146 void fpstate_sanitize_xstate(struct fpu *fpu)
147 {
148         struct fxregs_state *fx = &fpu->state.fxsave;
149         int feature_bit;
150         u64 xfeatures;
151
152         if (!use_xsaveopt())
153                 return;
154
155         xfeatures = fpu->state.xsave.header.xfeatures;
156
157         /*
158          * None of the feature bits are in init state. So nothing else
159          * to do for us, as the memory layout is up to date.
160          */
161         if ((xfeatures & xfeatures_mask_all) == xfeatures_mask_all)
162                 return;
163
164         /*
165          * FP is in init state
166          */
167         if (!(xfeatures & XFEATURE_MASK_FP)) {
168                 fx->cwd = 0x37f;
169                 fx->swd = 0;
170                 fx->twd = 0;
171                 fx->fop = 0;
172                 fx->rip = 0;
173                 fx->rdp = 0;
174                 memset(fx->st_space, 0, sizeof(fx->st_space));
175         }
176
177         /*
178          * SSE is in init state
179          */
180         if (!(xfeatures & XFEATURE_MASK_SSE))
181                 memset(fx->xmm_space, 0, sizeof(fx->xmm_space));
182
183         /*
184          * First two features are FPU and SSE, which above we handled
185          * in a special way already:
186          */
187         feature_bit = 0x2;
188         xfeatures = (xfeatures_mask_user() & ~xfeatures) >> 2;
189
190         /*
191          * Update all the remaining memory layouts according to their
192          * standard xstate layout, if their header bit is in the init
193          * state:
194          */
195         while (xfeatures) {
196                 if (xfeatures & 0x1) {
197                         int offset = xstate_comp_offsets[feature_bit];
198                         int size = xstate_sizes[feature_bit];
199
200                         memcpy((void *)fx + offset,
201                                (void *)&init_fpstate.xsave + offset,
202                                size);
203                 }
204
205                 xfeatures >>= 1;
206                 feature_bit++;
207         }
208 }
209
210 /*
211  * Enable the extended processor state save/restore feature.
212  * Called once per CPU onlining.
213  */
214 void fpu__init_cpu_xstate(void)
215 {
216         if (!boot_cpu_has(X86_FEATURE_XSAVE) || !xfeatures_mask_all)
217                 return;
218
219         cr4_set_bits(X86_CR4_OSXSAVE);
220
221         /*
222          * XCR_XFEATURE_ENABLED_MASK (aka. XCR0) sets user features
223          * managed by XSAVE{C, OPT, S} and XRSTOR{S}.  Only XSAVE user
224          * states can be set here.
225          */
226         xsetbv(XCR_XFEATURE_ENABLED_MASK, xfeatures_mask_user());
227
228         /*
229          * MSR_IA32_XSS sets supervisor states managed by XSAVES.
230          */
231         if (boot_cpu_has(X86_FEATURE_XSAVES)) {
232                 wrmsrl(MSR_IA32_XSS, xfeatures_mask_supervisor() |
233                                      xfeatures_mask_dynamic());
234         }
235 }
236
237 static bool xfeature_enabled(enum xfeature xfeature)
238 {
239         return xfeatures_mask_all & BIT_ULL(xfeature);
240 }
241
242 /*
243  * Record the offsets and sizes of various xstates contained
244  * in the XSAVE state memory layout.
245  */
246 static void __init setup_xstate_features(void)
247 {
248         u32 eax, ebx, ecx, edx, i;
249         /* start at the beginning of the "extended state" */
250         unsigned int last_good_offset = offsetof(struct xregs_state,
251                                                  extended_state_area);
252         /*
253          * The FP xstates and SSE xstates are legacy states. They are always
254          * in the fixed offsets in the xsave area in either compacted form
255          * or standard form.
256          */
257         xstate_offsets[XFEATURE_FP]     = 0;
258         xstate_sizes[XFEATURE_FP]       = offsetof(struct fxregs_state,
259                                                    xmm_space);
260
261         xstate_offsets[XFEATURE_SSE]    = xstate_sizes[XFEATURE_FP];
262         xstate_sizes[XFEATURE_SSE]      = sizeof_field(struct fxregs_state,
263                                                        xmm_space);
264
265         for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
266                 if (!xfeature_enabled(i))
267                         continue;
268
269                 cpuid_count(XSTATE_CPUID, i, &eax, &ebx, &ecx, &edx);
270
271                 xstate_sizes[i] = eax;
272
273                 /*
274                  * If an xfeature is supervisor state, the offset in EBX is
275                  * invalid, leave it to -1.
276                  */
277                 if (xfeature_is_supervisor(i))
278                         continue;
279
280                 xstate_offsets[i] = ebx;
281
282                 /*
283                  * In our xstate size checks, we assume that the highest-numbered
284                  * xstate feature has the highest offset in the buffer.  Ensure
285                  * it does.
286                  */
287                 WARN_ONCE(last_good_offset > xstate_offsets[i],
288                           "x86/fpu: misordered xstate at %d\n", last_good_offset);
289
290                 last_good_offset = xstate_offsets[i];
291         }
292 }
293
294 static void __init print_xstate_feature(u64 xstate_mask)
295 {
296         const char *feature_name;
297
298         if (cpu_has_xfeatures(xstate_mask, &feature_name))
299                 pr_info("x86/fpu: Supporting XSAVE feature 0x%03Lx: '%s'\n", xstate_mask, feature_name);
300 }
301
302 /*
303  * Print out all the supported xstate features:
304  */
305 static void __init print_xstate_features(void)
306 {
307         print_xstate_feature(XFEATURE_MASK_FP);
308         print_xstate_feature(XFEATURE_MASK_SSE);
309         print_xstate_feature(XFEATURE_MASK_YMM);
310         print_xstate_feature(XFEATURE_MASK_BNDREGS);
311         print_xstate_feature(XFEATURE_MASK_BNDCSR);
312         print_xstate_feature(XFEATURE_MASK_OPMASK);
313         print_xstate_feature(XFEATURE_MASK_ZMM_Hi256);
314         print_xstate_feature(XFEATURE_MASK_Hi16_ZMM);
315         print_xstate_feature(XFEATURE_MASK_PKRU);
316         print_xstate_feature(XFEATURE_MASK_PASID);
317 }
318
319 /*
320  * This check is important because it is easy to get XSTATE_*
321  * confused with XSTATE_BIT_*.
322  */
323 #define CHECK_XFEATURE(nr) do {         \
324         WARN_ON(nr < FIRST_EXTENDED_XFEATURE);  \
325         WARN_ON(nr >= XFEATURE_MAX);    \
326 } while (0)
327
328 /*
329  * We could cache this like xstate_size[], but we only use
330  * it here, so it would be a waste of space.
331  */
332 static int xfeature_is_aligned(int xfeature_nr)
333 {
334         u32 eax, ebx, ecx, edx;
335
336         CHECK_XFEATURE(xfeature_nr);
337
338         if (!xfeature_enabled(xfeature_nr)) {
339                 WARN_ONCE(1, "Checking alignment of disabled xfeature %d\n",
340                           xfeature_nr);
341                 return 0;
342         }
343
344         cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
345         /*
346          * The value returned by ECX[1] indicates the alignment
347          * of state component 'i' when the compacted format
348          * of the extended region of an XSAVE area is used:
349          */
350         return !!(ecx & 2);
351 }
352
353 /*
354  * This function sets up offsets and sizes of all extended states in
355  * xsave area. This supports both standard format and compacted format
356  * of the xsave area.
357  */
358 static void __init setup_xstate_comp_offsets(void)
359 {
360         unsigned int next_offset;
361         int i;
362
363         /*
364          * The FP xstates and SSE xstates are legacy states. They are always
365          * in the fixed offsets in the xsave area in either compacted form
366          * or standard form.
367          */
368         xstate_comp_offsets[XFEATURE_FP] = 0;
369         xstate_comp_offsets[XFEATURE_SSE] = offsetof(struct fxregs_state,
370                                                      xmm_space);
371
372         if (!boot_cpu_has(X86_FEATURE_XSAVES)) {
373                 for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
374                         if (xfeature_enabled(i))
375                                 xstate_comp_offsets[i] = xstate_offsets[i];
376                 }
377                 return;
378         }
379
380         next_offset = FXSAVE_SIZE + XSAVE_HDR_SIZE;
381
382         for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
383                 if (!xfeature_enabled(i))
384                         continue;
385
386                 if (xfeature_is_aligned(i))
387                         next_offset = ALIGN(next_offset, 64);
388
389                 xstate_comp_offsets[i] = next_offset;
390                 next_offset += xstate_sizes[i];
391         }
392 }
393
394 /*
395  * Setup offsets of a supervisor-state-only XSAVES buffer:
396  *
397  * The offsets stored in xstate_comp_offsets[] only work for one specific
398  * value of the Requested Feature BitMap (RFBM).  In cases where a different
399  * RFBM value is used, a different set of offsets is required.  This set of
400  * offsets is for when RFBM=xfeatures_mask_supervisor().
401  */
402 static void __init setup_supervisor_only_offsets(void)
403 {
404         unsigned int next_offset;
405         int i;
406
407         next_offset = FXSAVE_SIZE + XSAVE_HDR_SIZE;
408
409         for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
410                 if (!xfeature_enabled(i) || !xfeature_is_supervisor(i))
411                         continue;
412
413                 if (xfeature_is_aligned(i))
414                         next_offset = ALIGN(next_offset, 64);
415
416                 xstate_supervisor_only_offsets[i] = next_offset;
417                 next_offset += xstate_sizes[i];
418         }
419 }
420
421 /*
422  * Print out xstate component offsets and sizes
423  */
424 static void __init print_xstate_offset_size(void)
425 {
426         int i;
427
428         for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
429                 if (!xfeature_enabled(i))
430                         continue;
431                 pr_info("x86/fpu: xstate_offset[%d]: %4d, xstate_sizes[%d]: %4d\n",
432                          i, xstate_comp_offsets[i], i, xstate_sizes[i]);
433         }
434 }
435
436 /*
437  * All supported features have either init state all zeros or are
438  * handled in setup_init_fpu() individually. This is an explicit
439  * feature list and does not use XFEATURE_MASK*SUPPORTED to catch
440  * newly added supported features at build time and make people
441  * actually look at the init state for the new feature.
442  */
443 #define XFEATURES_INIT_FPSTATE_HANDLED          \
444         (XFEATURE_MASK_FP |                     \
445          XFEATURE_MASK_SSE |                    \
446          XFEATURE_MASK_YMM |                    \
447          XFEATURE_MASK_OPMASK |                 \
448          XFEATURE_MASK_ZMM_Hi256 |              \
449          XFEATURE_MASK_Hi16_ZMM  |              \
450          XFEATURE_MASK_PKRU |                   \
451          XFEATURE_MASK_BNDREGS |                \
452          XFEATURE_MASK_BNDCSR |                 \
453          XFEATURE_MASK_PASID)
454
455 /*
456  * setup the xstate image representing the init state
457  */
458 static void __init setup_init_fpu_buf(void)
459 {
460         static int on_boot_cpu __initdata = 1;
461
462         BUILD_BUG_ON((XFEATURE_MASK_USER_SUPPORTED |
463                       XFEATURE_MASK_SUPERVISOR_SUPPORTED) !=
464                      XFEATURES_INIT_FPSTATE_HANDLED);
465
466         WARN_ON_FPU(!on_boot_cpu);
467         on_boot_cpu = 0;
468
469         if (!boot_cpu_has(X86_FEATURE_XSAVE))
470                 return;
471
472         setup_xstate_features();
473         print_xstate_features();
474
475         if (boot_cpu_has(X86_FEATURE_XSAVES))
476                 init_fpstate.xsave.header.xcomp_bv = XCOMP_BV_COMPACTED_FORMAT |
477                                                      xfeatures_mask_all;
478
479         /*
480          * Init all the features state with header.xfeatures being 0x0
481          */
482         copy_kernel_to_xregs_booting(&init_fpstate.xsave);
483
484         /*
485          * All components are now in init state. Read the state back so
486          * that init_fpstate contains all non-zero init state. This only
487          * works with XSAVE, but not with XSAVEOPT and XSAVES because
488          * those use the init optimization which skips writing data for
489          * components in init state.
490          *
491          * XSAVE could be used, but that would require to reshuffle the
492          * data when XSAVES is available because XSAVES uses xstate
493          * compaction. But doing so is a pointless exercise because most
494          * components have an all zeros init state except for the legacy
495          * ones (FP and SSE). Those can be saved with FXSAVE into the
496          * legacy area. Adding new features requires to ensure that init
497          * state is all zeroes or if not to add the necessary handling
498          * here.
499          */
500         fxsave(&init_fpstate.fxsave);
501 }
502
503 static int xfeature_uncompacted_offset(int xfeature_nr)
504 {
505         u32 eax, ebx, ecx, edx;
506
507         /*
508          * Only XSAVES supports supervisor states and it uses compacted
509          * format. Checking a supervisor state's uncompacted offset is
510          * an error.
511          */
512         if (XFEATURE_MASK_SUPERVISOR_ALL & BIT_ULL(xfeature_nr)) {
513                 WARN_ONCE(1, "No fixed offset for xstate %d\n", xfeature_nr);
514                 return -1;
515         }
516
517         CHECK_XFEATURE(xfeature_nr);
518         cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
519         return ebx;
520 }
521
522 int xfeature_size(int xfeature_nr)
523 {
524         u32 eax, ebx, ecx, edx;
525
526         CHECK_XFEATURE(xfeature_nr);
527         cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
528         return eax;
529 }
530
531 /*
532  * 'XSAVES' implies two different things:
533  * 1. saving of supervisor/system state
534  * 2. using the compacted format
535  *
536  * Use this function when dealing with the compacted format so
537  * that it is obvious which aspect of 'XSAVES' is being handled
538  * by the calling code.
539  */
540 int using_compacted_format(void)
541 {
542         return boot_cpu_has(X86_FEATURE_XSAVES);
543 }
544
545 /* Validate an xstate header supplied by userspace (ptrace or sigreturn) */
546 int validate_user_xstate_header(const struct xstate_header *hdr)
547 {
548         /* No unknown or supervisor features may be set */
549         if (hdr->xfeatures & ~xfeatures_mask_user())
550                 return -EINVAL;
551
552         /* Userspace must use the uncompacted format */
553         if (hdr->xcomp_bv)
554                 return -EINVAL;
555
556         /*
557          * If 'reserved' is shrunken to add a new field, make sure to validate
558          * that new field here!
559          */
560         BUILD_BUG_ON(sizeof(hdr->reserved) != 48);
561
562         /* No reserved bits may be set */
563         if (memchr_inv(hdr->reserved, 0, sizeof(hdr->reserved)))
564                 return -EINVAL;
565
566         return 0;
567 }
568
569 static void __xstate_dump_leaves(void)
570 {
571         int i;
572         u32 eax, ebx, ecx, edx;
573         static int should_dump = 1;
574
575         if (!should_dump)
576                 return;
577         should_dump = 0;
578         /*
579          * Dump out a few leaves past the ones that we support
580          * just in case there are some goodies up there
581          */
582         for (i = 0; i < XFEATURE_MAX + 10; i++) {
583                 cpuid_count(XSTATE_CPUID, i, &eax, &ebx, &ecx, &edx);
584                 pr_warn("CPUID[%02x, %02x]: eax=%08x ebx=%08x ecx=%08x edx=%08x\n",
585                         XSTATE_CPUID, i, eax, ebx, ecx, edx);
586         }
587 }
588
589 #define XSTATE_WARN_ON(x) do {                                                  \
590         if (WARN_ONCE(x, "XSAVE consistency problem, dumping leaves")) {        \
591                 __xstate_dump_leaves();                                         \
592         }                                                                       \
593 } while (0)
594
595 #define XCHECK_SZ(sz, nr, nr_macro, __struct) do {                      \
596         if ((nr == nr_macro) &&                                         \
597             WARN_ONCE(sz != sizeof(__struct),                           \
598                 "%s: struct is %zu bytes, cpu state %d bytes\n",        \
599                 __stringify(nr_macro), sizeof(__struct), sz)) {         \
600                 __xstate_dump_leaves();                                 \
601         }                                                               \
602 } while (0)
603
604 /*
605  * We have a C struct for each 'xstate'.  We need to ensure
606  * that our software representation matches what the CPU
607  * tells us about the state's size.
608  */
609 static void check_xstate_against_struct(int nr)
610 {
611         /*
612          * Ask the CPU for the size of the state.
613          */
614         int sz = xfeature_size(nr);
615         /*
616          * Match each CPU state with the corresponding software
617          * structure.
618          */
619         XCHECK_SZ(sz, nr, XFEATURE_YMM,       struct ymmh_struct);
620         XCHECK_SZ(sz, nr, XFEATURE_BNDREGS,   struct mpx_bndreg_state);
621         XCHECK_SZ(sz, nr, XFEATURE_BNDCSR,    struct mpx_bndcsr_state);
622         XCHECK_SZ(sz, nr, XFEATURE_OPMASK,    struct avx_512_opmask_state);
623         XCHECK_SZ(sz, nr, XFEATURE_ZMM_Hi256, struct avx_512_zmm_uppers_state);
624         XCHECK_SZ(sz, nr, XFEATURE_Hi16_ZMM,  struct avx_512_hi16_state);
625         XCHECK_SZ(sz, nr, XFEATURE_PKRU,      struct pkru_state);
626         XCHECK_SZ(sz, nr, XFEATURE_PASID,     struct ia32_pasid_state);
627
628         /*
629          * Make *SURE* to add any feature numbers in below if
630          * there are "holes" in the xsave state component
631          * numbers.
632          */
633         if ((nr < XFEATURE_YMM) ||
634             (nr >= XFEATURE_MAX) ||
635             (nr == XFEATURE_PT_UNIMPLEMENTED_SO_FAR) ||
636             ((nr >= XFEATURE_RSRVD_COMP_11) && (nr <= XFEATURE_LBR))) {
637                 WARN_ONCE(1, "no structure for xstate: %d\n", nr);
638                 XSTATE_WARN_ON(1);
639         }
640 }
641
642 /*
643  * This essentially double-checks what the cpu told us about
644  * how large the XSAVE buffer needs to be.  We are recalculating
645  * it to be safe.
646  *
647  * Dynamic XSAVE features allocate their own buffers and are not
648  * covered by these checks. Only the size of the buffer for task->fpu
649  * is checked here.
650  */
651 static void do_extra_xstate_size_checks(void)
652 {
653         int paranoid_xstate_size = FXSAVE_SIZE + XSAVE_HDR_SIZE;
654         int i;
655
656         for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
657                 if (!xfeature_enabled(i))
658                         continue;
659
660                 check_xstate_against_struct(i);
661                 /*
662                  * Supervisor state components can be managed only by
663                  * XSAVES, which is compacted-format only.
664                  */
665                 if (!using_compacted_format())
666                         XSTATE_WARN_ON(xfeature_is_supervisor(i));
667
668                 /* Align from the end of the previous feature */
669                 if (xfeature_is_aligned(i))
670                         paranoid_xstate_size = ALIGN(paranoid_xstate_size, 64);
671                 /*
672                  * The offset of a given state in the non-compacted
673                  * format is given to us in a CPUID leaf.  We check
674                  * them for being ordered (increasing offsets) in
675                  * setup_xstate_features().
676                  */
677                 if (!using_compacted_format())
678                         paranoid_xstate_size = xfeature_uncompacted_offset(i);
679                 /*
680                  * The compacted-format offset always depends on where
681                  * the previous state ended.
682                  */
683                 paranoid_xstate_size += xfeature_size(i);
684         }
685         XSTATE_WARN_ON(paranoid_xstate_size != fpu_kernel_xstate_size);
686 }
687
688
689 /*
690  * Get total size of enabled xstates in XCR0 | IA32_XSS.
691  *
692  * Note the SDM's wording here.  "sub-function 0" only enumerates
693  * the size of the *user* states.  If we use it to size a buffer
694  * that we use 'XSAVES' on, we could potentially overflow the
695  * buffer because 'XSAVES' saves system states too.
696  */
697 static unsigned int __init get_xsaves_size(void)
698 {
699         unsigned int eax, ebx, ecx, edx;
700         /*
701          * - CPUID function 0DH, sub-function 1:
702          *    EBX enumerates the size (in bytes) required by
703          *    the XSAVES instruction for an XSAVE area
704          *    containing all the state components
705          *    corresponding to bits currently set in
706          *    XCR0 | IA32_XSS.
707          */
708         cpuid_count(XSTATE_CPUID, 1, &eax, &ebx, &ecx, &edx);
709         return ebx;
710 }
711
712 /*
713  * Get the total size of the enabled xstates without the dynamic supervisor
714  * features.
715  */
716 static unsigned int __init get_xsaves_size_no_dynamic(void)
717 {
718         u64 mask = xfeatures_mask_dynamic();
719         unsigned int size;
720
721         if (!mask)
722                 return get_xsaves_size();
723
724         /* Disable dynamic features. */
725         wrmsrl(MSR_IA32_XSS, xfeatures_mask_supervisor());
726
727         /*
728          * Ask the hardware what size is required of the buffer.
729          * This is the size required for the task->fpu buffer.
730          */
731         size = get_xsaves_size();
732
733         /* Re-enable dynamic features so XSAVES will work on them again. */
734         wrmsrl(MSR_IA32_XSS, xfeatures_mask_supervisor() | mask);
735
736         return size;
737 }
738
739 static unsigned int __init get_xsave_size(void)
740 {
741         unsigned int eax, ebx, ecx, edx;
742         /*
743          * - CPUID function 0DH, sub-function 0:
744          *    EBX enumerates the size (in bytes) required by
745          *    the XSAVE instruction for an XSAVE area
746          *    containing all the *user* state components
747          *    corresponding to bits currently set in XCR0.
748          */
749         cpuid_count(XSTATE_CPUID, 0, &eax, &ebx, &ecx, &edx);
750         return ebx;
751 }
752
753 /*
754  * Will the runtime-enumerated 'xstate_size' fit in the init
755  * task's statically-allocated buffer?
756  */
757 static bool is_supported_xstate_size(unsigned int test_xstate_size)
758 {
759         if (test_xstate_size <= sizeof(union fpregs_state))
760                 return true;
761
762         pr_warn("x86/fpu: xstate buffer too small (%zu < %d), disabling xsave\n",
763                         sizeof(union fpregs_state), test_xstate_size);
764         return false;
765 }
766
767 static int __init init_xstate_size(void)
768 {
769         /* Recompute the context size for enabled features: */
770         unsigned int possible_xstate_size;
771         unsigned int xsave_size;
772
773         xsave_size = get_xsave_size();
774
775         if (boot_cpu_has(X86_FEATURE_XSAVES))
776                 possible_xstate_size = get_xsaves_size_no_dynamic();
777         else
778                 possible_xstate_size = xsave_size;
779
780         /* Ensure we have the space to store all enabled: */
781         if (!is_supported_xstate_size(possible_xstate_size))
782                 return -EINVAL;
783
784         /*
785          * The size is OK, we are definitely going to use xsave,
786          * make it known to the world that we need more space.
787          */
788         fpu_kernel_xstate_size = possible_xstate_size;
789         do_extra_xstate_size_checks();
790
791         /*
792          * User space is always in standard format.
793          */
794         fpu_user_xstate_size = xsave_size;
795         return 0;
796 }
797
798 /*
799  * We enabled the XSAVE hardware, but something went wrong and
800  * we can not use it.  Disable it.
801  */
802 static void fpu__init_disable_system_xstate(void)
803 {
804         xfeatures_mask_all = 0;
805         cr4_clear_bits(X86_CR4_OSXSAVE);
806         setup_clear_cpu_cap(X86_FEATURE_XSAVE);
807 }
808
809 /*
810  * Enable and initialize the xsave feature.
811  * Called once per system bootup.
812  */
813 void __init fpu__init_system_xstate(void)
814 {
815         unsigned int eax, ebx, ecx, edx;
816         static int on_boot_cpu __initdata = 1;
817         u64 xfeatures;
818         int err;
819         int i;
820
821         WARN_ON_FPU(!on_boot_cpu);
822         on_boot_cpu = 0;
823
824         if (!boot_cpu_has(X86_FEATURE_FPU)) {
825                 pr_info("x86/fpu: No FPU detected\n");
826                 return;
827         }
828
829         if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
830                 pr_info("x86/fpu: x87 FPU will use %s\n",
831                         boot_cpu_has(X86_FEATURE_FXSR) ? "FXSAVE" : "FSAVE");
832                 return;
833         }
834
835         if (boot_cpu_data.cpuid_level < XSTATE_CPUID) {
836                 WARN_ON_FPU(1);
837                 return;
838         }
839
840         /*
841          * Find user xstates supported by the processor.
842          */
843         cpuid_count(XSTATE_CPUID, 0, &eax, &ebx, &ecx, &edx);
844         xfeatures_mask_all = eax + ((u64)edx << 32);
845
846         /*
847          * Find supervisor xstates supported by the processor.
848          */
849         cpuid_count(XSTATE_CPUID, 1, &eax, &ebx, &ecx, &edx);
850         xfeatures_mask_all |= ecx + ((u64)edx << 32);
851
852         if ((xfeatures_mask_user() & XFEATURE_MASK_FPSSE) != XFEATURE_MASK_FPSSE) {
853                 /*
854                  * This indicates that something really unexpected happened
855                  * with the enumeration.  Disable XSAVE and try to continue
856                  * booting without it.  This is too early to BUG().
857                  */
858                 pr_err("x86/fpu: FP/SSE not present amongst the CPU's xstate features: 0x%llx.\n",
859                        xfeatures_mask_all);
860                 goto out_disable;
861         }
862
863         /*
864          * Clear XSAVE features that are disabled in the normal CPUID.
865          */
866         for (i = 0; i < ARRAY_SIZE(xsave_cpuid_features); i++) {
867                 if (!boot_cpu_has(xsave_cpuid_features[i]))
868                         xfeatures_mask_all &= ~BIT_ULL(i);
869         }
870
871         xfeatures_mask_all &= XFEATURE_MASK_USER_SUPPORTED |
872                               XFEATURE_MASK_SUPERVISOR_SUPPORTED;
873
874         /* Store it for paranoia check at the end */
875         xfeatures = xfeatures_mask_all;
876
877         /* Enable xstate instructions to be able to continue with initialization: */
878         fpu__init_cpu_xstate();
879         err = init_xstate_size();
880         if (err)
881                 goto out_disable;
882
883         /*
884          * Update info used for ptrace frames; use standard-format size and no
885          * supervisor xstates:
886          */
887         update_regset_xstate_info(fpu_user_xstate_size, xfeatures_mask_user());
888
889         fpu__init_prepare_fx_sw_frame();
890         setup_init_fpu_buf();
891         setup_xstate_comp_offsets();
892         setup_supervisor_only_offsets();
893
894         /*
895          * Paranoia check whether something in the setup modified the
896          * xfeatures mask.
897          */
898         if (xfeatures != xfeatures_mask_all) {
899                 pr_err("x86/fpu: xfeatures modified from 0x%016llx to 0x%016llx during init, disabling XSAVE\n",
900                        xfeatures, xfeatures_mask_all);
901                 goto out_disable;
902         }
903
904         print_xstate_offset_size();
905         pr_info("x86/fpu: Enabled xstate features 0x%llx, context size is %d bytes, using '%s' format.\n",
906                 xfeatures_mask_all,
907                 fpu_kernel_xstate_size,
908                 boot_cpu_has(X86_FEATURE_XSAVES) ? "compacted" : "standard");
909         return;
910
911 out_disable:
912         /* something went wrong, try to boot without any XSAVE support */
913         fpu__init_disable_system_xstate();
914 }
915
916 /*
917  * Restore minimal FPU state after suspend:
918  */
919 void fpu__resume_cpu(void)
920 {
921         /*
922          * Restore XCR0 on xsave capable CPUs:
923          */
924         if (boot_cpu_has(X86_FEATURE_XSAVE))
925                 xsetbv(XCR_XFEATURE_ENABLED_MASK, xfeatures_mask_user());
926
927         /*
928          * Restore IA32_XSS. The same CPUID bit enumerates support
929          * of XSAVES and MSR_IA32_XSS.
930          */
931         if (boot_cpu_has(X86_FEATURE_XSAVES)) {
932                 wrmsrl(MSR_IA32_XSS, xfeatures_mask_supervisor()  |
933                                      xfeatures_mask_dynamic());
934         }
935 }
936
937 /*
938  * Given an xstate feature nr, calculate where in the xsave
939  * buffer the state is.  Callers should ensure that the buffer
940  * is valid.
941  */
942 static void *__raw_xsave_addr(struct xregs_state *xsave, int xfeature_nr)
943 {
944         if (!xfeature_enabled(xfeature_nr)) {
945                 WARN_ON_FPU(1);
946                 return NULL;
947         }
948
949         return (void *)xsave + xstate_comp_offsets[xfeature_nr];
950 }
951 /*
952  * Given the xsave area and a state inside, this function returns the
953  * address of the state.
954  *
955  * This is the API that is called to get xstate address in either
956  * standard format or compacted format of xsave area.
957  *
958  * Note that if there is no data for the field in the xsave buffer
959  * this will return NULL.
960  *
961  * Inputs:
962  *      xstate: the thread's storage area for all FPU data
963  *      xfeature_nr: state which is defined in xsave.h (e.g. XFEATURE_FP,
964  *      XFEATURE_SSE, etc...)
965  * Output:
966  *      address of the state in the xsave area, or NULL if the
967  *      field is not present in the xsave buffer.
968  */
969 void *get_xsave_addr(struct xregs_state *xsave, int xfeature_nr)
970 {
971         /*
972          * Do we even *have* xsave state?
973          */
974         if (!boot_cpu_has(X86_FEATURE_XSAVE))
975                 return NULL;
976
977         /*
978          * We should not ever be requesting features that we
979          * have not enabled.
980          */
981         WARN_ONCE(!(xfeatures_mask_all & BIT_ULL(xfeature_nr)),
982                   "get of unsupported state");
983         /*
984          * This assumes the last 'xsave*' instruction to
985          * have requested that 'xfeature_nr' be saved.
986          * If it did not, we might be seeing and old value
987          * of the field in the buffer.
988          *
989          * This can happen because the last 'xsave' did not
990          * request that this feature be saved (unlikely)
991          * or because the "init optimization" caused it
992          * to not be saved.
993          */
994         if (!(xsave->header.xfeatures & BIT_ULL(xfeature_nr)))
995                 return NULL;
996
997         return __raw_xsave_addr(xsave, xfeature_nr);
998 }
999 EXPORT_SYMBOL_GPL(get_xsave_addr);
1000
1001 #ifdef CONFIG_ARCH_HAS_PKEYS
1002
1003 /*
1004  * This will go out and modify PKRU register to set the access
1005  * rights for @pkey to @init_val.
1006  */
1007 int arch_set_user_pkey_access(struct task_struct *tsk, int pkey,
1008                 unsigned long init_val)
1009 {
1010         u32 old_pkru;
1011         int pkey_shift = (pkey * PKRU_BITS_PER_PKEY);
1012         u32 new_pkru_bits = 0;
1013
1014         /*
1015          * This check implies XSAVE support.  OSPKE only gets
1016          * set if we enable XSAVE and we enable PKU in XCR0.
1017          */
1018         if (!boot_cpu_has(X86_FEATURE_OSPKE))
1019                 return -EINVAL;
1020
1021         /*
1022          * This code should only be called with valid 'pkey'
1023          * values originating from in-kernel users.  Complain
1024          * if a bad value is observed.
1025          */
1026         WARN_ON_ONCE(pkey >= arch_max_pkey());
1027
1028         /* Set the bits we need in PKRU:  */
1029         if (init_val & PKEY_DISABLE_ACCESS)
1030                 new_pkru_bits |= PKRU_AD_BIT;
1031         if (init_val & PKEY_DISABLE_WRITE)
1032                 new_pkru_bits |= PKRU_WD_BIT;
1033
1034         /* Shift the bits in to the correct place in PKRU for pkey: */
1035         new_pkru_bits <<= pkey_shift;
1036
1037         /* Get old PKRU and mask off any old bits in place: */
1038         old_pkru = read_pkru();
1039         old_pkru &= ~((PKRU_AD_BIT|PKRU_WD_BIT) << pkey_shift);
1040
1041         /* Write old part along with new part: */
1042         write_pkru(old_pkru | new_pkru_bits);
1043
1044         return 0;
1045 }
1046 #endif /* ! CONFIG_ARCH_HAS_PKEYS */
1047
1048 /*
1049  * Weird legacy quirk: SSE and YMM states store information in the
1050  * MXCSR and MXCSR_FLAGS fields of the FP area. That means if the FP
1051  * area is marked as unused in the xfeatures header, we need to copy
1052  * MXCSR and MXCSR_FLAGS if either SSE or YMM are in use.
1053  */
1054 static inline bool xfeatures_mxcsr_quirk(u64 xfeatures)
1055 {
1056         if (!(xfeatures & (XFEATURE_MASK_SSE|XFEATURE_MASK_YMM)))
1057                 return false;
1058
1059         if (xfeatures & XFEATURE_MASK_FP)
1060                 return false;
1061
1062         return true;
1063 }
1064
1065 static void copy_feature(bool from_xstate, struct membuf *to, void *xstate,
1066                          void *init_xstate, unsigned int size)
1067 {
1068         membuf_write(to, from_xstate ? xstate : init_xstate, size);
1069 }
1070
1071 /*
1072  * Convert from kernel XSAVES compacted format to standard format and copy
1073  * to a kernel-space ptrace buffer.
1074  *
1075  * It supports partial copy but pos always starts from zero. This is called
1076  * from xstateregs_get() and there we check the CPU has XSAVES.
1077  */
1078 void copy_xstate_to_kernel(struct membuf to, struct xregs_state *xsave)
1079 {
1080         const unsigned int off_mxcsr = offsetof(struct fxregs_state, mxcsr);
1081         struct xregs_state *xinit = &init_fpstate.xsave;
1082         struct xstate_header header;
1083         unsigned int zerofrom;
1084         int i;
1085
1086         /*
1087          * The destination is a ptrace buffer; we put in only user xstates:
1088          */
1089         memset(&header, 0, sizeof(header));
1090         header.xfeatures = xsave->header.xfeatures;
1091         header.xfeatures &= xfeatures_mask_user();
1092
1093         /* Copy FP state up to MXCSR */
1094         copy_feature(header.xfeatures & XFEATURE_MASK_FP, &to, &xsave->i387,
1095                      &xinit->i387, off_mxcsr);
1096
1097         /* Copy MXCSR when SSE or YMM are set in the feature mask */
1098         copy_feature(header.xfeatures & (XFEATURE_MASK_SSE | XFEATURE_MASK_YMM),
1099                      &to, &xsave->i387.mxcsr, &xinit->i387.mxcsr,
1100                      MXCSR_AND_FLAGS_SIZE);
1101
1102         /* Copy the remaining FP state */
1103         copy_feature(header.xfeatures & XFEATURE_MASK_FP,
1104                      &to, &xsave->i387.st_space, &xinit->i387.st_space,
1105                      sizeof(xsave->i387.st_space));
1106
1107         /* Copy the SSE state - shared with YMM, but independently managed */
1108         copy_feature(header.xfeatures & XFEATURE_MASK_SSE,
1109                      &to, &xsave->i387.xmm_space, &xinit->i387.xmm_space,
1110                      sizeof(xsave->i387.xmm_space));
1111
1112         /* Zero the padding area */
1113         membuf_zero(&to, sizeof(xsave->i387.padding));
1114
1115         /* Copy xsave->i387.sw_reserved */
1116         membuf_write(&to, xstate_fx_sw_bytes, sizeof(xsave->i387.sw_reserved));
1117
1118         /* Copy the user space relevant state of @xsave->header */
1119         membuf_write(&to, &header, sizeof(header));
1120
1121         zerofrom = offsetof(struct xregs_state, extended_state_area);
1122
1123         for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
1124                 /*
1125                  * The ptrace buffer is in non-compacted XSAVE format.
1126                  * In non-compacted format disabled features still occupy
1127                  * state space, but there is no state to copy from in the
1128                  * compacted init_fpstate. The gap tracking will zero this
1129                  * later.
1130                  */
1131                 if (!(xfeatures_mask_user() & BIT_ULL(i)))
1132                         continue;
1133
1134                 /*
1135                  * If there was a feature or alignment gap, zero the space
1136                  * in the destination buffer.
1137                  */
1138                 if (zerofrom < xstate_offsets[i])
1139                         membuf_zero(&to, xstate_offsets[i] - zerofrom);
1140
1141                 copy_feature(header.xfeatures & BIT_ULL(i), &to,
1142                              __raw_xsave_addr(xsave, i),
1143                              __raw_xsave_addr(xinit, i),
1144                              xstate_sizes[i]);
1145
1146                 /*
1147                  * Keep track of the last copied state in the non-compacted
1148                  * target buffer for gap zeroing.
1149                  */
1150                 zerofrom = xstate_offsets[i] + xstate_sizes[i];
1151         }
1152
1153         if (to.left)
1154                 membuf_zero(&to, to.left);
1155 }
1156
1157 /*
1158  * Convert from a ptrace standard-format kernel buffer to kernel XSAVES format
1159  * and copy to the target thread. This is called from xstateregs_set().
1160  */
1161 int copy_kernel_to_xstate(struct xregs_state *xsave, const void *kbuf)
1162 {
1163         unsigned int offset, size;
1164         int i;
1165         struct xstate_header hdr;
1166
1167         offset = offsetof(struct xregs_state, header);
1168         size = sizeof(hdr);
1169
1170         memcpy(&hdr, kbuf + offset, size);
1171
1172         if (validate_user_xstate_header(&hdr))
1173                 return -EINVAL;
1174
1175         for (i = 0; i < XFEATURE_MAX; i++) {
1176                 u64 mask = ((u64)1 << i);
1177
1178                 if (hdr.xfeatures & mask) {
1179                         void *dst = __raw_xsave_addr(xsave, i);
1180
1181                         offset = xstate_offsets[i];
1182                         size = xstate_sizes[i];
1183
1184                         memcpy(dst, kbuf + offset, size);
1185                 }
1186         }
1187
1188         if (xfeatures_mxcsr_quirk(hdr.xfeatures)) {
1189                 offset = offsetof(struct fxregs_state, mxcsr);
1190                 size = MXCSR_AND_FLAGS_SIZE;
1191                 memcpy(&xsave->i387.mxcsr, kbuf + offset, size);
1192         }
1193
1194         /*
1195          * The state that came in from userspace was user-state only.
1196          * Mask all the user states out of 'xfeatures':
1197          */
1198         xsave->header.xfeatures &= XFEATURE_MASK_SUPERVISOR_ALL;
1199
1200         /*
1201          * Add back in the features that came in from userspace:
1202          */
1203         xsave->header.xfeatures |= hdr.xfeatures;
1204
1205         return 0;
1206 }
1207
1208 /*
1209  * Convert from a ptrace or sigreturn standard-format user-space buffer to
1210  * kernel XSAVES format and copy to the target thread. This is called from
1211  * xstateregs_set(), as well as potentially from the sigreturn() and
1212  * rt_sigreturn() system calls.
1213  */
1214 int copy_user_to_xstate(struct xregs_state *xsave, const void __user *ubuf)
1215 {
1216         unsigned int offset, size;
1217         int i;
1218         struct xstate_header hdr;
1219
1220         offset = offsetof(struct xregs_state, header);
1221         size = sizeof(hdr);
1222
1223         if (copy_from_user(&hdr, ubuf + offset, size))
1224                 return -EFAULT;
1225
1226         if (validate_user_xstate_header(&hdr))
1227                 return -EINVAL;
1228
1229         for (i = 0; i < XFEATURE_MAX; i++) {
1230                 u64 mask = ((u64)1 << i);
1231
1232                 if (hdr.xfeatures & mask) {
1233                         void *dst = __raw_xsave_addr(xsave, i);
1234
1235                         offset = xstate_offsets[i];
1236                         size = xstate_sizes[i];
1237
1238                         if (copy_from_user(dst, ubuf + offset, size))
1239                                 return -EFAULT;
1240                 }
1241         }
1242
1243         if (xfeatures_mxcsr_quirk(hdr.xfeatures)) {
1244                 offset = offsetof(struct fxregs_state, mxcsr);
1245                 size = MXCSR_AND_FLAGS_SIZE;
1246                 if (copy_from_user(&xsave->i387.mxcsr, ubuf + offset, size))
1247                         return -EFAULT;
1248         }
1249
1250         /*
1251          * The state that came in from userspace was user-state only.
1252          * Mask all the user states out of 'xfeatures':
1253          */
1254         xsave->header.xfeatures &= XFEATURE_MASK_SUPERVISOR_ALL;
1255
1256         /*
1257          * Add back in the features that came in from userspace:
1258          */
1259         xsave->header.xfeatures |= hdr.xfeatures;
1260
1261         return 0;
1262 }
1263
1264 /*
1265  * Save only supervisor states to the kernel buffer.  This blows away all
1266  * old states, and is intended to be used only in __fpu__restore_sig(), where
1267  * user states are restored from the user buffer.
1268  */
1269 void copy_supervisor_to_kernel(struct xregs_state *xstate)
1270 {
1271         struct xstate_header *header;
1272         u64 max_bit, min_bit;
1273         u32 lmask, hmask;
1274         int err, i;
1275
1276         if (WARN_ON(!boot_cpu_has(X86_FEATURE_XSAVES)))
1277                 return;
1278
1279         if (!xfeatures_mask_supervisor())
1280                 return;
1281
1282         max_bit = __fls(xfeatures_mask_supervisor());
1283         min_bit = __ffs(xfeatures_mask_supervisor());
1284
1285         lmask = xfeatures_mask_supervisor();
1286         hmask = xfeatures_mask_supervisor() >> 32;
1287         XSTATE_OP(XSAVES, xstate, lmask, hmask, err);
1288
1289         /* We should never fault when copying to a kernel buffer: */
1290         if (WARN_ON_FPU(err))
1291                 return;
1292
1293         /*
1294          * At this point, the buffer has only supervisor states and must be
1295          * converted back to normal kernel format.
1296          */
1297         header = &xstate->header;
1298         header->xcomp_bv |= xfeatures_mask_all;
1299
1300         /*
1301          * This only moves states up in the buffer.  Start with
1302          * the last state and move backwards so that states are
1303          * not overwritten until after they are moved.  Note:
1304          * memmove() allows overlapping src/dst buffers.
1305          */
1306         for (i = max_bit; i >= min_bit; i--) {
1307                 u8 *xbuf = (u8 *)xstate;
1308
1309                 if (!((header->xfeatures >> i) & 1))
1310                         continue;
1311
1312                 /* Move xfeature 'i' into its normal location */
1313                 memmove(xbuf + xstate_comp_offsets[i],
1314                         xbuf + xstate_supervisor_only_offsets[i],
1315                         xstate_sizes[i]);
1316         }
1317 }
1318
1319 /**
1320  * copy_dynamic_supervisor_to_kernel() - Save dynamic supervisor states to
1321  *                                       an xsave area
1322  * @xstate: A pointer to an xsave area
1323  * @mask: Represent the dynamic supervisor features saved into the xsave area
1324  *
1325  * Only the dynamic supervisor states sets in the mask are saved into the xsave
1326  * area (See the comment in XFEATURE_MASK_DYNAMIC for the details of dynamic
1327  * supervisor feature). Besides the dynamic supervisor states, the legacy
1328  * region and XSAVE header are also saved into the xsave area. The supervisor
1329  * features in the XFEATURE_MASK_SUPERVISOR_SUPPORTED and
1330  * XFEATURE_MASK_SUPERVISOR_UNSUPPORTED are not saved.
1331  *
1332  * The xsave area must be 64-bytes aligned.
1333  */
1334 void copy_dynamic_supervisor_to_kernel(struct xregs_state *xstate, u64 mask)
1335 {
1336         u64 dynamic_mask = xfeatures_mask_dynamic() & mask;
1337         u32 lmask, hmask;
1338         int err;
1339
1340         if (WARN_ON_FPU(!boot_cpu_has(X86_FEATURE_XSAVES)))
1341                 return;
1342
1343         if (WARN_ON_FPU(!dynamic_mask))
1344                 return;
1345
1346         lmask = dynamic_mask;
1347         hmask = dynamic_mask >> 32;
1348
1349         XSTATE_OP(XSAVES, xstate, lmask, hmask, err);
1350
1351         /* Should never fault when copying to a kernel buffer */
1352         WARN_ON_FPU(err);
1353 }
1354
1355 /**
1356  * copy_kernel_to_dynamic_supervisor() - Restore dynamic supervisor states from
1357  *                                       an xsave area
1358  * @xstate: A pointer to an xsave area
1359  * @mask: Represent the dynamic supervisor features restored from the xsave area
1360  *
1361  * Only the dynamic supervisor states sets in the mask are restored from the
1362  * xsave area (See the comment in XFEATURE_MASK_DYNAMIC for the details of
1363  * dynamic supervisor feature). Besides the dynamic supervisor states, the
1364  * legacy region and XSAVE header are also restored from the xsave area. The
1365  * supervisor features in the XFEATURE_MASK_SUPERVISOR_SUPPORTED and
1366  * XFEATURE_MASK_SUPERVISOR_UNSUPPORTED are not restored.
1367  *
1368  * The xsave area must be 64-bytes aligned.
1369  */
1370 void copy_kernel_to_dynamic_supervisor(struct xregs_state *xstate, u64 mask)
1371 {
1372         u64 dynamic_mask = xfeatures_mask_dynamic() & mask;
1373         u32 lmask, hmask;
1374         int err;
1375
1376         if (WARN_ON_FPU(!boot_cpu_has(X86_FEATURE_XSAVES)))
1377                 return;
1378
1379         if (WARN_ON_FPU(!dynamic_mask))
1380                 return;
1381
1382         lmask = dynamic_mask;
1383         hmask = dynamic_mask >> 32;
1384
1385         XSTATE_OP(XRSTORS, xstate, lmask, hmask, err);
1386
1387         /* Should never fault when copying from a kernel buffer */
1388         WARN_ON_FPU(err);
1389 }
1390
1391 #ifdef CONFIG_PROC_PID_ARCH_STATUS
1392 /*
1393  * Report the amount of time elapsed in millisecond since last AVX512
1394  * use in the task.
1395  */
1396 static void avx512_status(struct seq_file *m, struct task_struct *task)
1397 {
1398         unsigned long timestamp = READ_ONCE(task->thread.fpu.avx512_timestamp);
1399         long delta;
1400
1401         if (!timestamp) {
1402                 /*
1403                  * Report -1 if no AVX512 usage
1404                  */
1405                 delta = -1;
1406         } else {
1407                 delta = (long)(jiffies - timestamp);
1408                 /*
1409                  * Cap to LONG_MAX if time difference > LONG_MAX
1410                  */
1411                 if (delta < 0)
1412                         delta = LONG_MAX;
1413                 delta = jiffies_to_msecs(delta);
1414         }
1415
1416         seq_put_decimal_ll(m, "AVX512_elapsed_ms:\t", delta);
1417         seq_putc(m, '\n');
1418 }
1419
1420 /*
1421  * Report architecture specific information
1422  */
1423 int proc_pid_arch_status(struct seq_file *m, struct pid_namespace *ns,
1424                         struct pid *pid, struct task_struct *task)
1425 {
1426         /*
1427          * Report AVX512 state if the processor and build option supported.
1428          */
1429         if (cpu_feature_enabled(X86_FEATURE_AVX512F))
1430                 avx512_status(m, task);
1431
1432         return 0;
1433 }
1434 #endif /* CONFIG_PROC_PID_ARCH_STATUS */