nospec: Allow index argument to have const-qualified type
authorRasmus Villemoes <>
Fri, 16 Feb 2018 21:20:48 +0000 (13:20 -0800)
committerBen Hutchings <>
Thu, 31 May 2018 23:30:16 +0000 (00:30 +0100)
commit b98c6a160a057d5686a8c54c79cc6c8c94a7d0c8 upstream.

The last expression in a statement expression need not be a bare
variable, quoting gcc docs

  The last thing in the compound statement should be an expression
  followed by a semicolon; the value of this subexpression serves as the
  value of the entire construct.

and we already use that in e.g. the min/max macros which end with a
ternary expression.

This way, we can allow index to have const-qualified type, which will in
some cases avoid the need for introducing a local copy of index of
non-const qualified type. That, in turn, can prevent readers not
familiar with the internals of array_index_nospec from wondering about
the seemingly redundant extra variable, and I think that's worthwhile
considering how confusing the whole _nospec business is.

The expression _i&_mask has type unsigned long (since that is the type
of _mask, and the BUILD_BUG_ONs guarantee that _i will get promoted to
that), so in order not to change the type of the whole expression, add
a cast back to typeof(_i).

Signed-off-by: Rasmus Villemoes <>
Signed-off-by: Dan Williams <>
Acked-by: Linus Torvalds <>
Cc: Andy Lutomirski <>
Cc: Arjan van de Ven <>
Cc: Borislav Petkov <>
Cc: Dave Hansen <>
Cc: David Woodhouse <>
Cc: Greg Kroah-Hartman <>
Cc: Josh Poimboeuf <>
Cc: Peter Zijlstra <>
Cc: Thomas Gleixner <>
Cc: Will Deacon <>
Signed-off-by: Ingo Molnar <>
Signed-off-by: Ben Hutchings <>

index 4232e73..6f06589 100644 (file)
@@ -53,7 +53,6 @@ static inline unsigned long array_index_mask_nospec(unsigned long index,
        BUILD_BUG_ON(sizeof(_i) > sizeof(long));                        \
        BUILD_BUG_ON(sizeof(_s) > sizeof(long));                        \
-       _i &= _mask;                                                    \
-       _i;                                                             \
+       (typeof(_i)) (_i & _mask);                                      \
 #endif /* _LINUX_NOSPEC_H */