mm/core, x86/mm/pkeys: Add execute-only protection keys support
[cascardo/linux.git] / arch / x86 / kernel / fpu / xstate.c
1 /*
2  * xsave/xrstor support.
3  *
4  * Author: Suresh Siddha <suresh.b.siddha@intel.com>
5  */
6 #include <linux/compat.h>
7 #include <linux/cpu.h>
8 #include <linux/pkeys.h>
9
10 #include <asm/fpu/api.h>
11 #include <asm/fpu/internal.h>
12 #include <asm/fpu/signal.h>
13 #include <asm/fpu/regset.h>
14
15 #include <asm/tlbflush.h>
16
17 /*
18  * Although we spell it out in here, the Processor Trace
19  * xfeature is completely unused.  We use other mechanisms
20  * to save/restore PT state in Linux.
21  */
22 static const char *xfeature_names[] =
23 {
24         "x87 floating point registers"  ,
25         "SSE registers"                 ,
26         "AVX registers"                 ,
27         "MPX bounds registers"          ,
28         "MPX CSR"                       ,
29         "AVX-512 opmask"                ,
30         "AVX-512 Hi256"                 ,
31         "AVX-512 ZMM_Hi256"             ,
32         "Processor Trace (unused)"      ,
33         "Protection Keys User registers",
34         "unknown xstate feature"        ,
35 };
36
37 /*
38  * Mask of xstate features supported by the CPU and the kernel:
39  */
40 u64 xfeatures_mask __read_mostly;
41
42 static unsigned int xstate_offsets[XFEATURE_MAX] = { [ 0 ... XFEATURE_MAX - 1] = -1};
43 static unsigned int xstate_sizes[XFEATURE_MAX]   = { [ 0 ... XFEATURE_MAX - 1] = -1};
44 static unsigned int xstate_comp_offsets[sizeof(xfeatures_mask)*8];
45
46 /*
47  * Clear all of the X86_FEATURE_* bits that are unavailable
48  * when the CPU has no XSAVE support.
49  */
50 void fpu__xstate_clear_all_cpu_caps(void)
51 {
52         setup_clear_cpu_cap(X86_FEATURE_XSAVE);
53         setup_clear_cpu_cap(X86_FEATURE_XSAVEOPT);
54         setup_clear_cpu_cap(X86_FEATURE_XSAVEC);
55         setup_clear_cpu_cap(X86_FEATURE_XSAVES);
56         setup_clear_cpu_cap(X86_FEATURE_AVX);
57         setup_clear_cpu_cap(X86_FEATURE_AVX2);
58         setup_clear_cpu_cap(X86_FEATURE_AVX512F);
59         setup_clear_cpu_cap(X86_FEATURE_AVX512PF);
60         setup_clear_cpu_cap(X86_FEATURE_AVX512ER);
61         setup_clear_cpu_cap(X86_FEATURE_AVX512CD);
62         setup_clear_cpu_cap(X86_FEATURE_MPX);
63         setup_clear_cpu_cap(X86_FEATURE_XGETBV1);
64         setup_clear_cpu_cap(X86_FEATURE_PKU);
65 }
66
67 /*
68  * Return whether the system supports a given xfeature.
69  *
70  * Also return the name of the (most advanced) feature that the caller requested:
71  */
72 int cpu_has_xfeatures(u64 xfeatures_needed, const char **feature_name)
73 {
74         u64 xfeatures_missing = xfeatures_needed & ~xfeatures_mask;
75
76         if (unlikely(feature_name)) {
77                 long xfeature_idx, max_idx;
78                 u64 xfeatures_print;
79                 /*
80                  * So we use FLS here to be able to print the most advanced
81                  * feature that was requested but is missing. So if a driver
82                  * asks about "XFEATURE_MASK_SSE | XFEATURE_MASK_YMM" we'll print the
83                  * missing AVX feature - this is the most informative message
84                  * to users:
85                  */
86                 if (xfeatures_missing)
87                         xfeatures_print = xfeatures_missing;
88                 else
89                         xfeatures_print = xfeatures_needed;
90
91                 xfeature_idx = fls64(xfeatures_print)-1;
92                 max_idx = ARRAY_SIZE(xfeature_names)-1;
93                 xfeature_idx = min(xfeature_idx, max_idx);
94
95                 *feature_name = xfeature_names[xfeature_idx];
96         }
97
98         if (xfeatures_missing)
99                 return 0;
100
101         return 1;
102 }
103 EXPORT_SYMBOL_GPL(cpu_has_xfeatures);
104
105 /*
106  * When executing XSAVEOPT (or other optimized XSAVE instructions), if
107  * a processor implementation detects that an FPU state component is still
108  * (or is again) in its initialized state, it may clear the corresponding
109  * bit in the header.xfeatures field, and can skip the writeout of registers
110  * to the corresponding memory layout.
111  *
112  * This means that when the bit is zero, the state component might still contain
113  * some previous - non-initialized register state.
114  *
115  * Before writing xstate information to user-space we sanitize those components,
116  * to always ensure that the memory layout of a feature will be in the init state
117  * if the corresponding header bit is zero. This is to ensure that user-space doesn't
118  * see some stale state in the memory layout during signal handling, debugging etc.
119  */
120 void fpstate_sanitize_xstate(struct fpu *fpu)
121 {
122         struct fxregs_state *fx = &fpu->state.fxsave;
123         int feature_bit;
124         u64 xfeatures;
125
126         if (!use_xsaveopt())
127                 return;
128
129         xfeatures = fpu->state.xsave.header.xfeatures;
130
131         /*
132          * None of the feature bits are in init state. So nothing else
133          * to do for us, as the memory layout is up to date.
134          */
135         if ((xfeatures & xfeatures_mask) == xfeatures_mask)
136                 return;
137
138         /*
139          * FP is in init state
140          */
141         if (!(xfeatures & XFEATURE_MASK_FP)) {
142                 fx->cwd = 0x37f;
143                 fx->swd = 0;
144                 fx->twd = 0;
145                 fx->fop = 0;
146                 fx->rip = 0;
147                 fx->rdp = 0;
148                 memset(&fx->st_space[0], 0, 128);
149         }
150
151         /*
152          * SSE is in init state
153          */
154         if (!(xfeatures & XFEATURE_MASK_SSE))
155                 memset(&fx->xmm_space[0], 0, 256);
156
157         /*
158          * First two features are FPU and SSE, which above we handled
159          * in a special way already:
160          */
161         feature_bit = 0x2;
162         xfeatures = (xfeatures_mask & ~xfeatures) >> 2;
163
164         /*
165          * Update all the remaining memory layouts according to their
166          * standard xstate layout, if their header bit is in the init
167          * state:
168          */
169         while (xfeatures) {
170                 if (xfeatures & 0x1) {
171                         int offset = xstate_offsets[feature_bit];
172                         int size = xstate_sizes[feature_bit];
173
174                         memcpy((void *)fx + offset,
175                                (void *)&init_fpstate.xsave + offset,
176                                size);
177                 }
178
179                 xfeatures >>= 1;
180                 feature_bit++;
181         }
182 }
183
184 /*
185  * Enable the extended processor state save/restore feature.
186  * Called once per CPU onlining.
187  */
188 void fpu__init_cpu_xstate(void)
189 {
190         if (!cpu_has_xsave || !xfeatures_mask)
191                 return;
192
193         cr4_set_bits(X86_CR4_OSXSAVE);
194         xsetbv(XCR_XFEATURE_ENABLED_MASK, xfeatures_mask);
195 }
196
197 /*
198  * Note that in the future we will likely need a pair of
199  * functions here: one for user xstates and the other for
200  * system xstates.  For now, they are the same.
201  */
202 static int xfeature_enabled(enum xfeature xfeature)
203 {
204         return !!(xfeatures_mask & (1UL << xfeature));
205 }
206
207 /*
208  * Record the offsets and sizes of various xstates contained
209  * in the XSAVE state memory layout.
210  */
211 static void __init setup_xstate_features(void)
212 {
213         u32 eax, ebx, ecx, edx, i;
214         /* start at the beginnning of the "extended state" */
215         unsigned int last_good_offset = offsetof(struct xregs_state,
216                                                  extended_state_area);
217
218         for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
219                 if (!xfeature_enabled(i))
220                         continue;
221
222                 cpuid_count(XSTATE_CPUID, i, &eax, &ebx, &ecx, &edx);
223                 xstate_offsets[i] = ebx;
224                 xstate_sizes[i] = eax;
225                 /*
226                  * In our xstate size checks, we assume that the
227                  * highest-numbered xstate feature has the
228                  * highest offset in the buffer.  Ensure it does.
229                  */
230                 WARN_ONCE(last_good_offset > xstate_offsets[i],
231                         "x86/fpu: misordered xstate at %d\n", last_good_offset);
232                 last_good_offset = xstate_offsets[i];
233
234                 printk(KERN_INFO "x86/fpu: xstate_offset[%d]: %4d, xstate_sizes[%d]: %4d\n", i, ebx, i, eax);
235         }
236 }
237
238 static void __init print_xstate_feature(u64 xstate_mask)
239 {
240         const char *feature_name;
241
242         if (cpu_has_xfeatures(xstate_mask, &feature_name))
243                 pr_info("x86/fpu: Supporting XSAVE feature 0x%03Lx: '%s'\n", xstate_mask, feature_name);
244 }
245
246 /*
247  * Print out all the supported xstate features:
248  */
249 static void __init print_xstate_features(void)
250 {
251         print_xstate_feature(XFEATURE_MASK_FP);
252         print_xstate_feature(XFEATURE_MASK_SSE);
253         print_xstate_feature(XFEATURE_MASK_YMM);
254         print_xstate_feature(XFEATURE_MASK_BNDREGS);
255         print_xstate_feature(XFEATURE_MASK_BNDCSR);
256         print_xstate_feature(XFEATURE_MASK_OPMASK);
257         print_xstate_feature(XFEATURE_MASK_ZMM_Hi256);
258         print_xstate_feature(XFEATURE_MASK_Hi16_ZMM);
259         print_xstate_feature(XFEATURE_MASK_PKRU);
260 }
261
262 /*
263  * This function sets up offsets and sizes of all extended states in
264  * xsave area. This supports both standard format and compacted format
265  * of the xsave aread.
266  */
267 static void __init setup_xstate_comp(void)
268 {
269         unsigned int xstate_comp_sizes[sizeof(xfeatures_mask)*8];
270         int i;
271
272         /*
273          * The FP xstates and SSE xstates are legacy states. They are always
274          * in the fixed offsets in the xsave area in either compacted form
275          * or standard form.
276          */
277         xstate_comp_offsets[0] = 0;
278         xstate_comp_offsets[1] = offsetof(struct fxregs_state, xmm_space);
279
280         if (!cpu_has_xsaves) {
281                 for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
282                         if (xfeature_enabled(i)) {
283                                 xstate_comp_offsets[i] = xstate_offsets[i];
284                                 xstate_comp_sizes[i] = xstate_sizes[i];
285                         }
286                 }
287                 return;
288         }
289
290         xstate_comp_offsets[FIRST_EXTENDED_XFEATURE] =
291                 FXSAVE_SIZE + XSAVE_HDR_SIZE;
292
293         for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
294                 if (xfeature_enabled(i))
295                         xstate_comp_sizes[i] = xstate_sizes[i];
296                 else
297                         xstate_comp_sizes[i] = 0;
298
299                 if (i > FIRST_EXTENDED_XFEATURE)
300                         xstate_comp_offsets[i] = xstate_comp_offsets[i-1]
301                                         + xstate_comp_sizes[i-1];
302
303         }
304 }
305
306 /*
307  * setup the xstate image representing the init state
308  */
309 static void __init setup_init_fpu_buf(void)
310 {
311         static int on_boot_cpu __initdata = 1;
312
313         WARN_ON_FPU(!on_boot_cpu);
314         on_boot_cpu = 0;
315
316         if (!cpu_has_xsave)
317                 return;
318
319         setup_xstate_features();
320         print_xstate_features();
321
322         if (cpu_has_xsaves) {
323                 init_fpstate.xsave.header.xcomp_bv = (u64)1 << 63 | xfeatures_mask;
324                 init_fpstate.xsave.header.xfeatures = xfeatures_mask;
325         }
326
327         /*
328          * Init all the features state with header_bv being 0x0
329          */
330         copy_kernel_to_xregs_booting(&init_fpstate.xsave);
331
332         /*
333          * Dump the init state again. This is to identify the init state
334          * of any feature which is not represented by all zero's.
335          */
336         copy_xregs_to_kernel_booting(&init_fpstate.xsave);
337 }
338
339 static int xfeature_is_supervisor(int xfeature_nr)
340 {
341         /*
342          * We currently do not support supervisor states, but if
343          * we did, we could find out like this.
344          *
345          * SDM says: If state component i is a user state component,
346          * ECX[0] return 0; if state component i is a supervisor
347          * state component, ECX[0] returns 1.
348         u32 eax, ebx, ecx, edx;
349         cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx;
350         return !!(ecx & 1);
351         */
352         return 0;
353 }
354 /*
355 static int xfeature_is_user(int xfeature_nr)
356 {
357         return !xfeature_is_supervisor(xfeature_nr);
358 }
359 */
360
361 /*
362  * This check is important because it is easy to get XSTATE_*
363  * confused with XSTATE_BIT_*.
364  */
365 #define CHECK_XFEATURE(nr) do {         \
366         WARN_ON(nr < FIRST_EXTENDED_XFEATURE);  \
367         WARN_ON(nr >= XFEATURE_MAX);    \
368 } while (0)
369
370 /*
371  * We could cache this like xstate_size[], but we only use
372  * it here, so it would be a waste of space.
373  */
374 static int xfeature_is_aligned(int xfeature_nr)
375 {
376         u32 eax, ebx, ecx, edx;
377
378         CHECK_XFEATURE(xfeature_nr);
379         cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
380         /*
381          * The value returned by ECX[1] indicates the alignment
382          * of state component i when the compacted format
383          * of the extended region of an XSAVE area is used
384          */
385         return !!(ecx & 2);
386 }
387
388 static int xfeature_uncompacted_offset(int xfeature_nr)
389 {
390         u32 eax, ebx, ecx, edx;
391
392         CHECK_XFEATURE(xfeature_nr);
393         cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
394         return ebx;
395 }
396
397 static int xfeature_size(int xfeature_nr)
398 {
399         u32 eax, ebx, ecx, edx;
400
401         CHECK_XFEATURE(xfeature_nr);
402         cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
403         return eax;
404 }
405
406 /*
407  * 'XSAVES' implies two different things:
408  * 1. saving of supervisor/system state
409  * 2. using the compacted format
410  *
411  * Use this function when dealing with the compacted format so
412  * that it is obvious which aspect of 'XSAVES' is being handled
413  * by the calling code.
414  */
415 static int using_compacted_format(void)
416 {
417         return cpu_has_xsaves;
418 }
419
420 static void __xstate_dump_leaves(void)
421 {
422         int i;
423         u32 eax, ebx, ecx, edx;
424         static int should_dump = 1;
425
426         if (!should_dump)
427                 return;
428         should_dump = 0;
429         /*
430          * Dump out a few leaves past the ones that we support
431          * just in case there are some goodies up there
432          */
433         for (i = 0; i < XFEATURE_MAX + 10; i++) {
434                 cpuid_count(XSTATE_CPUID, i, &eax, &ebx, &ecx, &edx);
435                 pr_warn("CPUID[%02x, %02x]: eax=%08x ebx=%08x ecx=%08x edx=%08x\n",
436                         XSTATE_CPUID, i, eax, ebx, ecx, edx);
437         }
438 }
439
440 #define XSTATE_WARN_ON(x) do {                                                  \
441         if (WARN_ONCE(x, "XSAVE consistency problem, dumping leaves")) {        \
442                 __xstate_dump_leaves();                                         \
443         }                                                                       \
444 } while (0)
445
446 #define XCHECK_SZ(sz, nr, nr_macro, __struct) do {                      \
447         if ((nr == nr_macro) &&                                         \
448             WARN_ONCE(sz != sizeof(__struct),                           \
449                 "%s: struct is %zu bytes, cpu state %d bytes\n",        \
450                 __stringify(nr_macro), sizeof(__struct), sz)) {         \
451                 __xstate_dump_leaves();                                 \
452         }                                                               \
453 } while (0)
454
455 /*
456  * We have a C struct for each 'xstate'.  We need to ensure
457  * that our software representation matches what the CPU
458  * tells us about the state's size.
459  */
460 static void check_xstate_against_struct(int nr)
461 {
462         /*
463          * Ask the CPU for the size of the state.
464          */
465         int sz = xfeature_size(nr);
466         /*
467          * Match each CPU state with the corresponding software
468          * structure.
469          */
470         XCHECK_SZ(sz, nr, XFEATURE_YMM,       struct ymmh_struct);
471         XCHECK_SZ(sz, nr, XFEATURE_BNDREGS,   struct mpx_bndreg_state);
472         XCHECK_SZ(sz, nr, XFEATURE_BNDCSR,    struct mpx_bndcsr_state);
473         XCHECK_SZ(sz, nr, XFEATURE_OPMASK,    struct avx_512_opmask_state);
474         XCHECK_SZ(sz, nr, XFEATURE_ZMM_Hi256, struct avx_512_zmm_uppers_state);
475         XCHECK_SZ(sz, nr, XFEATURE_Hi16_ZMM,  struct avx_512_hi16_state);
476         XCHECK_SZ(sz, nr, XFEATURE_PKRU,      struct pkru_state);
477
478         /*
479          * Make *SURE* to add any feature numbers in below if
480          * there are "holes" in the xsave state component
481          * numbers.
482          */
483         if ((nr < XFEATURE_YMM) ||
484             (nr >= XFEATURE_MAX) ||
485             (nr == XFEATURE_PT_UNIMPLEMENTED_SO_FAR)) {
486                 WARN_ONCE(1, "no structure for xstate: %d\n", nr);
487                 XSTATE_WARN_ON(1);
488         }
489 }
490
491 /*
492  * This essentially double-checks what the cpu told us about
493  * how large the XSAVE buffer needs to be.  We are recalculating
494  * it to be safe.
495  */
496 static void do_extra_xstate_size_checks(void)
497 {
498         int paranoid_xstate_size = FXSAVE_SIZE + XSAVE_HDR_SIZE;
499         int i;
500
501         for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
502                 if (!xfeature_enabled(i))
503                         continue;
504
505                 check_xstate_against_struct(i);
506                 /*
507                  * Supervisor state components can be managed only by
508                  * XSAVES, which is compacted-format only.
509                  */
510                 if (!using_compacted_format())
511                         XSTATE_WARN_ON(xfeature_is_supervisor(i));
512
513                 /* Align from the end of the previous feature */
514                 if (xfeature_is_aligned(i))
515                         paranoid_xstate_size = ALIGN(paranoid_xstate_size, 64);
516                 /*
517                  * The offset of a given state in the non-compacted
518                  * format is given to us in a CPUID leaf.  We check
519                  * them for being ordered (increasing offsets) in
520                  * setup_xstate_features().
521                  */
522                 if (!using_compacted_format())
523                         paranoid_xstate_size = xfeature_uncompacted_offset(i);
524                 /*
525                  * The compacted-format offset always depends on where
526                  * the previous state ended.
527                  */
528                 paranoid_xstate_size += xfeature_size(i);
529         }
530         XSTATE_WARN_ON(paranoid_xstate_size != xstate_size);
531 }
532
533 /*
534  * Calculate total size of enabled xstates in XCR0/xfeatures_mask.
535  *
536  * Note the SDM's wording here.  "sub-function 0" only enumerates
537  * the size of the *user* states.  If we use it to size a buffer
538  * that we use 'XSAVES' on, we could potentially overflow the
539  * buffer because 'XSAVES' saves system states too.
540  *
541  * Note that we do not currently set any bits on IA32_XSS so
542  * 'XCR0 | IA32_XSS == XCR0' for now.
543  */
544 static unsigned int __init calculate_xstate_size(void)
545 {
546         unsigned int eax, ebx, ecx, edx;
547         unsigned int calculated_xstate_size;
548
549         if (!cpu_has_xsaves) {
550                 /*
551                  * - CPUID function 0DH, sub-function 0:
552                  *    EBX enumerates the size (in bytes) required by
553                  *    the XSAVE instruction for an XSAVE area
554                  *    containing all the *user* state components
555                  *    corresponding to bits currently set in XCR0.
556                  */
557                 cpuid_count(XSTATE_CPUID, 0, &eax, &ebx, &ecx, &edx);
558                 calculated_xstate_size = ebx;
559         } else {
560                 /*
561                  * - CPUID function 0DH, sub-function 1:
562                  *    EBX enumerates the size (in bytes) required by
563                  *    the XSAVES instruction for an XSAVE area
564                  *    containing all the state components
565                  *    corresponding to bits currently set in
566                  *    XCR0 | IA32_XSS.
567                  */
568                 cpuid_count(XSTATE_CPUID, 1, &eax, &ebx, &ecx, &edx);
569                 calculated_xstate_size = ebx;
570         }
571         return calculated_xstate_size;
572 }
573
574 /*
575  * Will the runtime-enumerated 'xstate_size' fit in the init
576  * task's statically-allocated buffer?
577  */
578 static bool is_supported_xstate_size(unsigned int test_xstate_size)
579 {
580         if (test_xstate_size <= sizeof(union fpregs_state))
581                 return true;
582
583         pr_warn("x86/fpu: xstate buffer too small (%zu < %d), disabling xsave\n",
584                         sizeof(union fpregs_state), test_xstate_size);
585         return false;
586 }
587
588 static int init_xstate_size(void)
589 {
590         /* Recompute the context size for enabled features: */
591         unsigned int possible_xstate_size = calculate_xstate_size();
592
593         /* Ensure we have the space to store all enabled: */
594         if (!is_supported_xstate_size(possible_xstate_size))
595                 return -EINVAL;
596
597         /*
598          * The size is OK, we are definitely going to use xsave,
599          * make it known to the world that we need more space.
600          */
601         xstate_size = possible_xstate_size;
602         do_extra_xstate_size_checks();
603         return 0;
604 }
605
606 /*
607  * We enabled the XSAVE hardware, but something went wrong and
608  * we can not use it.  Disable it.
609  */
610 static void fpu__init_disable_system_xstate(void)
611 {
612         xfeatures_mask = 0;
613         cr4_clear_bits(X86_CR4_OSXSAVE);
614         fpu__xstate_clear_all_cpu_caps();
615 }
616
617 /*
618  * Enable and initialize the xsave feature.
619  * Called once per system bootup.
620  */
621 void __init fpu__init_system_xstate(void)
622 {
623         unsigned int eax, ebx, ecx, edx;
624         static int on_boot_cpu __initdata = 1;
625         int err;
626
627         WARN_ON_FPU(!on_boot_cpu);
628         on_boot_cpu = 0;
629
630         if (!cpu_has_xsave) {
631                 pr_info("x86/fpu: Legacy x87 FPU detected.\n");
632                 return;
633         }
634
635         if (boot_cpu_data.cpuid_level < XSTATE_CPUID) {
636                 WARN_ON_FPU(1);
637                 return;
638         }
639
640         cpuid_count(XSTATE_CPUID, 0, &eax, &ebx, &ecx, &edx);
641         xfeatures_mask = eax + ((u64)edx << 32);
642
643         if ((xfeatures_mask & XFEATURE_MASK_FPSSE) != XFEATURE_MASK_FPSSE) {
644                 pr_err("x86/fpu: FP/SSE not present amongst the CPU's xstate features: 0x%llx.\n", xfeatures_mask);
645                 BUG();
646         }
647
648         xfeatures_mask &= fpu__get_supported_xfeatures_mask();
649
650         /* Enable xstate instructions to be able to continue with initialization: */
651         fpu__init_cpu_xstate();
652         err = init_xstate_size();
653         if (err) {
654                 /* something went wrong, boot without any XSAVE support */
655                 fpu__init_disable_system_xstate();
656                 return;
657         }
658
659         update_regset_xstate_info(xstate_size, xfeatures_mask);
660         fpu__init_prepare_fx_sw_frame();
661         setup_init_fpu_buf();
662         setup_xstate_comp();
663
664         pr_info("x86/fpu: Enabled xstate features 0x%llx, context size is %d bytes, using '%s' format.\n",
665                 xfeatures_mask,
666                 xstate_size,
667                 cpu_has_xsaves ? "compacted" : "standard");
668 }
669
670 /*
671  * Restore minimal FPU state after suspend:
672  */
673 void fpu__resume_cpu(void)
674 {
675         /*
676          * Restore XCR0 on xsave capable CPUs:
677          */
678         if (cpu_has_xsave)
679                 xsetbv(XCR_XFEATURE_ENABLED_MASK, xfeatures_mask);
680 }
681
682 /*
683  * Given an xstate feature mask, calculate where in the xsave
684  * buffer the state is.  Callers should ensure that the buffer
685  * is valid.
686  *
687  * Note: does not work for compacted buffers.
688  */
689 void *__raw_xsave_addr(struct xregs_state *xsave, int xstate_feature_mask)
690 {
691         int feature_nr = fls64(xstate_feature_mask) - 1;
692
693         return (void *)xsave + xstate_comp_offsets[feature_nr];
694 }
695 /*
696  * Given the xsave area and a state inside, this function returns the
697  * address of the state.
698  *
699  * This is the API that is called to get xstate address in either
700  * standard format or compacted format of xsave area.
701  *
702  * Note that if there is no data for the field in the xsave buffer
703  * this will return NULL.
704  *
705  * Inputs:
706  *      xstate: the thread's storage area for all FPU data
707  *      xstate_feature: state which is defined in xsave.h (e.g.
708  *      XFEATURE_MASK_FP, XFEATURE_MASK_SSE, etc...)
709  * Output:
710  *      address of the state in the xsave area, or NULL if the
711  *      field is not present in the xsave buffer.
712  */
713 void *get_xsave_addr(struct xregs_state *xsave, int xstate_feature)
714 {
715         /*
716          * Do we even *have* xsave state?
717          */
718         if (!boot_cpu_has(X86_FEATURE_XSAVE))
719                 return NULL;
720
721         /*
722          * We should not ever be requesting features that we
723          * have not enabled.  Remember that pcntxt_mask is
724          * what we write to the XCR0 register.
725          */
726         WARN_ONCE(!(xfeatures_mask & xstate_feature),
727                   "get of unsupported state");
728         /*
729          * This assumes the last 'xsave*' instruction to
730          * have requested that 'xstate_feature' be saved.
731          * If it did not, we might be seeing and old value
732          * of the field in the buffer.
733          *
734          * This can happen because the last 'xsave' did not
735          * request that this feature be saved (unlikely)
736          * or because the "init optimization" caused it
737          * to not be saved.
738          */
739         if (!(xsave->header.xfeatures & xstate_feature))
740                 return NULL;
741
742         return __raw_xsave_addr(xsave, xstate_feature);
743 }
744 EXPORT_SYMBOL_GPL(get_xsave_addr);
745
746 /*
747  * This wraps up the common operations that need to occur when retrieving
748  * data from xsave state.  It first ensures that the current task was
749  * using the FPU and retrieves the data in to a buffer.  It then calculates
750  * the offset of the requested field in the buffer.
751  *
752  * This function is safe to call whether the FPU is in use or not.
753  *
754  * Note that this only works on the current task.
755  *
756  * Inputs:
757  *      @xsave_state: state which is defined in xsave.h (e.g. XFEATURE_MASK_FP,
758  *      XFEATURE_MASK_SSE, etc...)
759  * Output:
760  *      address of the state in the xsave area or NULL if the state
761  *      is not present or is in its 'init state'.
762  */
763 const void *get_xsave_field_ptr(int xsave_state)
764 {
765         struct fpu *fpu = &current->thread.fpu;
766
767         if (!fpu->fpstate_active)
768                 return NULL;
769         /*
770          * fpu__save() takes the CPU's xstate registers
771          * and saves them off to the 'fpu memory buffer.
772          */
773         fpu__save(fpu);
774
775         return get_xsave_addr(&fpu->state.xsave, xsave_state);
776 }
777
778
779 /*
780  * Set xfeatures (aka XSTATE_BV) bit for a feature that we want
781  * to take out of its "init state".  This will ensure that an
782  * XRSTOR actually restores the state.
783  */
784 static void fpu__xfeature_set_non_init(struct xregs_state *xsave,
785                 int xstate_feature_mask)
786 {
787         xsave->header.xfeatures |= xstate_feature_mask;
788 }
789
790 /*
791  * This function is safe to call whether the FPU is in use or not.
792  *
793  * Note that this only works on the current task.
794  *
795  * Inputs:
796  *      @xsave_state: state which is defined in xsave.h (e.g. XFEATURE_MASK_FP,
797  *      XFEATURE_MASK_SSE, etc...)
798  *      @xsave_state_ptr: a pointer to a copy of the state that you would
799  *      like written in to the current task's FPU xsave state.  This pointer
800  *      must not be located in the current tasks's xsave area.
801  * Output:
802  *      address of the state in the xsave area or NULL if the state
803  *      is not present or is in its 'init state'.
804  */
805 static void fpu__xfeature_set_state(int xstate_feature_mask,
806                 void *xstate_feature_src, size_t len)
807 {
808         struct xregs_state *xsave = &current->thread.fpu.state.xsave;
809         struct fpu *fpu = &current->thread.fpu;
810         void *dst;
811
812         if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
813                 WARN_ONCE(1, "%s() attempted with no xsave support", __func__);
814                 return;
815         }
816
817         /*
818          * Tell the FPU code that we need the FPU state to be in
819          * 'fpu' (not in the registers), and that we need it to
820          * be stable while we write to it.
821          */
822         fpu__current_fpstate_write_begin();
823
824         /*
825          * This method *WILL* *NOT* work for compact-format
826          * buffers.  If the 'xstate_feature_mask' is unset in
827          * xcomp_bv then we may need to move other feature state
828          * "up" in the buffer.
829          */
830         if (xsave->header.xcomp_bv & xstate_feature_mask) {
831                 WARN_ON_ONCE(1);
832                 goto out;
833         }
834
835         /* find the location in the xsave buffer of the desired state */
836         dst = __raw_xsave_addr(&fpu->state.xsave, xstate_feature_mask);
837
838         /*
839          * Make sure that the pointer being passed in did not
840          * come from the xsave buffer itself.
841          */
842         WARN_ONCE(xstate_feature_src == dst, "set from xsave buffer itself");
843
844         /* put the caller-provided data in the location */
845         memcpy(dst, xstate_feature_src, len);
846
847         /*
848          * Mark the xfeature so that the CPU knows there is state
849          * in the buffer now.
850          */
851         fpu__xfeature_set_non_init(xsave, xstate_feature_mask);
852 out:
853         /*
854          * We are done writing to the 'fpu'.  Reenable preeption
855          * and (possibly) move the fpstate back in to the fpregs.
856          */
857         fpu__current_fpstate_write_end();
858 }
859
860 #define NR_VALID_PKRU_BITS (CONFIG_NR_PROTECTION_KEYS * 2)
861 #define PKRU_VALID_MASK (NR_VALID_PKRU_BITS - 1)
862
863 /*
864  * This will go out and modify the XSAVE buffer so that PKRU is
865  * set to a particular state for access to 'pkey'.
866  *
867  * PKRU state does affect kernel access to user memory.  We do
868  * not modfiy PKRU *itself* here, only the XSAVE state that will
869  * be restored in to PKRU when we return back to userspace.
870  */
871 int arch_set_user_pkey_access(struct task_struct *tsk, int pkey,
872                 unsigned long init_val)
873 {
874         struct xregs_state *xsave = &tsk->thread.fpu.state.xsave;
875         struct pkru_state *old_pkru_state;
876         struct pkru_state new_pkru_state;
877         int pkey_shift = (pkey * PKRU_BITS_PER_PKEY);
878         u32 new_pkru_bits = 0;
879
880         /*
881          * This check implies XSAVE support.  OSPKE only gets
882          * set if we enable XSAVE and we enable PKU in XCR0.
883          */
884         if (!boot_cpu_has(X86_FEATURE_OSPKE))
885                 return -EINVAL;
886
887         /* Set the bits we need in PKRU  */
888         if (init_val & PKEY_DISABLE_ACCESS)
889                 new_pkru_bits |= PKRU_AD_BIT;
890         if (init_val & PKEY_DISABLE_WRITE)
891                 new_pkru_bits |= PKRU_WD_BIT;
892
893         /* Shift the bits in to the correct place in PKRU for pkey. */
894         new_pkru_bits <<= pkey_shift;
895
896         /* Locate old copy of the state in the xsave buffer */
897         old_pkru_state = get_xsave_addr(xsave, XFEATURE_MASK_PKRU);
898
899         /*
900          * When state is not in the buffer, it is in the init
901          * state, set it manually.  Otherwise, copy out the old
902          * state.
903          */
904         if (!old_pkru_state)
905                 new_pkru_state.pkru = 0;
906         else
907                 new_pkru_state.pkru = old_pkru_state->pkru;
908
909         /* mask off any old bits in place */
910         new_pkru_state.pkru &= ~((PKRU_AD_BIT|PKRU_WD_BIT) << pkey_shift);
911         /* Set the newly-requested bits */
912         new_pkru_state.pkru |= new_pkru_bits;
913
914         /*
915          * We could theoretically live without zeroing pkru.pad.
916          * The current XSAVE feature state definition says that
917          * only bytes 0->3 are used.  But we do not want to
918          * chance leaking kernel stack out to userspace in case a
919          * memcpy() of the whole xsave buffer was done.
920          *
921          * They're in the same cacheline anyway.
922          */
923         new_pkru_state.pad = 0;
924
925         fpu__xfeature_set_state(XFEATURE_MASK_PKRU, &new_pkru_state,
926                         sizeof(new_pkru_state));
927
928         return 0;
929 }