nospec.h 2.1 KB

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