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