xref: /openbmc/linux/arch/x86/kernel/fpu/xstate.c (revision 2874c5fd)
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 
12 #include <asm/fpu/api.h>
13 #include <asm/fpu/internal.h>
14 #include <asm/fpu/signal.h>
15 #include <asm/fpu/regset.h>
16 #include <asm/fpu/xstate.h>
17 
18 #include <asm/tlbflush.h>
19 #include <asm/cpufeature.h>
20 
21 /*
22  * Although we spell it out in here, the Processor Trace
23  * xfeature is completely unused.  We use other mechanisms
24  * to save/restore PT state in Linux.
25  */
26 static const char *xfeature_names[] =
27 {
28 	"x87 floating point registers"	,
29 	"SSE registers"			,
30 	"AVX registers"			,
31 	"MPX bounds registers"		,
32 	"MPX CSR"			,
33 	"AVX-512 opmask"		,
34 	"AVX-512 Hi256"			,
35 	"AVX-512 ZMM_Hi256"		,
36 	"Processor Trace (unused)"	,
37 	"Protection Keys User registers",
38 	"unknown xstate feature"	,
39 };
40 
41 static short xsave_cpuid_features[] __initdata = {
42 	X86_FEATURE_FPU,
43 	X86_FEATURE_XMM,
44 	X86_FEATURE_AVX,
45 	X86_FEATURE_MPX,
46 	X86_FEATURE_MPX,
47 	X86_FEATURE_AVX512F,
48 	X86_FEATURE_AVX512F,
49 	X86_FEATURE_AVX512F,
50 	X86_FEATURE_INTEL_PT,
51 	X86_FEATURE_PKU,
52 };
53 
54 /*
55  * Mask of xstate features supported by the CPU and the kernel:
56  */
57 u64 xfeatures_mask __read_mostly;
58 
59 static unsigned int xstate_offsets[XFEATURE_MAX] = { [ 0 ... XFEATURE_MAX - 1] = -1};
60 static unsigned int xstate_sizes[XFEATURE_MAX]   = { [ 0 ... XFEATURE_MAX - 1] = -1};
61 static unsigned int xstate_comp_offsets[sizeof(xfeatures_mask)*8];
62 
63 /*
64  * The XSAVE area of kernel can be in standard or compacted format;
65  * it is always in standard format for user mode. This is the user
66  * mode standard format size used for signal and ptrace frames.
67  */
68 unsigned int fpu_user_xstate_size;
69 
70 /*
71  * Clear all of the X86_FEATURE_* bits that are unavailable
72  * when the CPU has no XSAVE support.
73  */
74 void fpu__xstate_clear_all_cpu_caps(void)
75 {
76 	setup_clear_cpu_cap(X86_FEATURE_XSAVE);
77 }
78 
79 /*
80  * Return whether the system supports a given xfeature.
81  *
82  * Also return the name of the (most advanced) feature that the caller requested:
83  */
84 int cpu_has_xfeatures(u64 xfeatures_needed, const char **feature_name)
85 {
86 	u64 xfeatures_missing = xfeatures_needed & ~xfeatures_mask;
87 
88 	if (unlikely(feature_name)) {
89 		long xfeature_idx, max_idx;
90 		u64 xfeatures_print;
91 		/*
92 		 * So we use FLS here to be able to print the most advanced
93 		 * feature that was requested but is missing. So if a driver
94 		 * asks about "XFEATURE_MASK_SSE | XFEATURE_MASK_YMM" we'll print the
95 		 * missing AVX feature - this is the most informative message
96 		 * to users:
97 		 */
98 		if (xfeatures_missing)
99 			xfeatures_print = xfeatures_missing;
100 		else
101 			xfeatures_print = xfeatures_needed;
102 
103 		xfeature_idx = fls64(xfeatures_print)-1;
104 		max_idx = ARRAY_SIZE(xfeature_names)-1;
105 		xfeature_idx = min(xfeature_idx, max_idx);
106 
107 		*feature_name = xfeature_names[xfeature_idx];
108 	}
109 
110 	if (xfeatures_missing)
111 		return 0;
112 
113 	return 1;
114 }
115 EXPORT_SYMBOL_GPL(cpu_has_xfeatures);
116 
117 static int xfeature_is_supervisor(int xfeature_nr)
118 {
119 	/*
120 	 * We currently do not support supervisor states, but if
121 	 * we did, we could find out like this.
122 	 *
123 	 * SDM says: If state component 'i' is a user state component,
124 	 * ECX[0] return 0; if state component i is a supervisor
125 	 * state component, ECX[0] returns 1.
126 	 */
127 	u32 eax, ebx, ecx, edx;
128 
129 	cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
130 	return !!(ecx & 1);
131 }
132 
133 static int xfeature_is_user(int xfeature_nr)
134 {
135 	return !xfeature_is_supervisor(xfeature_nr);
136 }
137 
138 /*
139  * When executing XSAVEOPT (or other optimized XSAVE instructions), if
140  * a processor implementation detects that an FPU state component is still
141  * (or is again) in its initialized state, it may clear the corresponding
142  * bit in the header.xfeatures field, and can skip the writeout of registers
143  * to the corresponding memory layout.
144  *
145  * This means that when the bit is zero, the state component might still contain
146  * some previous - non-initialized register state.
147  *
148  * Before writing xstate information to user-space we sanitize those components,
149  * to always ensure that the memory layout of a feature will be in the init state
150  * if the corresponding header bit is zero. This is to ensure that user-space doesn't
151  * see some stale state in the memory layout during signal handling, debugging etc.
152  */
153 void fpstate_sanitize_xstate(struct fpu *fpu)
154 {
155 	struct fxregs_state *fx = &fpu->state.fxsave;
156 	int feature_bit;
157 	u64 xfeatures;
158 
159 	if (!use_xsaveopt())
160 		return;
161 
162 	xfeatures = fpu->state.xsave.header.xfeatures;
163 
164 	/*
165 	 * None of the feature bits are in init state. So nothing else
166 	 * to do for us, as the memory layout is up to date.
167 	 */
168 	if ((xfeatures & xfeatures_mask) == xfeatures_mask)
169 		return;
170 
171 	/*
172 	 * FP is in init state
173 	 */
174 	if (!(xfeatures & XFEATURE_MASK_FP)) {
175 		fx->cwd = 0x37f;
176 		fx->swd = 0;
177 		fx->twd = 0;
178 		fx->fop = 0;
179 		fx->rip = 0;
180 		fx->rdp = 0;
181 		memset(&fx->st_space[0], 0, 128);
182 	}
183 
184 	/*
185 	 * SSE is in init state
186 	 */
187 	if (!(xfeatures & XFEATURE_MASK_SSE))
188 		memset(&fx->xmm_space[0], 0, 256);
189 
190 	/*
191 	 * First two features are FPU and SSE, which above we handled
192 	 * in a special way already:
193 	 */
194 	feature_bit = 0x2;
195 	xfeatures = (xfeatures_mask & ~xfeatures) >> 2;
196 
197 	/*
198 	 * Update all the remaining memory layouts according to their
199 	 * standard xstate layout, if their header bit is in the init
200 	 * state:
201 	 */
202 	while (xfeatures) {
203 		if (xfeatures & 0x1) {
204 			int offset = xstate_comp_offsets[feature_bit];
205 			int size = xstate_sizes[feature_bit];
206 
207 			memcpy((void *)fx + offset,
208 			       (void *)&init_fpstate.xsave + offset,
209 			       size);
210 		}
211 
212 		xfeatures >>= 1;
213 		feature_bit++;
214 	}
215 }
216 
217 /*
218  * Enable the extended processor state save/restore feature.
219  * Called once per CPU onlining.
220  */
221 void fpu__init_cpu_xstate(void)
222 {
223 	if (!boot_cpu_has(X86_FEATURE_XSAVE) || !xfeatures_mask)
224 		return;
225 	/*
226 	 * Make it clear that XSAVES supervisor states are not yet
227 	 * implemented should anyone expect it to work by changing
228 	 * bits in XFEATURE_MASK_* macros and XCR0.
229 	 */
230 	WARN_ONCE((xfeatures_mask & XFEATURE_MASK_SUPERVISOR),
231 		"x86/fpu: XSAVES supervisor states are not yet implemented.\n");
232 
233 	xfeatures_mask &= ~XFEATURE_MASK_SUPERVISOR;
234 
235 	cr4_set_bits(X86_CR4_OSXSAVE);
236 	xsetbv(XCR_XFEATURE_ENABLED_MASK, xfeatures_mask);
237 }
238 
239 /*
240  * Note that in the future we will likely need a pair of
241  * functions here: one for user xstates and the other for
242  * system xstates.  For now, they are the same.
243  */
244 static int xfeature_enabled(enum xfeature xfeature)
245 {
246 	return !!(xfeatures_mask & (1UL << xfeature));
247 }
248 
249 /*
250  * Record the offsets and sizes of various xstates contained
251  * in the XSAVE state memory layout.
252  */
253 static void __init setup_xstate_features(void)
254 {
255 	u32 eax, ebx, ecx, edx, i;
256 	/* start at the beginnning of the "extended state" */
257 	unsigned int last_good_offset = offsetof(struct xregs_state,
258 						 extended_state_area);
259 	/*
260 	 * The FP xstates and SSE xstates are legacy states. They are always
261 	 * in the fixed offsets in the xsave area in either compacted form
262 	 * or standard form.
263 	 */
264 	xstate_offsets[0] = 0;
265 	xstate_sizes[0] = offsetof(struct fxregs_state, xmm_space);
266 	xstate_offsets[1] = xstate_sizes[0];
267 	xstate_sizes[1] = FIELD_SIZEOF(struct fxregs_state, xmm_space);
268 
269 	for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
270 		if (!xfeature_enabled(i))
271 			continue;
272 
273 		cpuid_count(XSTATE_CPUID, i, &eax, &ebx, &ecx, &edx);
274 
275 		/*
276 		 * If an xfeature is supervisor state, the offset
277 		 * in EBX is invalid. We leave it to -1.
278 		 */
279 		if (xfeature_is_user(i))
280 			xstate_offsets[i] = ebx;
281 
282 		xstate_sizes[i] = eax;
283 		/*
284 		 * In our xstate size checks, we assume that the
285 		 * highest-numbered xstate feature has the
286 		 * highest offset in the buffer.  Ensure it does.
287 		 */
288 		WARN_ONCE(last_good_offset > xstate_offsets[i],
289 			"x86/fpu: misordered xstate at %d\n", last_good_offset);
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 }
317 
318 /*
319  * This check is important because it is easy to get XSTATE_*
320  * confused with XSTATE_BIT_*.
321  */
322 #define CHECK_XFEATURE(nr) do {		\
323 	WARN_ON(nr < FIRST_EXTENDED_XFEATURE);	\
324 	WARN_ON(nr >= XFEATURE_MAX);	\
325 } while (0)
326 
327 /*
328  * We could cache this like xstate_size[], but we only use
329  * it here, so it would be a waste of space.
330  */
331 static int xfeature_is_aligned(int xfeature_nr)
332 {
333 	u32 eax, ebx, ecx, edx;
334 
335 	CHECK_XFEATURE(xfeature_nr);
336 	cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
337 	/*
338 	 * The value returned by ECX[1] indicates the alignment
339 	 * of state component 'i' when the compacted format
340 	 * of the extended region of an XSAVE area is used:
341 	 */
342 	return !!(ecx & 2);
343 }
344 
345 /*
346  * This function sets up offsets and sizes of all extended states in
347  * xsave area. This supports both standard format and compacted format
348  * of the xsave aread.
349  */
350 static void __init setup_xstate_comp(void)
351 {
352 	unsigned int xstate_comp_sizes[sizeof(xfeatures_mask)*8];
353 	int i;
354 
355 	/*
356 	 * The FP xstates and SSE xstates are legacy states. They are always
357 	 * in the fixed offsets in the xsave area in either compacted form
358 	 * or standard form.
359 	 */
360 	xstate_comp_offsets[0] = 0;
361 	xstate_comp_offsets[1] = offsetof(struct fxregs_state, xmm_space);
362 
363 	if (!boot_cpu_has(X86_FEATURE_XSAVES)) {
364 		for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
365 			if (xfeature_enabled(i)) {
366 				xstate_comp_offsets[i] = xstate_offsets[i];
367 				xstate_comp_sizes[i] = xstate_sizes[i];
368 			}
369 		}
370 		return;
371 	}
372 
373 	xstate_comp_offsets[FIRST_EXTENDED_XFEATURE] =
374 		FXSAVE_SIZE + XSAVE_HDR_SIZE;
375 
376 	for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
377 		if (xfeature_enabled(i))
378 			xstate_comp_sizes[i] = xstate_sizes[i];
379 		else
380 			xstate_comp_sizes[i] = 0;
381 
382 		if (i > FIRST_EXTENDED_XFEATURE) {
383 			xstate_comp_offsets[i] = xstate_comp_offsets[i-1]
384 					+ xstate_comp_sizes[i-1];
385 
386 			if (xfeature_is_aligned(i))
387 				xstate_comp_offsets[i] =
388 					ALIGN(xstate_comp_offsets[i], 64);
389 		}
390 	}
391 }
392 
393 /*
394  * Print out xstate component offsets and sizes
395  */
396 static void __init print_xstate_offset_size(void)
397 {
398 	int i;
399 
400 	for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
401 		if (!xfeature_enabled(i))
402 			continue;
403 		pr_info("x86/fpu: xstate_offset[%d]: %4d, xstate_sizes[%d]: %4d\n",
404 			 i, xstate_comp_offsets[i], i, xstate_sizes[i]);
405 	}
406 }
407 
408 /*
409  * setup the xstate image representing the init state
410  */
411 static void __init setup_init_fpu_buf(void)
412 {
413 	static int on_boot_cpu __initdata = 1;
414 
415 	WARN_ON_FPU(!on_boot_cpu);
416 	on_boot_cpu = 0;
417 
418 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
419 		return;
420 
421 	setup_xstate_features();
422 	print_xstate_features();
423 
424 	if (boot_cpu_has(X86_FEATURE_XSAVES))
425 		init_fpstate.xsave.header.xcomp_bv = (u64)1 << 63 | xfeatures_mask;
426 
427 	/*
428 	 * Init all the features state with header.xfeatures being 0x0
429 	 */
430 	copy_kernel_to_xregs_booting(&init_fpstate.xsave);
431 
432 	/*
433 	 * Dump the init state again. This is to identify the init state
434 	 * of any feature which is not represented by all zero's.
435 	 */
436 	copy_xregs_to_kernel_booting(&init_fpstate.xsave);
437 }
438 
439 static int xfeature_uncompacted_offset(int xfeature_nr)
440 {
441 	u32 eax, ebx, ecx, edx;
442 
443 	/*
444 	 * Only XSAVES supports supervisor states and it uses compacted
445 	 * format. Checking a supervisor state's uncompacted offset is
446 	 * an error.
447 	 */
448 	if (XFEATURE_MASK_SUPERVISOR & BIT_ULL(xfeature_nr)) {
449 		WARN_ONCE(1, "No fixed offset for xstate %d\n", xfeature_nr);
450 		return -1;
451 	}
452 
453 	CHECK_XFEATURE(xfeature_nr);
454 	cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
455 	return ebx;
456 }
457 
458 static int xfeature_size(int xfeature_nr)
459 {
460 	u32 eax, ebx, ecx, edx;
461 
462 	CHECK_XFEATURE(xfeature_nr);
463 	cpuid_count(XSTATE_CPUID, xfeature_nr, &eax, &ebx, &ecx, &edx);
464 	return eax;
465 }
466 
467 /*
468  * 'XSAVES' implies two different things:
469  * 1. saving of supervisor/system state
470  * 2. using the compacted format
471  *
472  * Use this function when dealing with the compacted format so
473  * that it is obvious which aspect of 'XSAVES' is being handled
474  * by the calling code.
475  */
476 int using_compacted_format(void)
477 {
478 	return boot_cpu_has(X86_FEATURE_XSAVES);
479 }
480 
481 /* Validate an xstate header supplied by userspace (ptrace or sigreturn) */
482 int validate_xstate_header(const struct xstate_header *hdr)
483 {
484 	/* No unknown or supervisor features may be set */
485 	if (hdr->xfeatures & (~xfeatures_mask | XFEATURE_MASK_SUPERVISOR))
486 		return -EINVAL;
487 
488 	/* Userspace must use the uncompacted format */
489 	if (hdr->xcomp_bv)
490 		return -EINVAL;
491 
492 	/*
493 	 * If 'reserved' is shrunken to add a new field, make sure to validate
494 	 * that new field here!
495 	 */
496 	BUILD_BUG_ON(sizeof(hdr->reserved) != 48);
497 
498 	/* No reserved bits may be set */
499 	if (memchr_inv(hdr->reserved, 0, sizeof(hdr->reserved)))
500 		return -EINVAL;
501 
502 	return 0;
503 }
504 
505 static void __xstate_dump_leaves(void)
506 {
507 	int i;
508 	u32 eax, ebx, ecx, edx;
509 	static int should_dump = 1;
510 
511 	if (!should_dump)
512 		return;
513 	should_dump = 0;
514 	/*
515 	 * Dump out a few leaves past the ones that we support
516 	 * just in case there are some goodies up there
517 	 */
518 	for (i = 0; i < XFEATURE_MAX + 10; i++) {
519 		cpuid_count(XSTATE_CPUID, i, &eax, &ebx, &ecx, &edx);
520 		pr_warn("CPUID[%02x, %02x]: eax=%08x ebx=%08x ecx=%08x edx=%08x\n",
521 			XSTATE_CPUID, i, eax, ebx, ecx, edx);
522 	}
523 }
524 
525 #define XSTATE_WARN_ON(x) do {							\
526 	if (WARN_ONCE(x, "XSAVE consistency problem, dumping leaves")) {	\
527 		__xstate_dump_leaves();						\
528 	}									\
529 } while (0)
530 
531 #define XCHECK_SZ(sz, nr, nr_macro, __struct) do {			\
532 	if ((nr == nr_macro) &&						\
533 	    WARN_ONCE(sz != sizeof(__struct),				\
534 		"%s: struct is %zu bytes, cpu state %d bytes\n",	\
535 		__stringify(nr_macro), sizeof(__struct), sz)) {		\
536 		__xstate_dump_leaves();					\
537 	}								\
538 } while (0)
539 
540 /*
541  * We have a C struct for each 'xstate'.  We need to ensure
542  * that our software representation matches what the CPU
543  * tells us about the state's size.
544  */
545 static void check_xstate_against_struct(int nr)
546 {
547 	/*
548 	 * Ask the CPU for the size of the state.
549 	 */
550 	int sz = xfeature_size(nr);
551 	/*
552 	 * Match each CPU state with the corresponding software
553 	 * structure.
554 	 */
555 	XCHECK_SZ(sz, nr, XFEATURE_YMM,       struct ymmh_struct);
556 	XCHECK_SZ(sz, nr, XFEATURE_BNDREGS,   struct mpx_bndreg_state);
557 	XCHECK_SZ(sz, nr, XFEATURE_BNDCSR,    struct mpx_bndcsr_state);
558 	XCHECK_SZ(sz, nr, XFEATURE_OPMASK,    struct avx_512_opmask_state);
559 	XCHECK_SZ(sz, nr, XFEATURE_ZMM_Hi256, struct avx_512_zmm_uppers_state);
560 	XCHECK_SZ(sz, nr, XFEATURE_Hi16_ZMM,  struct avx_512_hi16_state);
561 	XCHECK_SZ(sz, nr, XFEATURE_PKRU,      struct pkru_state);
562 
563 	/*
564 	 * Make *SURE* to add any feature numbers in below if
565 	 * there are "holes" in the xsave state component
566 	 * numbers.
567 	 */
568 	if ((nr < XFEATURE_YMM) ||
569 	    (nr >= XFEATURE_MAX) ||
570 	    (nr == XFEATURE_PT_UNIMPLEMENTED_SO_FAR)) {
571 		WARN_ONCE(1, "no structure for xstate: %d\n", nr);
572 		XSTATE_WARN_ON(1);
573 	}
574 }
575 
576 /*
577  * This essentially double-checks what the cpu told us about
578  * how large the XSAVE buffer needs to be.  We are recalculating
579  * it to be safe.
580  */
581 static void do_extra_xstate_size_checks(void)
582 {
583 	int paranoid_xstate_size = FXSAVE_SIZE + XSAVE_HDR_SIZE;
584 	int i;
585 
586 	for (i = FIRST_EXTENDED_XFEATURE; i < XFEATURE_MAX; i++) {
587 		if (!xfeature_enabled(i))
588 			continue;
589 
590 		check_xstate_against_struct(i);
591 		/*
592 		 * Supervisor state components can be managed only by
593 		 * XSAVES, which is compacted-format only.
594 		 */
595 		if (!using_compacted_format())
596 			XSTATE_WARN_ON(xfeature_is_supervisor(i));
597 
598 		/* Align from the end of the previous feature */
599 		if (xfeature_is_aligned(i))
600 			paranoid_xstate_size = ALIGN(paranoid_xstate_size, 64);
601 		/*
602 		 * The offset of a given state in the non-compacted
603 		 * format is given to us in a CPUID leaf.  We check
604 		 * them for being ordered (increasing offsets) in
605 		 * setup_xstate_features().
606 		 */
607 		if (!using_compacted_format())
608 			paranoid_xstate_size = xfeature_uncompacted_offset(i);
609 		/*
610 		 * The compacted-format offset always depends on where
611 		 * the previous state ended.
612 		 */
613 		paranoid_xstate_size += xfeature_size(i);
614 	}
615 	XSTATE_WARN_ON(paranoid_xstate_size != fpu_kernel_xstate_size);
616 }
617 
618 
619 /*
620  * Get total size of enabled xstates in XCR0/xfeatures_mask.
621  *
622  * Note the SDM's wording here.  "sub-function 0" only enumerates
623  * the size of the *user* states.  If we use it to size a buffer
624  * that we use 'XSAVES' on, we could potentially overflow the
625  * buffer because 'XSAVES' saves system states too.
626  *
627  * Note that we do not currently set any bits on IA32_XSS so
628  * 'XCR0 | IA32_XSS == XCR0' for now.
629  */
630 static unsigned int __init get_xsaves_size(void)
631 {
632 	unsigned int eax, ebx, ecx, edx;
633 	/*
634 	 * - CPUID function 0DH, sub-function 1:
635 	 *    EBX enumerates the size (in bytes) required by
636 	 *    the XSAVES instruction for an XSAVE area
637 	 *    containing all the state components
638 	 *    corresponding to bits currently set in
639 	 *    XCR0 | IA32_XSS.
640 	 */
641 	cpuid_count(XSTATE_CPUID, 1, &eax, &ebx, &ecx, &edx);
642 	return ebx;
643 }
644 
645 static unsigned int __init get_xsave_size(void)
646 {
647 	unsigned int eax, ebx, ecx, edx;
648 	/*
649 	 * - CPUID function 0DH, sub-function 0:
650 	 *    EBX enumerates the size (in bytes) required by
651 	 *    the XSAVE instruction for an XSAVE area
652 	 *    containing all the *user* state components
653 	 *    corresponding to bits currently set in XCR0.
654 	 */
655 	cpuid_count(XSTATE_CPUID, 0, &eax, &ebx, &ecx, &edx);
656 	return ebx;
657 }
658 
659 /*
660  * Will the runtime-enumerated 'xstate_size' fit in the init
661  * task's statically-allocated buffer?
662  */
663 static bool is_supported_xstate_size(unsigned int test_xstate_size)
664 {
665 	if (test_xstate_size <= sizeof(union fpregs_state))
666 		return true;
667 
668 	pr_warn("x86/fpu: xstate buffer too small (%zu < %d), disabling xsave\n",
669 			sizeof(union fpregs_state), test_xstate_size);
670 	return false;
671 }
672 
673 static int __init init_xstate_size(void)
674 {
675 	/* Recompute the context size for enabled features: */
676 	unsigned int possible_xstate_size;
677 	unsigned int xsave_size;
678 
679 	xsave_size = get_xsave_size();
680 
681 	if (boot_cpu_has(X86_FEATURE_XSAVES))
682 		possible_xstate_size = get_xsaves_size();
683 	else
684 		possible_xstate_size = xsave_size;
685 
686 	/* Ensure we have the space to store all enabled: */
687 	if (!is_supported_xstate_size(possible_xstate_size))
688 		return -EINVAL;
689 
690 	/*
691 	 * The size is OK, we are definitely going to use xsave,
692 	 * make it known to the world that we need more space.
693 	 */
694 	fpu_kernel_xstate_size = possible_xstate_size;
695 	do_extra_xstate_size_checks();
696 
697 	/*
698 	 * User space is always in standard format.
699 	 */
700 	fpu_user_xstate_size = xsave_size;
701 	return 0;
702 }
703 
704 /*
705  * We enabled the XSAVE hardware, but something went wrong and
706  * we can not use it.  Disable it.
707  */
708 static void fpu__init_disable_system_xstate(void)
709 {
710 	xfeatures_mask = 0;
711 	cr4_clear_bits(X86_CR4_OSXSAVE);
712 	fpu__xstate_clear_all_cpu_caps();
713 }
714 
715 /*
716  * Enable and initialize the xsave feature.
717  * Called once per system bootup.
718  */
719 void __init fpu__init_system_xstate(void)
720 {
721 	unsigned int eax, ebx, ecx, edx;
722 	static int on_boot_cpu __initdata = 1;
723 	int err;
724 	int i;
725 
726 	WARN_ON_FPU(!on_boot_cpu);
727 	on_boot_cpu = 0;
728 
729 	if (!boot_cpu_has(X86_FEATURE_FPU)) {
730 		pr_info("x86/fpu: No FPU detected\n");
731 		return;
732 	}
733 
734 	if (!boot_cpu_has(X86_FEATURE_XSAVE)) {
735 		pr_info("x86/fpu: x87 FPU will use %s\n",
736 			boot_cpu_has(X86_FEATURE_FXSR) ? "FXSAVE" : "FSAVE");
737 		return;
738 	}
739 
740 	if (boot_cpu_data.cpuid_level < XSTATE_CPUID) {
741 		WARN_ON_FPU(1);
742 		return;
743 	}
744 
745 	cpuid_count(XSTATE_CPUID, 0, &eax, &ebx, &ecx, &edx);
746 	xfeatures_mask = eax + ((u64)edx << 32);
747 
748 	if ((xfeatures_mask & XFEATURE_MASK_FPSSE) != XFEATURE_MASK_FPSSE) {
749 		/*
750 		 * This indicates that something really unexpected happened
751 		 * with the enumeration.  Disable XSAVE and try to continue
752 		 * booting without it.  This is too early to BUG().
753 		 */
754 		pr_err("x86/fpu: FP/SSE not present amongst the CPU's xstate features: 0x%llx.\n", xfeatures_mask);
755 		goto out_disable;
756 	}
757 
758 	/*
759 	 * Clear XSAVE features that are disabled in the normal CPUID.
760 	 */
761 	for (i = 0; i < ARRAY_SIZE(xsave_cpuid_features); i++) {
762 		if (!boot_cpu_has(xsave_cpuid_features[i]))
763 			xfeatures_mask &= ~BIT(i);
764 	}
765 
766 	xfeatures_mask &= fpu__get_supported_xfeatures_mask();
767 
768 	/* Enable xstate instructions to be able to continue with initialization: */
769 	fpu__init_cpu_xstate();
770 	err = init_xstate_size();
771 	if (err)
772 		goto out_disable;
773 
774 	/*
775 	 * Update info used for ptrace frames; use standard-format size and no
776 	 * supervisor xstates:
777 	 */
778 	update_regset_xstate_info(fpu_user_xstate_size,	xfeatures_mask & ~XFEATURE_MASK_SUPERVISOR);
779 
780 	fpu__init_prepare_fx_sw_frame();
781 	setup_init_fpu_buf();
782 	setup_xstate_comp();
783 	print_xstate_offset_size();
784 
785 	pr_info("x86/fpu: Enabled xstate features 0x%llx, context size is %d bytes, using '%s' format.\n",
786 		xfeatures_mask,
787 		fpu_kernel_xstate_size,
788 		boot_cpu_has(X86_FEATURE_XSAVES) ? "compacted" : "standard");
789 	return;
790 
791 out_disable:
792 	/* something went wrong, try to boot without any XSAVE support */
793 	fpu__init_disable_system_xstate();
794 }
795 
796 /*
797  * Restore minimal FPU state after suspend:
798  */
799 void fpu__resume_cpu(void)
800 {
801 	/*
802 	 * Restore XCR0 on xsave capable CPUs:
803 	 */
804 	if (boot_cpu_has(X86_FEATURE_XSAVE))
805 		xsetbv(XCR_XFEATURE_ENABLED_MASK, xfeatures_mask);
806 }
807 
808 /*
809  * Given an xstate feature nr, calculate where in the xsave
810  * buffer the state is.  Callers should ensure that the buffer
811  * is valid.
812  */
813 static void *__raw_xsave_addr(struct xregs_state *xsave, int xfeature_nr)
814 {
815 	if (!xfeature_enabled(xfeature_nr)) {
816 		WARN_ON_FPU(1);
817 		return NULL;
818 	}
819 
820 	return (void *)xsave + xstate_comp_offsets[xfeature_nr];
821 }
822 /*
823  * Given the xsave area and a state inside, this function returns the
824  * address of the state.
825  *
826  * This is the API that is called to get xstate address in either
827  * standard format or compacted format of xsave area.
828  *
829  * Note that if there is no data for the field in the xsave buffer
830  * this will return NULL.
831  *
832  * Inputs:
833  *	xstate: the thread's storage area for all FPU data
834  *	xfeature_nr: state which is defined in xsave.h (e.g. XFEATURE_FP,
835  *	XFEATURE_SSE, etc...)
836  * Output:
837  *	address of the state in the xsave area, or NULL if the
838  *	field is not present in the xsave buffer.
839  */
840 void *get_xsave_addr(struct xregs_state *xsave, int xfeature_nr)
841 {
842 	/*
843 	 * Do we even *have* xsave state?
844 	 */
845 	if (!boot_cpu_has(X86_FEATURE_XSAVE))
846 		return NULL;
847 
848 	/*
849 	 * We should not ever be requesting features that we
850 	 * have not enabled.  Remember that pcntxt_mask is
851 	 * what we write to the XCR0 register.
852 	 */
853 	WARN_ONCE(!(xfeatures_mask & BIT_ULL(xfeature_nr)),
854 		  "get of unsupported state");
855 	/*
856 	 * This assumes the last 'xsave*' instruction to
857 	 * have requested that 'xfeature_nr' be saved.
858 	 * If it did not, we might be seeing and old value
859 	 * of the field in the buffer.
860 	 *
861 	 * This can happen because the last 'xsave' did not
862 	 * request that this feature be saved (unlikely)
863 	 * or because the "init optimization" caused it
864 	 * to not be saved.
865 	 */
866 	if (!(xsave->header.xfeatures & BIT_ULL(xfeature_nr)))
867 		return NULL;
868 
869 	return __raw_xsave_addr(xsave, xfeature_nr);
870 }
871 EXPORT_SYMBOL_GPL(get_xsave_addr);
872 
873 /*
874  * This wraps up the common operations that need to occur when retrieving
875  * data from xsave state.  It first ensures that the current task was
876  * using the FPU and retrieves the data in to a buffer.  It then calculates
877  * the offset of the requested field in the buffer.
878  *
879  * This function is safe to call whether the FPU is in use or not.
880  *
881  * Note that this only works on the current task.
882  *
883  * Inputs:
884  *	@xfeature_nr: state which is defined in xsave.h (e.g. XFEATURE_FP,
885  *	XFEATURE_SSE, etc...)
886  * Output:
887  *	address of the state in the xsave area or NULL if the state
888  *	is not present or is in its 'init state'.
889  */
890 const void *get_xsave_field_ptr(int xfeature_nr)
891 {
892 	struct fpu *fpu = &current->thread.fpu;
893 
894 	/*
895 	 * fpu__save() takes the CPU's xstate registers
896 	 * and saves them off to the 'fpu memory buffer.
897 	 */
898 	fpu__save(fpu);
899 
900 	return get_xsave_addr(&fpu->state.xsave, xfeature_nr);
901 }
902 
903 #ifdef CONFIG_ARCH_HAS_PKEYS
904 
905 #define NR_VALID_PKRU_BITS (CONFIG_NR_PROTECTION_KEYS * 2)
906 #define PKRU_VALID_MASK (NR_VALID_PKRU_BITS - 1)
907 /*
908  * This will go out and modify PKRU register to set the access
909  * rights for @pkey to @init_val.
910  */
911 int arch_set_user_pkey_access(struct task_struct *tsk, int pkey,
912 		unsigned long init_val)
913 {
914 	u32 old_pkru;
915 	int pkey_shift = (pkey * PKRU_BITS_PER_PKEY);
916 	u32 new_pkru_bits = 0;
917 
918 	/*
919 	 * This check implies XSAVE support.  OSPKE only gets
920 	 * set if we enable XSAVE and we enable PKU in XCR0.
921 	 */
922 	if (!boot_cpu_has(X86_FEATURE_OSPKE))
923 		return -EINVAL;
924 
925 	/* Set the bits we need in PKRU:  */
926 	if (init_val & PKEY_DISABLE_ACCESS)
927 		new_pkru_bits |= PKRU_AD_BIT;
928 	if (init_val & PKEY_DISABLE_WRITE)
929 		new_pkru_bits |= PKRU_WD_BIT;
930 
931 	/* Shift the bits in to the correct place in PKRU for pkey: */
932 	new_pkru_bits <<= pkey_shift;
933 
934 	/* Get old PKRU and mask off any old bits in place: */
935 	old_pkru = read_pkru();
936 	old_pkru &= ~((PKRU_AD_BIT|PKRU_WD_BIT) << pkey_shift);
937 
938 	/* Write old part along with new part: */
939 	write_pkru(old_pkru | new_pkru_bits);
940 
941 	return 0;
942 }
943 #endif /* ! CONFIG_ARCH_HAS_PKEYS */
944 
945 /*
946  * Weird legacy quirk: SSE and YMM states store information in the
947  * MXCSR and MXCSR_FLAGS fields of the FP area. That means if the FP
948  * area is marked as unused in the xfeatures header, we need to copy
949  * MXCSR and MXCSR_FLAGS if either SSE or YMM are in use.
950  */
951 static inline bool xfeatures_mxcsr_quirk(u64 xfeatures)
952 {
953 	if (!(xfeatures & (XFEATURE_MASK_SSE|XFEATURE_MASK_YMM)))
954 		return false;
955 
956 	if (xfeatures & XFEATURE_MASK_FP)
957 		return false;
958 
959 	return true;
960 }
961 
962 /*
963  * This is similar to user_regset_copyout(), but will not add offset to
964  * the source data pointer or increment pos, count, kbuf, and ubuf.
965  */
966 static inline void
967 __copy_xstate_to_kernel(void *kbuf, const void *data,
968 			unsigned int offset, unsigned int size, unsigned int size_total)
969 {
970 	if (offset < size_total) {
971 		unsigned int copy = min(size, size_total - offset);
972 
973 		memcpy(kbuf + offset, data, copy);
974 	}
975 }
976 
977 /*
978  * Convert from kernel XSAVES compacted format to standard format and copy
979  * to a kernel-space ptrace buffer.
980  *
981  * It supports partial copy but pos always starts from zero. This is called
982  * from xstateregs_get() and there we check the CPU has XSAVES.
983  */
984 int copy_xstate_to_kernel(void *kbuf, struct xregs_state *xsave, unsigned int offset_start, unsigned int size_total)
985 {
986 	unsigned int offset, size;
987 	struct xstate_header header;
988 	int i;
989 
990 	/*
991 	 * Currently copy_regset_to_user() starts from pos 0:
992 	 */
993 	if (unlikely(offset_start != 0))
994 		return -EFAULT;
995 
996 	/*
997 	 * The destination is a ptrace buffer; we put in only user xstates:
998 	 */
999 	memset(&header, 0, sizeof(header));
1000 	header.xfeatures = xsave->header.xfeatures;
1001 	header.xfeatures &= ~XFEATURE_MASK_SUPERVISOR;
1002 
1003 	/*
1004 	 * Copy xregs_state->header:
1005 	 */
1006 	offset = offsetof(struct xregs_state, header);
1007 	size = sizeof(header);
1008 
1009 	__copy_xstate_to_kernel(kbuf, &header, offset, size, size_total);
1010 
1011 	for (i = 0; i < XFEATURE_MAX; i++) {
1012 		/*
1013 		 * Copy only in-use xstates:
1014 		 */
1015 		if ((header.xfeatures >> i) & 1) {
1016 			void *src = __raw_xsave_addr(xsave, i);
1017 
1018 			offset = xstate_offsets[i];
1019 			size = xstate_sizes[i];
1020 
1021 			/* The next component has to fit fully into the output buffer: */
1022 			if (offset + size > size_total)
1023 				break;
1024 
1025 			__copy_xstate_to_kernel(kbuf, src, offset, size, size_total);
1026 		}
1027 
1028 	}
1029 
1030 	if (xfeatures_mxcsr_quirk(header.xfeatures)) {
1031 		offset = offsetof(struct fxregs_state, mxcsr);
1032 		size = MXCSR_AND_FLAGS_SIZE;
1033 		__copy_xstate_to_kernel(kbuf, &xsave->i387.mxcsr, offset, size, size_total);
1034 	}
1035 
1036 	/*
1037 	 * Fill xsave->i387.sw_reserved value for ptrace frame:
1038 	 */
1039 	offset = offsetof(struct fxregs_state, sw_reserved);
1040 	size = sizeof(xstate_fx_sw_bytes);
1041 
1042 	__copy_xstate_to_kernel(kbuf, xstate_fx_sw_bytes, offset, size, size_total);
1043 
1044 	return 0;
1045 }
1046 
1047 static inline int
1048 __copy_xstate_to_user(void __user *ubuf, const void *data, unsigned int offset, unsigned int size, unsigned int size_total)
1049 {
1050 	if (!size)
1051 		return 0;
1052 
1053 	if (offset < size_total) {
1054 		unsigned int copy = min(size, size_total - offset);
1055 
1056 		if (__copy_to_user(ubuf + offset, data, copy))
1057 			return -EFAULT;
1058 	}
1059 	return 0;
1060 }
1061 
1062 /*
1063  * Convert from kernel XSAVES compacted format to standard format and copy
1064  * to a user-space buffer. It supports partial copy but pos always starts from
1065  * zero. This is called from xstateregs_get() and there we check the CPU
1066  * has XSAVES.
1067  */
1068 int copy_xstate_to_user(void __user *ubuf, struct xregs_state *xsave, unsigned int offset_start, unsigned int size_total)
1069 {
1070 	unsigned int offset, size;
1071 	int ret, i;
1072 	struct xstate_header header;
1073 
1074 	/*
1075 	 * Currently copy_regset_to_user() starts from pos 0:
1076 	 */
1077 	if (unlikely(offset_start != 0))
1078 		return -EFAULT;
1079 
1080 	/*
1081 	 * The destination is a ptrace buffer; we put in only user xstates:
1082 	 */
1083 	memset(&header, 0, sizeof(header));
1084 	header.xfeatures = xsave->header.xfeatures;
1085 	header.xfeatures &= ~XFEATURE_MASK_SUPERVISOR;
1086 
1087 	/*
1088 	 * Copy xregs_state->header:
1089 	 */
1090 	offset = offsetof(struct xregs_state, header);
1091 	size = sizeof(header);
1092 
1093 	ret = __copy_xstate_to_user(ubuf, &header, offset, size, size_total);
1094 	if (ret)
1095 		return ret;
1096 
1097 	for (i = 0; i < XFEATURE_MAX; i++) {
1098 		/*
1099 		 * Copy only in-use xstates:
1100 		 */
1101 		if ((header.xfeatures >> i) & 1) {
1102 			void *src = __raw_xsave_addr(xsave, i);
1103 
1104 			offset = xstate_offsets[i];
1105 			size = xstate_sizes[i];
1106 
1107 			/* The next component has to fit fully into the output buffer: */
1108 			if (offset + size > size_total)
1109 				break;
1110 
1111 			ret = __copy_xstate_to_user(ubuf, src, offset, size, size_total);
1112 			if (ret)
1113 				return ret;
1114 		}
1115 
1116 	}
1117 
1118 	if (xfeatures_mxcsr_quirk(header.xfeatures)) {
1119 		offset = offsetof(struct fxregs_state, mxcsr);
1120 		size = MXCSR_AND_FLAGS_SIZE;
1121 		__copy_xstate_to_user(ubuf, &xsave->i387.mxcsr, offset, size, size_total);
1122 	}
1123 
1124 	/*
1125 	 * Fill xsave->i387.sw_reserved value for ptrace frame:
1126 	 */
1127 	offset = offsetof(struct fxregs_state, sw_reserved);
1128 	size = sizeof(xstate_fx_sw_bytes);
1129 
1130 	ret = __copy_xstate_to_user(ubuf, xstate_fx_sw_bytes, offset, size, size_total);
1131 	if (ret)
1132 		return ret;
1133 
1134 	return 0;
1135 }
1136 
1137 /*
1138  * Convert from a ptrace standard-format kernel buffer to kernel XSAVES format
1139  * and copy to the target thread. This is called from xstateregs_set().
1140  */
1141 int copy_kernel_to_xstate(struct xregs_state *xsave, const void *kbuf)
1142 {
1143 	unsigned int offset, size;
1144 	int i;
1145 	struct xstate_header hdr;
1146 
1147 	offset = offsetof(struct xregs_state, header);
1148 	size = sizeof(hdr);
1149 
1150 	memcpy(&hdr, kbuf + offset, size);
1151 
1152 	if (validate_xstate_header(&hdr))
1153 		return -EINVAL;
1154 
1155 	for (i = 0; i < XFEATURE_MAX; i++) {
1156 		u64 mask = ((u64)1 << i);
1157 
1158 		if (hdr.xfeatures & mask) {
1159 			void *dst = __raw_xsave_addr(xsave, i);
1160 
1161 			offset = xstate_offsets[i];
1162 			size = xstate_sizes[i];
1163 
1164 			memcpy(dst, kbuf + offset, size);
1165 		}
1166 	}
1167 
1168 	if (xfeatures_mxcsr_quirk(hdr.xfeatures)) {
1169 		offset = offsetof(struct fxregs_state, mxcsr);
1170 		size = MXCSR_AND_FLAGS_SIZE;
1171 		memcpy(&xsave->i387.mxcsr, kbuf + offset, size);
1172 	}
1173 
1174 	/*
1175 	 * The state that came in from userspace was user-state only.
1176 	 * Mask all the user states out of 'xfeatures':
1177 	 */
1178 	xsave->header.xfeatures &= XFEATURE_MASK_SUPERVISOR;
1179 
1180 	/*
1181 	 * Add back in the features that came in from userspace:
1182 	 */
1183 	xsave->header.xfeatures |= hdr.xfeatures;
1184 
1185 	return 0;
1186 }
1187 
1188 /*
1189  * Convert from a ptrace or sigreturn standard-format user-space buffer to
1190  * kernel XSAVES format and copy to the target thread. This is called from
1191  * xstateregs_set(), as well as potentially from the sigreturn() and
1192  * rt_sigreturn() system calls.
1193  */
1194 int copy_user_to_xstate(struct xregs_state *xsave, const void __user *ubuf)
1195 {
1196 	unsigned int offset, size;
1197 	int i;
1198 	struct xstate_header hdr;
1199 
1200 	offset = offsetof(struct xregs_state, header);
1201 	size = sizeof(hdr);
1202 
1203 	if (__copy_from_user(&hdr, ubuf + offset, size))
1204 		return -EFAULT;
1205 
1206 	if (validate_xstate_header(&hdr))
1207 		return -EINVAL;
1208 
1209 	for (i = 0; i < XFEATURE_MAX; i++) {
1210 		u64 mask = ((u64)1 << i);
1211 
1212 		if (hdr.xfeatures & mask) {
1213 			void *dst = __raw_xsave_addr(xsave, i);
1214 
1215 			offset = xstate_offsets[i];
1216 			size = xstate_sizes[i];
1217 
1218 			if (__copy_from_user(dst, ubuf + offset, size))
1219 				return -EFAULT;
1220 		}
1221 	}
1222 
1223 	if (xfeatures_mxcsr_quirk(hdr.xfeatures)) {
1224 		offset = offsetof(struct fxregs_state, mxcsr);
1225 		size = MXCSR_AND_FLAGS_SIZE;
1226 		if (__copy_from_user(&xsave->i387.mxcsr, ubuf + offset, size))
1227 			return -EFAULT;
1228 	}
1229 
1230 	/*
1231 	 * The state that came in from userspace was user-state only.
1232 	 * Mask all the user states out of 'xfeatures':
1233 	 */
1234 	xsave->header.xfeatures &= XFEATURE_MASK_SUPERVISOR;
1235 
1236 	/*
1237 	 * Add back in the features that came in from userspace:
1238 	 */
1239 	xsave->header.xfeatures |= hdr.xfeatures;
1240 
1241 	return 0;
1242 }
1243