diff options
author | Jason Gunthorpe <jgg@mellanox.com> | 2018-08-02 00:25:39 +0300 |
---|---|---|
committer | Greg Kroah-Hartman <gregkh@linuxfoundation.org> | 2020-05-02 18:24:21 +0300 |
commit | 334c43f8d69fa5aa6487157b927ed9146e40786e (patch) | |
tree | d79fbc9d56d513033a58472864a61ae18015fc07 /include | |
parent | 17f673a9861cb15b98fcae1467647d7817e46109 (diff) | |
download | linux-334c43f8d69fa5aa6487157b927ed9146e40786e.tar.xz |
overflow.h: Add arithmetic shift helper
commit 0c66847793d1982d1083dc6f7adad60fa265ce9c upstream.
Add shift_overflow() helper to assist driver authors in ensuring that
shift operations don't cause overflows or other odd conditions.
Signed-off-by: Jason Gunthorpe <jgg@mellanox.com>
Signed-off-by: Leon Romanovsky <leonro@mellanox.com>
[kees: tweaked comments and commit log, dropped unneeded assignment]
Signed-off-by: Kees Cook <keescook@chromium.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Diffstat (limited to 'include')
-rw-r--r-- | include/linux/overflow.h | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/include/linux/overflow.h b/include/linux/overflow.h index c8890ec358a7..d309788f4cd2 100644 --- a/include/linux/overflow.h +++ b/include/linux/overflow.h @@ -202,4 +202,35 @@ #endif /* COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW */ +/** check_shl_overflow() - Calculate a left-shifted value and check overflow + * + * @a: Value to be shifted + * @s: How many bits left to shift + * @d: Pointer to where to store the result + * + * Computes *@d = (@a << @s) + * + * Returns true if '*d' cannot hold the result or when 'a << s' doesn't + * make sense. Example conditions: + * - 'a << s' causes bits to be lost when stored in *d. + * - 's' is garbage (e.g. negative) or so large that the result of + * 'a << s' is guaranteed to be 0. + * - 'a' is negative. + * - 'a << s' sets the sign bit, if any, in '*d'. + * + * '*d' will hold the results of the attempted shift, but is not + * considered "safe for use" if false is returned. + */ +#define check_shl_overflow(a, s, d) ({ \ + typeof(a) _a = a; \ + typeof(s) _s = s; \ + typeof(d) _d = d; \ + u64 _a_full = _a; \ + unsigned int _to_shift = \ + _s >= 0 && _s < 8 * sizeof(*d) ? _s : 0; \ + *_d = (_a_full << _to_shift); \ + (_to_shift != _s || *_d < 0 || _a < 0 || \ + (*_d >> _to_shift) != _a); \ +}) + #endif /* __LINUX_OVERFLOW_H */ |