xref: /OK3568_Linux_fs/kernel/tools/testing/selftests/fpu/test_fpu.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun // SPDX-License-Identifier: GPL-2.0+
2*4882a593Smuzhiyun /* This testcase operates with the test_fpu kernel driver.
3*4882a593Smuzhiyun  * It modifies the FPU control register in user mode and calls the kernel
4*4882a593Smuzhiyun  * module to perform floating point operations in the kernel. The control
5*4882a593Smuzhiyun  * register value should be independent between kernel and user mode.
6*4882a593Smuzhiyun  */
7*4882a593Smuzhiyun 
8*4882a593Smuzhiyun #define _GNU_SOURCE
9*4882a593Smuzhiyun #include <stdio.h>
10*4882a593Smuzhiyun #include <errno.h>
11*4882a593Smuzhiyun #include <string.h>
12*4882a593Smuzhiyun #include <fenv.h>
13*4882a593Smuzhiyun #include <unistd.h>
14*4882a593Smuzhiyun #include <fcntl.h>
15*4882a593Smuzhiyun 
16*4882a593Smuzhiyun const char *test_fpu_path = "/sys/kernel/debug/selftest_helpers/test_fpu";
17*4882a593Smuzhiyun 
main(void)18*4882a593Smuzhiyun int main(void)
19*4882a593Smuzhiyun {
20*4882a593Smuzhiyun 	char dummy[1];
21*4882a593Smuzhiyun 	int fd = open(test_fpu_path, O_RDONLY);
22*4882a593Smuzhiyun 
23*4882a593Smuzhiyun 	if (fd < 0) {
24*4882a593Smuzhiyun 		printf("[SKIP]\tcan't access %s: %s\n",
25*4882a593Smuzhiyun 		       test_fpu_path, strerror(errno));
26*4882a593Smuzhiyun 		return 0;
27*4882a593Smuzhiyun 	}
28*4882a593Smuzhiyun 
29*4882a593Smuzhiyun 	if (read(fd, dummy, 1) < 0) {
30*4882a593Smuzhiyun 		printf("[FAIL]\taccess with default rounding mode failed\n");
31*4882a593Smuzhiyun 		return 1;
32*4882a593Smuzhiyun 	}
33*4882a593Smuzhiyun 
34*4882a593Smuzhiyun 	fesetround(FE_DOWNWARD);
35*4882a593Smuzhiyun 	if (read(fd, dummy, 1) < 0) {
36*4882a593Smuzhiyun 		printf("[FAIL]\taccess with downward rounding mode failed\n");
37*4882a593Smuzhiyun 		return 2;
38*4882a593Smuzhiyun 	}
39*4882a593Smuzhiyun 	if (fegetround() != FE_DOWNWARD) {
40*4882a593Smuzhiyun 		printf("[FAIL]\tusermode rounding mode clobbered\n");
41*4882a593Smuzhiyun 		return 3;
42*4882a593Smuzhiyun 	}
43*4882a593Smuzhiyun 
44*4882a593Smuzhiyun 	/* Note: the tests up to this point are quite safe and will only return
45*4882a593Smuzhiyun 	 * an error. But the exception mask setting can cause misbehaving kernel
46*4882a593Smuzhiyun 	 * to crash.
47*4882a593Smuzhiyun 	 */
48*4882a593Smuzhiyun 	feclearexcept(FE_ALL_EXCEPT);
49*4882a593Smuzhiyun 	feenableexcept(FE_ALL_EXCEPT);
50*4882a593Smuzhiyun 	if (read(fd, dummy, 1) < 0) {
51*4882a593Smuzhiyun 		printf("[FAIL]\taccess with fpu exceptions unmasked failed\n");
52*4882a593Smuzhiyun 		return 4;
53*4882a593Smuzhiyun 	}
54*4882a593Smuzhiyun 	if (fegetexcept() != FE_ALL_EXCEPT) {
55*4882a593Smuzhiyun 		printf("[FAIL]\tusermode fpu exception mask clobbered\n");
56*4882a593Smuzhiyun 		return 5;
57*4882a593Smuzhiyun 	}
58*4882a593Smuzhiyun 
59*4882a593Smuzhiyun 	printf("[OK]\ttest_fpu\n");
60*4882a593Smuzhiyun 	return 0;
61*4882a593Smuzhiyun }
62