test_fpu.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Test cases for using floating point operations inside a kernel module.
  4. *
  5. * This tests kernel_fpu_begin() and kernel_fpu_end() functions, especially
  6. * when userland has modified the floating point control registers. The kernel
  7. * state might depend on the state set by the userland thread that was active
  8. * before a syscall.
  9. *
  10. * To facilitate the test, this module registers file
  11. * /sys/kernel/debug/selftest_helpers/test_fpu, which when read causes a
  12. * sequence of floating point operations. If the operations fail, either the
  13. * read returns error status or the kernel crashes.
  14. * If the operations succeed, the read returns "1\n".
  15. */
  16. #include <linux/module.h>
  17. #include <linux/kernel.h>
  18. #include <linux/debugfs.h>
  19. #include <asm/fpu/api.h>
  20. static int test_fpu(void)
  21. {
  22. /*
  23. * This sequence of operations tests that rounding mode is
  24. * to nearest and that denormal numbers are supported.
  25. * Volatile variables are used to avoid compiler optimizing
  26. * the calculations away.
  27. */
  28. volatile double a, b, c, d, e, f, g;
  29. a = 4.0;
  30. b = 1e-15;
  31. c = 1e-310;
  32. /* Sets precision flag */
  33. d = a + b;
  34. /* Result depends on rounding mode */
  35. e = a + b / 2;
  36. /* Denormal and very large values */
  37. f = b / c;
  38. /* Depends on denormal support */
  39. g = a + c * f;
  40. if (d > a && e > a && g > a)
  41. return 0;
  42. else
  43. return -EINVAL;
  44. }
  45. static int test_fpu_get(void *data, u64 *val)
  46. {
  47. int status = -EINVAL;
  48. kernel_fpu_begin();
  49. status = test_fpu();
  50. kernel_fpu_end();
  51. *val = 1;
  52. return status;
  53. }
  54. DEFINE_SIMPLE_ATTRIBUTE(test_fpu_fops, test_fpu_get, NULL, "%lld\n");
  55. static struct dentry *selftest_dir;
  56. static int __init test_fpu_init(void)
  57. {
  58. selftest_dir = debugfs_create_dir("selftest_helpers", NULL);
  59. if (!selftest_dir)
  60. return -ENOMEM;
  61. debugfs_create_file("test_fpu", 0444, selftest_dir, NULL,
  62. &test_fpu_fops);
  63. return 0;
  64. }
  65. static void __exit test_fpu_exit(void)
  66. {
  67. debugfs_remove(selftest_dir);
  68. }
  69. module_init(test_fpu_init);
  70. module_exit(test_fpu_exit);
  71. MODULE_LICENSE("GPL");