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