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