xref: /linux/arch/x86/kernel/fpu/signal.c (revision 22a78a25438d246e4e951960523bee6a5155897d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * FPU signal frame handling routines.
4  */
5 
6 #include <linux/compat.h>
7 #include <linux/cpu.h>
8 #include <linux/pagemap.h>
9 
10 #include <asm/fpu/signal.h>
11 #include <asm/fpu/regset.h>
12 #include <asm/fpu/xstate.h>
13 
14 #include <asm/sigframe.h>
15 #include <asm/trapnr.h>
16 #include <asm/trace/fpu.h>
17 
18 #include "context.h"
19 #include "internal.h"
20 #include "legacy.h"
21 #include "xstate.h"
22 
23 /*
24  * Check for the presence of extended state information in the
25  * user fpstate pointer in the sigcontext.
26  */
27 static inline bool check_xstate_in_sigframe(struct fxregs_state __user *buf_fx,
28 					    struct _fpx_sw_bytes *fx_sw)
29 {
30 	struct fpstate *fpstate = x86_task_fpu(current)->fpstate;
31 	int min_xstate_size = sizeof(struct fxregs_state) +
32 			      sizeof(struct xstate_header);
33 	void __user *buf = buf_fx;
34 	unsigned int magic2;
35 
36 	if (__copy_from_user(fx_sw, &buf_fx->sw_reserved[0], sizeof(*fx_sw)))
37 		return false;
38 
39 	/* Check for the first magic field and other error scenarios. */
40 	if (fx_sw->magic1 != FP_XSTATE_MAGIC1 ||
41 	    fx_sw->xstate_size < min_xstate_size ||
42 	    fx_sw->xstate_size > fpstate->user_size ||
43 	    fx_sw->extended_size < fx_sw->xstate_size + FP_XSTATE_MAGIC2_SIZE)
44 		goto err_setfx;
45 
46 	/*
47 	 * Check for the presence of second magic word at the end of memory
48 	 * layout. This detects the case where the user just copied the legacy
49 	 * fpstate layout with out copying the extended state information
50 	 * in the memory layout.
51 	 */
52 	if (get_user(magic2, (__u32 __user *)(buf + fx_sw->xstate_size)))
53 		return false;
54 	if (unlikely(magic2 != FP_XSTATE_MAGIC2))
55 		goto err_setfx;
56 
57 	if (fx_sw->xstate_size != fpstate->user_size ||
58 	    fx_sw->xfeatures != fpstate->user_xfeatures) {
59 		unsigned int xsize;
60 		u64 xfeatures;
61 
62 		/* Calculate size of enabled features only. */
63 		xfeatures = fx_sw->xfeatures & fpstate->user_xfeatures;
64 
65 		xsize = xstate_calculate_size(xfeatures, false);
66 		if (fx_sw->xstate_size < xsize)
67 			return false;
68 
69 		fx_sw->xstate_size = xsize;
70 	}
71 
72 	return true;
73 err_setfx:
74 	/*
75 	 * The fallback to FX-only state is used to preserve backward
76 	 * compatibility with user-space processes that are not aware of xsave
77 	 * states.
78 	 *
79 	 * In all other cases, returning false (to trigger SIGSEGV) is
80 	 * preferred to avoid silent user-space state corruption.
81 	 */
82 	trace_x86_fpu_xstate_check_failed(x86_task_fpu(current));
83 
84 	/* Set the parameters for fx only state */
85 	fx_sw->magic1 = 0;
86 	fx_sw->xstate_size = sizeof(struct fxregs_state);
87 	fx_sw->xfeatures = XFEATURE_MASK_FPSSE;
88 	return true;
89 }
90 
91 /*
92  * Signal frame handlers.
93  */
94 static inline bool save_fsave_header(struct task_struct *tsk, void __user *buf)
95 {
96 	if (use_fxsr()) {
97 		struct xregs_state *xsave = &x86_task_fpu(tsk)->fpstate->regs.xsave;
98 		struct user_i387_ia32_struct env;
99 		struct _fpstate_32 __user *fp = buf;
100 
101 		fpregs_lock();
102 		if (!test_thread_flag(TIF_NEED_FPU_LOAD))
103 			fxsave(&x86_task_fpu(tsk)->fpstate->regs.fxsave);
104 		fpregs_unlock();
105 
106 		convert_from_fxsr(&env, tsk);
107 
108 		if (__copy_to_user(buf, &env, sizeof(env)) ||
109 		    put_user(xsave->i387.swd, &fp->status) ||
110 		    put_user(X86_FXSR_MAGIC, &fp->magic))
111 			return false;
112 	} else {
113 		struct fregs_state __user *fp = buf;
114 		u32 swd;
115 
116 		if (get_user(swd, &fp->swd) || put_user(swd, &fp->status))
117 			return false;
118 	}
119 
120 	return true;
121 }
122 
123 /*
124  * Prepare the SW reserved portion of the fxsave memory layout, indicating
125  * the presence of the extended state information in the memory layout
126  * pointed to by the fpstate pointer in the sigcontext.
127  * This is saved when ever the FP and extended state context is
128  * saved on the user stack during the signal handler delivery to the user.
129  */
130 static inline void save_sw_bytes(struct _fpx_sw_bytes *sw_bytes, bool ia32_frame,
131 				 struct fpstate *fpstate)
132 {
133 	sw_bytes->magic1 = FP_XSTATE_MAGIC1;
134 	sw_bytes->extended_size = fpstate->user_size + FP_XSTATE_MAGIC2_SIZE;
135 	sw_bytes->xfeatures = fpstate->user_xfeatures;
136 	sw_bytes->xstate_size = fpstate->user_size;
137 
138 	if (ia32_frame)
139 		sw_bytes->extended_size += sizeof(struct fregs_state);
140 }
141 
142 static inline bool save_xstate_epilog(void __user *buf, int ia32_frame,
143 				      struct fpstate *fpstate)
144 {
145 	struct xregs_state __user *x = buf;
146 	struct _fpx_sw_bytes sw_bytes = {};
147 	int err;
148 
149 	/* Setup the bytes not touched by the [f]xsave and reserved for SW. */
150 	save_sw_bytes(&sw_bytes, ia32_frame, fpstate);
151 	err = __copy_to_user(&x->i387.sw_reserved, &sw_bytes, sizeof(sw_bytes));
152 
153 	if (!use_xsave())
154 		return !err;
155 
156 	err |= put_user(FP_XSTATE_MAGIC2,
157 			(__u32 __user *)(buf + fpstate->user_size));
158 
159 	/*
160 	 * For legacy compatible, we always set FP/SSE bits in the bit
161 	 * vector while saving the state to the user context. This will
162 	 * enable us capturing any changes(during sigreturn) to
163 	 * the FP/SSE bits by the legacy applications which don't touch
164 	 * xfeatures in the xsave header.
165 	 *
166 	 * xsave aware apps can change the xfeatures in the xsave
167 	 * header as well as change any contents in the memory layout.
168 	 * xrestore as part of sigreturn will capture all the changes.
169 	 */
170 	err |= set_xfeature_in_sigframe(x, XFEATURE_MASK_FPSSE);
171 
172 	return !err;
173 }
174 
175 static inline int copy_fpregs_to_sigframe(struct xregs_state __user *buf, u32 pkru)
176 {
177 	if (use_xsave())
178 		return xsave_to_user_sigframe(buf, pkru);
179 
180 	if (use_fxsr())
181 		return fxsave_to_user_sigframe((struct fxregs_state __user *) buf);
182 	else
183 		return fnsave_to_user_sigframe((struct fregs_state __user *) buf);
184 }
185 
186 /*
187  * Save the fpu, extended register state to the user signal frame.
188  *
189  * 'buf_fx' is the 64-byte aligned pointer at which the [f|fx|x]save
190  *  state is copied.
191  *  'buf' points to the 'buf_fx' or to the fsave header followed by 'buf_fx'.
192  *
193  *	buf == buf_fx for 64-bit frames and 32-bit fsave frame.
194  *	buf != buf_fx for 32-bit frames with fxstate.
195  *
196  * Save it directly to the user frame with disabled page fault handler. If
197  * that faults, try to clear the frame which handles the page fault.
198  *
199  * If this is a 32-bit frame with fxstate, put a fsave header before
200  * the aligned state at 'buf_fx'.
201  *
202  * For [f]xsave state, update the SW reserved fields in the [f]xsave frame
203  * indicating the absence/presence of the extended state to the user.
204  */
205 bool copy_fpstate_to_sigframe(void __user *buf, void __user *buf_fx, int size, u32 pkru)
206 {
207 	struct task_struct *tsk = current;
208 	struct fpstate *fpstate = x86_task_fpu(tsk)->fpstate;
209 	bool ia32_fxstate = (buf != buf_fx);
210 	int ret;
211 
212 	ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) ||
213 			 IS_ENABLED(CONFIG_IA32_EMULATION));
214 
215 	if (!access_ok(buf, size))
216 		return false;
217 
218 	if (use_xsave()) {
219 		struct xregs_state __user *xbuf = buf_fx;
220 
221 		/*
222 		 * Clear the xsave header first, so that reserved fields are
223 		 * initialized to zero.
224 		 */
225 		if (__clear_user(&xbuf->header, sizeof(xbuf->header)))
226 			return false;
227 	}
228 retry:
229 	/*
230 	 * Load the FPU registers if they are not valid for the current task.
231 	 * With a valid FPU state we can attempt to save the state directly to
232 	 * userland's stack frame which will likely succeed. If it does not,
233 	 * resolve the fault in the user memory and try again.
234 	 */
235 	fpregs_lock();
236 	if (test_thread_flag(TIF_NEED_FPU_LOAD))
237 		fpregs_restore_userregs();
238 
239 	pagefault_disable();
240 	ret = copy_fpregs_to_sigframe(buf_fx, pkru);
241 	pagefault_enable();
242 	fpregs_unlock();
243 
244 	if (ret) {
245 		if (!__clear_user(buf_fx, fpstate->user_size))
246 			goto retry;
247 		return false;
248 	}
249 
250 	/* Save the fsave header for the 32-bit frames. */
251 	if ((ia32_fxstate || !use_fxsr()) && !save_fsave_header(tsk, buf))
252 		return false;
253 
254 	if (use_fxsr() && !save_xstate_epilog(buf_fx, ia32_fxstate, fpstate))
255 		return false;
256 
257 	return true;
258 }
259 
260 static int __restore_fpregs_from_user(void __user *buf, u64 task_xfeatures,
261 				      u64 xrestore_mask, bool fx_only)
262 {
263 	if (use_xsave()) {
264 		u64 init_bv;
265 		int ret;
266 
267 		/* Restore enabled features only. */
268 		xrestore_mask &= task_xfeatures;
269 		init_bv = task_xfeatures & ~xrestore_mask;
270 		if (likely(!fx_only))
271 			ret = xrstor_from_user_sigframe(buf, xrestore_mask);
272 		else
273 			ret = fxrstor_from_user_sigframe(buf);
274 
275 		if (!ret && unlikely(init_bv))
276 			os_xrstor(&init_fpstate, init_bv);
277 		return ret;
278 	} else if (use_fxsr()) {
279 		return fxrstor_from_user_sigframe(buf);
280 	} else {
281 		return frstor_from_user_sigframe(buf);
282 	}
283 }
284 
285 /*
286  * Attempt to restore the FPU registers directly from user memory.
287  * Pagefaults are handled and any errors returned are fatal.
288  */
289 static bool restore_fpregs_from_user(void __user *buf, u64 xrestore_mask,
290 				     bool fx_only, size_t xstate_size)
291 {
292 	struct fpu *fpu = x86_task_fpu(current);
293 	int ret;
294 
295 retry:
296 	fpregs_lock();
297 	/* Ensure that XFD is up to date */
298 	xfd_update_state(fpu->fpstate);
299 	pagefault_disable();
300 	ret = __restore_fpregs_from_user(buf, fpu->fpstate->user_xfeatures,
301 					 xrestore_mask, fx_only);
302 	pagefault_enable();
303 
304 	if (unlikely(ret)) {
305 		/*
306 		 * The above did an FPU restore operation, restricted to
307 		 * the user portion of the registers, and failed, but the
308 		 * microcode might have modified the FPU registers
309 		 * nevertheless.
310 		 *
311 		 * If the FPU registers do not belong to current, then
312 		 * invalidate the FPU register state otherwise the task
313 		 * might preempt current and return to user space with
314 		 * corrupted FPU registers.
315 		 */
316 		if (test_thread_flag(TIF_NEED_FPU_LOAD))
317 			__cpu_invalidate_fpregs_state();
318 		fpregs_unlock();
319 
320 		/* Try to handle #PF, but anything else is fatal. */
321 		if (ret != X86_TRAP_PF)
322 			return false;
323 
324 		if (!fault_in_readable(buf, xstate_size))
325 			goto retry;
326 		return false;
327 	}
328 
329 	/*
330 	 * Restore supervisor states: previous context switch etc has done
331 	 * XSAVES and saved the supervisor states in the kernel buffer from
332 	 * which they can be restored now.
333 	 *
334 	 * It would be optimal to handle this with a single XRSTORS, but
335 	 * this does not work because the rest of the FPU registers have
336 	 * been restored from a user buffer directly.
337 	 */
338 	if (test_thread_flag(TIF_NEED_FPU_LOAD) && xfeatures_mask_supervisor())
339 		os_xrstor_supervisor(fpu->fpstate);
340 
341 	fpregs_mark_activate();
342 	fpregs_unlock();
343 	return true;
344 }
345 
346 /*
347  * Restore FPU state from a signal frame when a legacy 32-bit FP frame
348  * (buf_f) is present.
349  *
350  * The legacy FP frame duplicates the FP state portion of the FX/XSAVE
351  * frame (buf_fx). For backward compatibility, the legacy FP frame is
352  * treated as the source of truth, and its state is folded into the
353  * FX/XSAVE state before restoring the registers.
354  */
355 static bool restore_from_ia32_fxstate(void __user *buf_f, void __user *buf_fx,
356 				      u64 xrestore_mask, bool fx_only)
357 {
358 	struct task_struct *tsk = current;
359 	struct fpu *fpu = x86_task_fpu(tsk);
360 	struct user_i387_ia32_struct env;
361 	union fpregs_state *fpregs;
362 	bool success;
363 
364 	if (!IS_ENABLED(CONFIG_X86_32) && !IS_ENABLED(CONFIG_IA32_EMULATION))
365 		return false;
366 
367 	/*
368 	 * Copy the legacy state because the FP portion of the FX frame has
369 	 * to be ignored for histerical raisins. The legacy state is folded
370 	 * in once the larger state has been copied.
371 	 */
372 	if (__copy_from_user(&env, buf_f, sizeof(env)))
373 		return false;
374 
375 	/*
376 	 * By setting TIF_NEED_FPU_LOAD it is ensured that our xstate is
377 	 * not modified on context switch and that the xstate is considered
378 	 * to be loaded again on return to userland (overriding last_cpu avoids
379 	 * the optimisation).
380 	 */
381 	fpregs_lock();
382 	if (!test_thread_flag(TIF_NEED_FPU_LOAD)) {
383 		/*
384 		 * If supervisor states are available then save the
385 		 * hardware state in current's fpstate so that the
386 		 * supervisor state is preserved. Save the full state for
387 		 * simplicity. There is no point in optimizing this by only
388 		 * saving the supervisor states and then shuffle them to
389 		 * the right place in memory. It's ia32 mode. Shrug.
390 		 */
391 		if (xfeatures_mask_supervisor())
392 			os_xsave(fpu->fpstate);
393 		set_thread_flag(TIF_NEED_FPU_LOAD);
394 	}
395 	__fpu_invalidate_fpregs_state(fpu);
396 	__cpu_invalidate_fpregs_state();
397 	fpregs_unlock();
398 
399 	fpregs = &fpu->fpstate->regs;
400 	if (use_xsave() && !fx_only) {
401 		if (copy_sigframe_from_user_to_xstate(tsk, buf_fx))
402 			return false;
403 	} else {
404 		if (__copy_from_user(&fpregs->fxsave, buf_fx,
405 				     sizeof(fpregs->fxsave)))
406 			return false;
407 
408 		if (IS_ENABLED(CONFIG_X86_64)) {
409 			/* Reject invalid MXCSR values. */
410 			if (fpregs->fxsave.mxcsr & ~mxcsr_feature_mask)
411 				return false;
412 		} else {
413 			/* Mask invalid bits out for historical reasons (broken hardware). */
414 			fpregs->fxsave.mxcsr &= mxcsr_feature_mask;
415 		}
416 
417 		/* Enforce XFEATURE_MASK_FPSSE when XSAVE is enabled */
418 		if (use_xsave())
419 			fpregs->xsave.header.xfeatures |= XFEATURE_MASK_FPSSE;
420 	}
421 
422 	/* Fold the legacy FP storage */
423 	convert_to_fxsr(&fpregs->fxsave, &env);
424 
425 	fpregs_lock();
426 	if (use_xsave()) {
427 		/*
428 		 * Remove all UABI feature bits not set in user_xfeatures
429 		 * from the memory xstate header which makes the full
430 		 * restore below bring them into init state. This works for
431 		 * fx_only mode as well because that has only FP and SSE
432 		 * set in user_xfeatures.
433 		 *
434 		 * Preserve supervisor states!
435 		 */
436 		u64 mask = xrestore_mask | xfeatures_mask_supervisor();
437 
438 		fpregs->xsave.header.xfeatures &= mask;
439 		success = !os_xrstor_safe(fpu->fpstate,
440 					  fpu_kernel_cfg.max_features);
441 	} else {
442 		success = !fxrstor_safe(&fpregs->fxsave);
443 	}
444 
445 	if (likely(success))
446 		fpregs_mark_activate();
447 
448 	fpregs_unlock();
449 	return success;
450 }
451 
452 static inline unsigned int xstate_sigframe_size(struct fpstate *fpstate)
453 {
454 	unsigned int size = fpstate->user_size;
455 
456 	return use_xsave() ? size + FP_XSTATE_MAGIC2_SIZE : size;
457 }
458 
459 /*
460  * Restore FPU state from a sigframe:
461  */
462 bool fpu__restore_sig(void __user *buf, int ia32_frame)
463 {
464 	struct fpu *fpu = x86_task_fpu(current);
465 	bool success = false, fx_only = false;
466 	bool ia32_fxstate = false;
467 	void __user *buf_fx = buf;
468 	unsigned int size;
469 	u64 xrestore_mask;
470 
471 	if (unlikely(!buf)) {
472 		fpu__clear_user_states(fpu);
473 		return true;
474 	}
475 
476 	size = xstate_sigframe_size(fpu->fpstate);
477 
478 	ia32_frame &= (IS_ENABLED(CONFIG_X86_32) ||
479 		       IS_ENABLED(CONFIG_IA32_EMULATION));
480 
481 	/*
482 	 * Only FXSR enabled systems need the FX state quirk.
483 	 * FRSTOR does not need it and can use the fast path.
484 	 */
485 	if (ia32_frame && use_fxsr()) {
486 		buf_fx = buf + sizeof(struct fregs_state);
487 		size += sizeof(struct fregs_state);
488 		ia32_fxstate = true;
489 	}
490 
491 	if (!access_ok(buf, size))
492 		goto out;
493 
494 	if (use_xsave()) {
495 		struct _fpx_sw_bytes fx_sw_user;
496 
497 		if (!check_xstate_in_sigframe(buf_fx, &fx_sw_user))
498 			goto out;
499 
500 		fx_only = !fx_sw_user.magic1;
501 		xrestore_mask = fx_sw_user.xfeatures;
502 		size = fx_sw_user.xstate_size;
503 	} else {
504 		xrestore_mask = XFEATURE_MASK_FPSSE;
505 		size = fpu->fpstate->user_size;
506 	}
507 
508 	if (ia32_fxstate)
509 		success = restore_from_ia32_fxstate(buf, buf_fx, xrestore_mask, fx_only);
510 	else
511 		success = restore_fpregs_from_user(buf_fx, xrestore_mask, fx_only, size);
512 out:
513 	if (unlikely(!success))
514 		fpu__clear_user_states(fpu);
515 	return success;
516 }
517 
518 unsigned long
519 fpu__alloc_mathframe(unsigned long sp, int ia32_frame,
520 		     unsigned long *buf_fx, unsigned long *size)
521 {
522 	unsigned long frame_size = xstate_sigframe_size(x86_task_fpu(current)->fpstate);
523 
524 	*buf_fx = sp = round_down(sp - frame_size, 64);
525 	if (ia32_frame && use_fxsr()) {
526 		frame_size += sizeof(struct fregs_state);
527 		sp -= sizeof(struct fregs_state);
528 	}
529 
530 	*size = frame_size;
531 
532 	return sp;
533 }
534 
535 unsigned long __init fpu__get_fpstate_size(void)
536 {
537 	unsigned long ret = fpu_user_cfg.max_size;
538 
539 	if (use_xsave())
540 		ret += FP_XSTATE_MAGIC2_SIZE;
541 
542 	/*
543 	 * This space is needed on (most) 32-bit kernels, or when a 32-bit
544 	 * app is running on a 64-bit kernel. To keep things simple, just
545 	 * assume the worst case and always include space for 'freg_state',
546 	 * even for 64-bit apps on 64-bit kernels. This wastes a bit of
547 	 * space, but keeps the code simple.
548 	 */
549 	if ((IS_ENABLED(CONFIG_IA32_EMULATION) ||
550 	     IS_ENABLED(CONFIG_X86_32)) && use_fxsr())
551 		ret += sizeof(struct fregs_state);
552 
553 	return ret;
554 }
555 
556