Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 // Copyright(c) 2018 Linus Torvalds. All rights reserved.
0003 // Copyright(c) 2018 Alexei Starovoitov. All rights reserved.
0004 // Copyright(c) 2018 Intel Corporation. All rights reserved.
0005 
0006 #ifndef _LINUX_NOSPEC_H
0007 #define _LINUX_NOSPEC_H
0008 
0009 #include <linux/compiler.h>
0010 #include <asm/barrier.h>
0011 
0012 struct task_struct;
0013 
0014 /**
0015  * array_index_mask_nospec() - generate a ~0 mask when index < size, 0 otherwise
0016  * @index: array element index
0017  * @size: number of elements in array
0018  *
0019  * When @index is out of bounds (@index >= @size), the sign bit will be
0020  * set.  Extend the sign bit to all bits and invert, giving a result of
0021  * zero for an out of bounds index, or ~0 if within bounds [0, @size).
0022  */
0023 #ifndef array_index_mask_nospec
0024 static inline unsigned long array_index_mask_nospec(unsigned long index,
0025                             unsigned long size)
0026 {
0027     /*
0028      * Always calculate and emit the mask even if the compiler
0029      * thinks the mask is not needed. The compiler does not take
0030      * into account the value of @index under speculation.
0031      */
0032     OPTIMIZER_HIDE_VAR(index);
0033     return ~(long)(index | (size - 1UL - index)) >> (BITS_PER_LONG - 1);
0034 }
0035 #endif
0036 
0037 /*
0038  * array_index_nospec - sanitize an array index after a bounds check
0039  *
0040  * For a code sequence like:
0041  *
0042  *     if (index < size) {
0043  *         index = array_index_nospec(index, size);
0044  *         val = array[index];
0045  *     }
0046  *
0047  * ...if the CPU speculates past the bounds check then
0048  * array_index_nospec() will clamp the index within the range of [0,
0049  * size).
0050  */
0051 #define array_index_nospec(index, size)                 \
0052 ({                                  \
0053     typeof(index) _i = (index);                 \
0054     typeof(size) _s = (size);                   \
0055     unsigned long _mask = array_index_mask_nospec(_i, _s);      \
0056                                     \
0057     BUILD_BUG_ON(sizeof(_i) > sizeof(long));            \
0058     BUILD_BUG_ON(sizeof(_s) > sizeof(long));            \
0059                                     \
0060     (typeof(_i)) (_i & _mask);                  \
0061 })
0062 
0063 /* Speculation control prctl */
0064 int arch_prctl_spec_ctrl_get(struct task_struct *task, unsigned long which);
0065 int arch_prctl_spec_ctrl_set(struct task_struct *task, unsigned long which,
0066                  unsigned long ctrl);
0067 /* Speculation control for seccomp enforced mitigation */
0068 void arch_seccomp_spec_mitigate(struct task_struct *task);
0069 
0070 #endif /* _LINUX_NOSPEC_H */