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