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