nospec.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // SPDX-License-Identifier: GPL-2.0
  2. // Copyright(c) 2018 Linus Torvalds. All rights reserved.
  3. // Copyright(c) 2018 Alexei Starovoitov. All rights reserved.
  4. // Copyright(c) 2018 Intel Corporation. All rights reserved.
  5. #ifndef _LINUX_NOSPEC_H
  6. #define _LINUX_NOSPEC_H
  7. #include <linux/compiler.h>
  8. #include <asm/barrier.h>
  9. struct task_struct;
  10. /**
  11. * array_index_mask_nospec() - generate a ~0 mask when index < size, 0 otherwise
  12. * @index: array element index
  13. * @size: number of elements in array
  14. *
  15. * When @index is out of bounds (@index >= @size), the sign bit will be
  16. * set. Extend the sign bit to all bits and invert, giving a result of
  17. * zero for an out of bounds index, or ~0 if within bounds [0, @size).
  18. */
  19. #ifndef array_index_mask_nospec
  20. static inline unsigned long array_index_mask_nospec(unsigned long index,
  21. unsigned long size)
  22. {
  23. /*
  24. * Always calculate and emit the mask even if the compiler
  25. * thinks the mask is not needed. The compiler does not take
  26. * into account the value of @index under speculation.
  27. */
  28. OPTIMIZER_HIDE_VAR(index);
  29. return ~(long)(index | (size - 1UL - index)) >> (BITS_PER_LONG - 1);
  30. }
  31. #endif
  32. /*
  33. * array_index_nospec - sanitize an array index after a bounds check
  34. *
  35. * For a code sequence like:
  36. *
  37. * if (index < size) {
  38. * index = array_index_nospec(index, size);
  39. * val = array[index];
  40. * }
  41. *
  42. * ...if the CPU speculates past the bounds check then
  43. * array_index_nospec() will clamp the index within the range of [0,
  44. * size).
  45. */
  46. #define array_index_nospec(index, size) \
  47. ({ \
  48. typeof(index) _i = (index); \
  49. typeof(size) _s = (size); \
  50. unsigned long _mask = array_index_mask_nospec(_i, _s); \
  51. \
  52. BUILD_BUG_ON(sizeof(_i) > sizeof(long)); \
  53. BUILD_BUG_ON(sizeof(_s) > sizeof(long)); \
  54. \
  55. (typeof(_i)) (_i & _mask); \
  56. })
  57. /* Speculation control prctl */
  58. int arch_prctl_spec_ctrl_get(struct task_struct *task, unsigned long which);
  59. int arch_prctl_spec_ctrl_set(struct task_struct *task, unsigned long which,
  60. unsigned long ctrl);
  61. /* Speculation control for seccomp enforced mitigation */
  62. void arch_seccomp_spec_mitigate(struct task_struct *task);
  63. #endif /* _LINUX_NOSPEC_H */