xref: /linux-6.15/include/linux/nospec.h (revision 1d91c1d2)
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 
6 #ifndef _LINUX_NOSPEC_H
7 #define _LINUX_NOSPEC_H
8 
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 /*
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 	_i &= _mask;							\
56 	_i;								\
57 })
58 #endif /* _LINUX_NOSPEC_H */
59