2022-09-09 11:03:21

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 0/9] Fixes integer overflow or integer truncation issues in page lookups, ttm place configuration and scatterlist creation

This patch series fixes integer overflow or integer truncation issues in
page lookups, ttm place configuration and scatterlist creation, etc.
We need to check that we avoid integer overflows when looking up a page,
and so fix all the instances where we have mistakenly used a plain integer
instead of a more suitable long.
And there is an impedance mismatch between the scatterlist API using
unsigned int and our memory/page accounting in unsigned long. That is we
may try to create a scatterlist for a large object that overflows returning
a small table into which we try to fit very many pages. As the object size
is under the control of userspace, we have to be prudent and catch the
conversion errors. To catch the implicit truncation as we switch from
unsigned long into the scatterlist's unsigned int, we use improved
overflows_type check and report E2BIG prior to the operation. This is
already used in our create ioctls to indicate if the uABI request is simply
too large for the backing store.
And ttm place also has the same problem with scatterlist creation,
and we fix the integer truncation problem with the way approached by
scatterlist creation.
And It corrects the error code to return -E2BIG when creating gem objects
using ttm or shmem, if the size is too large in each case.
In order to provide a common macro, it moves and adds a few utility macros
into overflow/compiler_types header.
It introduces assert_type() assert_typable() macros to catch type mismatch
while compiling. And it also introduces check_assign() and
check_assign_user_ptr() macros to perform an assigning source value into
the destination pointer along with an overflow check.
In order to implemente check_assign(), overflows_type() on top of updated
check_add_overflow() macro, this series include the patch which came from
Kees [1] (this patch is under reviewing from other patch mail).

[1] https://lore.kernel.org/all/202208311040.C6CA8253@keescook/

v10: Add check_assign_user_ptr() macro and drop overflows_ptr() macro(Kees)
Use assert_typable instead of exactly_pgoff_t() macro (Kees)
Remove a redundant type checking for a pointer. (Andrzej)
Add patch "compiler_types.h: Add assert_type to catch type mis-match while compiling" and
drop patch "util_macros: Add exact_type macro to catch type mis-match while compiling" from patch series (G.G.)
(adding of assert_type(t1, t2) and assert_typable(t, n) were suggested by Kees v9's comments)
v9: Fix overflows_type() to use __builtin_add_overflow() instead of
__builtin_add_overflow_p() (Andrzej)
Fix overflows_ptr() to use overflows_type() with the unsigned long type (Andrzej)
v8: Add check_assign() and remove safe_conversion() (Kees)
Replace safe_conversion() with check_assign() (Kees)
Fix overflows_type() to use gcc's built-in overflow function (Andrzej)
Add overflows_ptr() to allow overflow checking when assigning a value
into a pointer variable (G.G.)
v7: Fix to use WARN_ON() macro where GEM_BUG_ON() macro was used. (Jani)
v6: Move macro addition location so that it can be used by other than drm subsystem (Jani, Mauro, Andi)
Fix to follow general use case for GEM_BUG_ON(). (Jani)
v5: Fix an alignment to match open parenthesis
Fix macros to be enclosed in parentheses for complex values
Fix too long line warning
v4: Fix build warnins that reported by kernel test robot. (kernel test robot <[email protected]>)
Add kernel-doc markups to the kAPI functions and macros (Mauoro)
v3: Modify overflows_type() macro to consider signed data types and
add is_type_unsigned() macro (Mauro)
Make not use the same macro name on a function. (Mauro)
For kernel-doc, macros and functions are handled in the same namespace,
the same macro name on a function prevents ever adding documentation for it.
Not to change execution inside a macro. (Mauro)
Fix the problem that safe_conversion() macro always returns true (G.G)
Add safe_conversion_gem_bug_on() macro and remove temporal SAFE_CONVERSION() macro. (G.G.)

Chris Wilson (3):
drm/i915/gem: Typecheck page lookups
drm/i915: Check for integer truncation on scatterlist creation
drm/i915: Remove truncation warning for large objects

Gwan-gyeong Mun (5):
overflow: Move and add few utility macros into overflow
compiler_types.h: Add assert_type to catch type mis-match while
compiling
drm/i915: Check for integer truncation on the configuration of ttm
place
drm/i915: Check if the size is too big while creating shmem file
drm/i915: Use error code as -E2BIG when the size of gem ttm object is
too large

Kees Cook (1):
overflow: Allow mixed type arguments

drivers/gpu/drm/i915/gem/i915_gem_internal.c | 6 +-
drivers/gpu/drm/i915/gem/i915_gem_object.c | 7 +-
drivers/gpu/drm/i915/gem/i915_gem_object.h | 303 +++++++++++++++---
drivers/gpu/drm/i915/gem/i915_gem_pages.c | 27 +-
drivers/gpu/drm/i915/gem/i915_gem_phys.c | 4 +
drivers/gpu/drm/i915/gem/i915_gem_shmem.c | 19 +-
drivers/gpu/drm/i915/gem/i915_gem_ttm.c | 23 +-
drivers/gpu/drm/i915/gem/i915_gem_userptr.c | 5 +-
.../drm/i915/gem/selftests/i915_gem_context.c | 12 +-
.../drm/i915/gem/selftests/i915_gem_mman.c | 8 +-
.../drm/i915/gem/selftests/i915_gem_object.c | 8 +-
drivers/gpu/drm/i915/gvt/dmabuf.c | 9 +-
drivers/gpu/drm/i915/i915_gem.c | 18 +-
drivers/gpu/drm/i915/i915_scatterlist.h | 11 +
drivers/gpu/drm/i915/i915_user_extensions.c | 6 +-
drivers/gpu/drm/i915/i915_utils.h | 6 +-
drivers/gpu/drm/i915/i915_vma.c | 8 +-
drivers/gpu/drm/i915/intel_region_ttm.c | 17 +-
include/linux/compiler_types.h | 39 +++
include/linux/overflow.h | 138 ++++++--
lib/overflow_kunit.c | 101 ++++--
21 files changed, 618 insertions(+), 157 deletions(-)

--
2.37.1


2022-09-09 11:03:28

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 1/9] overflow: Allow mixed type arguments

From: Kees Cook <[email protected]>

When the check_[op]_overflow() helpers were introduced, all arguments were
required to be the same type to make the fallback macros simpler. However,
now that the fallback macros have been removed[1], it is fine to allow
mixed types, which makes using the helpers much more useful, as they
can be used to test for type-based overflows (e.g. adding two large ints
but storing into a u8), as would be handy in the drm core[2].

Remove the restriction, and add additional self-tests that exercise some
of the mixed-type overflow cases, and double-check for accidental macro
side-effects.

[1] https://git.kernel.org/linus/4eb6bd55cfb22ffc20652732340c4962f3ac9a91
[2] https://lore.kernel.org/lkml/[email protected]

Cc: Rasmus Villemoes <[email protected]>
Cc: Gwan-gyeong Mun <[email protected]>
Cc: Andrzej Hajda <[email protected]>
Cc: "Gustavo A. R. Silva" <[email protected]>
Cc: Nick Desaulniers <[email protected]>
Cc: [email protected]
Signed-off-by: Kees Cook <[email protected]>
---
include/linux/overflow.h | 72 ++++++++++++++++------------
lib/overflow_kunit.c | 101 ++++++++++++++++++++++++++++-----------
2 files changed, 113 insertions(+), 60 deletions(-)

diff --git a/include/linux/overflow.h b/include/linux/overflow.h
index 0eb3b192f07a..19dfdd74835e 100644
--- a/include/linux/overflow.h
+++ b/include/linux/overflow.h
@@ -51,40 +51,50 @@ static inline bool __must_check __must_check_overflow(bool overflow)
return unlikely(overflow);
}

-/*
- * For simplicity and code hygiene, the fallback code below insists on
- * a, b and *d having the same type (similar to the min() and max()
- * macros), whereas gcc's type-generic overflow checkers accept
- * different types. Hence we don't just make check_add_overflow an
- * alias for __builtin_add_overflow, but add type checks similar to
- * below.
+/** check_add_overflow() - Calculate addition with overflow checking
+ *
+ * @a: first addend
+ * @b: second addend
+ * @d: pointer to store sum
+ *
+ * Returns 0 on success.
+ *
+ * *@d holds the results of the attempted addition, but is not considered
+ * "safe for use" on a non-zero return value, which indicates that the
+ * sum has overflowed or been truncated.
*/
-#define check_add_overflow(a, b, d) __must_check_overflow(({ \
- typeof(a) __a = (a); \
- typeof(b) __b = (b); \
- typeof(d) __d = (d); \
- (void) (&__a == &__b); \
- (void) (&__a == __d); \
- __builtin_add_overflow(__a, __b, __d); \
-}))
+#define check_add_overflow(a, b, d) \
+ __must_check_overflow(__builtin_add_overflow(a, b, d))

-#define check_sub_overflow(a, b, d) __must_check_overflow(({ \
- typeof(a) __a = (a); \
- typeof(b) __b = (b); \
- typeof(d) __d = (d); \
- (void) (&__a == &__b); \
- (void) (&__a == __d); \
- __builtin_sub_overflow(__a, __b, __d); \
-}))
+/** check_sub_overflow() - Calculate subtraction with overflow checking
+ *
+ * @a: minuend; value to subtract from
+ * @b: subtrahend; value to subtract from @a
+ * @d: pointer to store difference
+ *
+ * Returns 0 on success.
+ *
+ * *@d holds the results of the attempted subtraction, but is not considered
+ * "safe for use" on a non-zero return value, which indicates that the
+ * difference has underflowed or been truncated.
+ */
+#define check_sub_overflow(a, b, d) \
+ __must_check_overflow(__builtin_sub_overflow(a, b, d))

-#define check_mul_overflow(a, b, d) __must_check_overflow(({ \
- typeof(a) __a = (a); \
- typeof(b) __b = (b); \
- typeof(d) __d = (d); \
- (void) (&__a == &__b); \
- (void) (&__a == __d); \
- __builtin_mul_overflow(__a, __b, __d); \
-}))
+/** check_mul_overflow() - Calculate multiplication with overflow checking
+ *
+ * @a: first factor
+ * @b: second factor
+ * @d: pointer to store product
+ *
+ * Returns 0 on success.
+ *
+ * *@d holds the results of the attempted multiplication, but is not
+ * considered "safe for use" on a non-zero return value, which indicates
+ * that the product has overflowed or been truncated.
+ */
+#define check_mul_overflow(a, b, d) \
+ __must_check_overflow(__builtin_mul_overflow(a, b, d))

/** check_shl_overflow() - Calculate a left-shifted value and check overflow
*
diff --git a/lib/overflow_kunit.c b/lib/overflow_kunit.c
index 7e3e43679b73..0d98c9bc75da 100644
--- a/lib/overflow_kunit.c
+++ b/lib/overflow_kunit.c
@@ -16,12 +16,15 @@
#include <linux/types.h>
#include <linux/vmalloc.h>

-#define DEFINE_TEST_ARRAY(t) \
- static const struct test_ ## t { \
- t a, b; \
- t sum, diff, prod; \
- bool s_of, d_of, p_of; \
- } t ## _tests[]
+#define DEFINE_TEST_ARRAY_TYPED(t1, t2, t) \
+ static const struct test_ ## t1 ## _ ## t2 ## __ ## t { \
+ t1 a; \
+ t2 b; \
+ t sum, diff, prod; \
+ bool s_of, d_of, p_of; \
+ } t1 ## _ ## t2 ## __ ## t ## _tests[]
+
+#define DEFINE_TEST_ARRAY(t) DEFINE_TEST_ARRAY_TYPED(t, t, t)

DEFINE_TEST_ARRAY(u8) = {
{0, 0, 0, 0, 0, false, false, false},
@@ -222,21 +225,27 @@ DEFINE_TEST_ARRAY(s64) = {
};
#endif

-#define check_one_op(t, fmt, op, sym, a, b, r, of) do { \
- t _r; \
- bool _of; \
- \
- _of = check_ ## op ## _overflow(a, b, &_r); \
- KUNIT_EXPECT_EQ_MSG(test, _of, of, \
+#define check_one_op(t, fmt, op, sym, a, b, r, of) do { \
+ int _a_orig = a, _a_bump = a + 1; \
+ int _b_orig = b, _b_bump = b + 1; \
+ bool _of; \
+ t _r; \
+ \
+ _of = check_ ## op ## _overflow(a, b, &_r); \
+ KUNIT_EXPECT_EQ_MSG(test, _of, of, \
"expected "fmt" "sym" "fmt" to%s overflow (type %s)\n", \
- a, b, of ? "" : " not", #t); \
- KUNIT_EXPECT_EQ_MSG(test, _r, r, \
+ a, b, of ? "" : " not", #t); \
+ KUNIT_EXPECT_EQ_MSG(test, _r, r, \
"expected "fmt" "sym" "fmt" == "fmt", got "fmt" (type %s)\n", \
- a, b, r, _r, #t); \
+ a, b, r, _r, #t); \
+ /* Check for internal macro side-effects. */ \
+ _of = check_ ## op ## _overflow(_a_orig++, _b_orig++, &_r); \
+ KUNIT_EXPECT_EQ_MSG(test, _a_orig, _a_bump, "Unexpected " #op " macro side-effect!\n"); \
+ KUNIT_EXPECT_EQ_MSG(test, _b_orig, _b_bump, "Unexpected " #op " macro side-effect!\n"); \
} while (0)

-#define DEFINE_TEST_FUNC(t, fmt) \
-static void do_test_ ## t(struct kunit *test, const struct test_ ## t *p) \
+#define DEFINE_TEST_FUNC_TYPED(n, t, fmt) \
+static void do_test_ ## n(struct kunit *test, const struct test_ ## n *p) \
{ \
check_one_op(t, fmt, add, "+", p->a, p->b, p->sum, p->s_of); \
check_one_op(t, fmt, add, "+", p->b, p->a, p->sum, p->s_of); \
@@ -245,15 +254,18 @@ static void do_test_ ## t(struct kunit *test, const struct test_ ## t *p) \
check_one_op(t, fmt, mul, "*", p->b, p->a, p->prod, p->p_of); \
} \
\
-static void t ## _overflow_test(struct kunit *test) { \
+static void n ## _overflow_test(struct kunit *test) { \
unsigned i; \
\
- for (i = 0; i < ARRAY_SIZE(t ## _tests); ++i) \
- do_test_ ## t(test, &t ## _tests[i]); \
+ for (i = 0; i < ARRAY_SIZE(n ## _tests); ++i) \
+ do_test_ ## n(test, &n ## _tests[i]); \
kunit_info(test, "%zu %s arithmetic tests finished\n", \
- ARRAY_SIZE(t ## _tests), #t); \
+ ARRAY_SIZE(n ## _tests), #n); \
}

+#define DEFINE_TEST_FUNC(t, fmt) \
+ DEFINE_TEST_FUNC_TYPED(t ## _ ## t ## __ ## t, t, fmt)
+
DEFINE_TEST_FUNC(u8, "%d");
DEFINE_TEST_FUNC(s8, "%d");
DEFINE_TEST_FUNC(u16, "%d");
@@ -265,6 +277,33 @@ DEFINE_TEST_FUNC(u64, "%llu");
DEFINE_TEST_FUNC(s64, "%lld");
#endif

+DEFINE_TEST_ARRAY_TYPED(u32, u32, u8) = {
+ {0, 0, 0, 0, 0, false, false, false},
+ {U8_MAX, 2, 1, U8_MAX - 2, U8_MAX - 1, true, false, true},
+ {U8_MAX + 1, 0, 0, 0, 0, true, true, false},
+};
+DEFINE_TEST_FUNC_TYPED(u32_u32__u8, u8, "%d");
+
+DEFINE_TEST_ARRAY_TYPED(u32, u32, int) = {
+ {0, 0, 0, 0, 0, false, false, false},
+ {U32_MAX, 0, -1, -1, 0, true, true, false},
+};
+DEFINE_TEST_FUNC_TYPED(u32_u32__int, int, "%d");
+
+DEFINE_TEST_ARRAY_TYPED(u8, u8, int) = {
+ {0, 0, 0, 0, 0, false, false, false},
+ {U8_MAX, U8_MAX, 2 * U8_MAX, 0, U8_MAX * U8_MAX, false, false, false},
+ {1, 2, 3, -1, 2, false, false, false},
+};
+DEFINE_TEST_FUNC_TYPED(u8_u8__int, int, "%d");
+
+DEFINE_TEST_ARRAY_TYPED(int, int, u8) = {
+ {0, 0, 0, 0, 0, false, false, false},
+ {1, 2, 3, U8_MAX, 2, false, true, false},
+ {-1, 0, U8_MAX, U8_MAX, 0, true, true, false},
+};
+DEFINE_TEST_FUNC_TYPED(int_int__u8, u8, "%d");
+
static void overflow_shift_test(struct kunit *test)
{
int count = 0;
@@ -649,17 +688,21 @@ static void overflow_size_helpers_test(struct kunit *test)
}

static struct kunit_case overflow_test_cases[] = {
- KUNIT_CASE(u8_overflow_test),
- KUNIT_CASE(s8_overflow_test),
- KUNIT_CASE(u16_overflow_test),
- KUNIT_CASE(s16_overflow_test),
- KUNIT_CASE(u32_overflow_test),
- KUNIT_CASE(s32_overflow_test),
+ KUNIT_CASE(u8_u8__u8_overflow_test),
+ KUNIT_CASE(s8_s8__s8_overflow_test),
+ KUNIT_CASE(u16_u16__u16_overflow_test),
+ KUNIT_CASE(s16_s16__s16_overflow_test),
+ KUNIT_CASE(u32_u32__u32_overflow_test),
+ KUNIT_CASE(s32_s32__s32_overflow_test),
/* Clang 13 and earlier generate unwanted libcalls on 32-bit. */
#if BITS_PER_LONG == 64
- KUNIT_CASE(u64_overflow_test),
- KUNIT_CASE(s64_overflow_test),
+ KUNIT_CASE(u64_u64__u64_overflow_test),
+ KUNIT_CASE(s64_s64__s64_overflow_test),
#endif
+ KUNIT_CASE(u32_u32__u8_overflow_test),
+ KUNIT_CASE(u32_u32__int_overflow_test),
+ KUNIT_CASE(u8_u8__int_overflow_test),
+ KUNIT_CASE(int_int__u8_overflow_test),
KUNIT_CASE(overflow_shift_test),
KUNIT_CASE(overflow_allocation_test),
KUNIT_CASE(overflow_size_helpers_test),
--
2.37.1

2022-09-09 11:03:36

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 2/9] overflow: Move and add few utility macros into overflow

It moves overflows_type utility macro into overflow header from i915_utils
header. The overflows_type can be used to catch the truncaion (overflow)
between different data types. And it adds check_assign() macro which
performs an assigning source value into destination pointer along with an
overflow check. overflow_type macro has been improved to handle the
different data types between source and destination by check_add_overflow
macro. It also adds check_assign_user_ptr macro which performs an assigning
source value into destination pointer type variable along with an overflow
check. If an explicit overflow check is required while assigning,
check_assign_user_ptr() can be used to assign integers into pointers along
with an overflow check.

v3: Add is_type_unsigned() macro (Mauro)
Modify overflows_type() macro to consider signed data types (Mauro)
Fix the problem that safe_conversion() macro always returns true
v4: Fix kernel-doc markups
v6: Move macro addition location so that it can be used by other than drm
subsystem (Jani, Mauro, Andi)
Change is_type_unsigned to is_unsigned_type to have the same name form
as is_signed_type macro
v8: Add check_assign() and remove safe_conversion() (Kees)
Fix overflows_type() to use gcc's built-in overflow function (Andrzej)
Add overflows_ptr() to allow overflow checking when assigning a value
into a pointer variable (G.G.)
v9: Fix overflows_type() to use __builtin_add_overflow() instead of
__builtin_add_overflow_p() (Andrzej)
Fix overflows_ptr() to use overflows_type() with the unsigned long type
(Andrzej)
v10: Remove a redundant type checking for a pointer. (Andrzej)
Use updated check_add_overflow macro instead of __builtin_add_overflow
(G.G)
Add check_assign_user_ptr() macro and drop overflows_ptr() macro(Kees)

Signed-off-by: Gwan-gyeong Mun <[email protected]>
Cc: Thomas Hellström <[email protected]>
Cc: Matthew Auld <[email protected]>
Cc: Nirmoy Das <[email protected]>
Cc: Jani Nikula <[email protected]>
Cc: Andi Shyti <[email protected]>
Cc: Andrzej Hajda <[email protected]>
Cc: Mauro Carvalho Chehab <[email protected]>
Cc: Kees Cook <[email protected]>
Reviewed-by: Mauro Carvalho Chehab <[email protected]> (v5)
Reviewed-by: Andrzej Hajda <[email protected]> (v9)
---
drivers/gpu/drm/i915/i915_user_extensions.c | 6 +-
drivers/gpu/drm/i915/i915_utils.h | 5 +-
include/linux/overflow.h | 64 +++++++++++++++++++++
3 files changed, 68 insertions(+), 7 deletions(-)

diff --git a/drivers/gpu/drm/i915/i915_user_extensions.c b/drivers/gpu/drm/i915/i915_user_extensions.c
index c822d0aafd2d..80ec8390b0d8 100644
--- a/drivers/gpu/drm/i915/i915_user_extensions.c
+++ b/drivers/gpu/drm/i915/i915_user_extensions.c
@@ -50,11 +50,11 @@ int i915_user_extensions(struct i915_user_extension __user *ext,
if (err)
return err;

- if (get_user(next, &ext->next_extension) ||
- overflows_type(next, ext))
+ if (get_user(next, &ext->next_extension))
return -EFAULT;

- ext = u64_to_user_ptr(next);
+ if (check_assign_user_ptr(next, ext))
+ return -EFAULT;
}

return 0;
diff --git a/drivers/gpu/drm/i915/i915_utils.h b/drivers/gpu/drm/i915/i915_utils.h
index 6c14d13364bf..efd3d69b78f7 100644
--- a/drivers/gpu/drm/i915/i915_utils.h
+++ b/drivers/gpu/drm/i915/i915_utils.h
@@ -32,6 +32,7 @@
#include <linux/types.h>
#include <linux/workqueue.h>
#include <linux/sched/clock.h>
+#include <linux/overflow.h>

#ifdef CONFIG_X86
#include <asm/hypervisor.h>
@@ -111,10 +112,6 @@ bool i915_error_injected(void);
#define range_overflows_end_t(type, start, size, max) \
range_overflows_end((type)(start), (type)(size), (type)(max))

-/* Note we don't consider signbits :| */
-#define overflows_type(x, T) \
- (sizeof(x) > sizeof(T) && (x) >> BITS_PER_TYPE(T))
-
#define ptr_mask_bits(ptr, n) ({ \
unsigned long __v = (unsigned long)(ptr); \
(typeof(ptr))(__v & -BIT(n)); \
diff --git a/include/linux/overflow.h b/include/linux/overflow.h
index 19dfdd74835e..9e8fc8f03e7a 100644
--- a/include/linux/overflow.h
+++ b/include/linux/overflow.h
@@ -5,6 +5,7 @@
#include <linux/compiler.h>
#include <linux/limits.h>
#include <linux/const.h>
+#include <linux/types.h>

/*
* We need to compute the minimum and maximum values representable in a given
@@ -127,6 +128,69 @@ static inline bool __must_check __must_check_overflow(bool overflow)
(*_d >> _to_shift) != _a); \
}))

+/**
+ * check_assign - perform an assigning source value into destination pointer
+ * along with an overflow check.
+ *
+ * @value: source value
+ * @ptr: Destination pointer address
+ *
+ * Returns:
+ * If the value would overflow the destination, it returns true. If not return
+ * false. When overflow does not occur, the assigning into destination from
+ * value succeeds. It follows the return policy as other check_*_overflow()
+ * functions return non-zero as a failure.
+ */
+#define check_assign(value, ptr) __must_check_overflow(({ \
+ check_add_overflow(0, value, ptr); \
+}))
+
+/**
+ * check_assign_user_ptr - perform an assigning source value into destination
+ * pointer type variable along with an overflow check
+ *
+ * @value: source value; a source value is expected to have a value of a size
+ * that can be stored in a pointer-type variable.
+ * @ptr: destination pointer type variable
+ *
+ * u64_to_user_ptr can be used in the kernel to avoid warnings about integers
+ * and pointers of different sizes. But u64_to_user_ptr is not performing the
+ * checking of overflow. If you need an explicit overflow check while
+ * assigning, check_assign_user_ptr() can be used to assign integers into
+ * pointers along with an overflow check. If ptr is not a pointer type,
+ * a warning message outputs while compiling.
+ *
+ * Returns:
+ * If the value would overflow the destination, it returns true. If not return
+ * false. When overflow does not occur, the assigning into ptr from value
+ * succeeds. It follows the return policy as other check_*_overflow() functions
+ * return non-zero as a failure.
+ */
+#define check_assign_user_ptr(value, ptr) __must_check_overflow(({ \
+ uintptr_t kptr; \
+ check_assign(value, &kptr) ? 1 : (({ ptr = (void * __user)kptr; }), 0); \
+}))
+
+/**
+ * overflows_type - helper for checking the overflows between data types or
+ * values
+ *
+ * @x: source value or data type for overflow check
+ * @T: destination value or data type for overflow check
+ *
+ * It compares the values or data type between the first and second argument to
+ * check whether overflow can occur when assigning the first argument to the
+ * variable of the second argument. Source and Destination can be different data
+ * types.
+ *
+ * Returns:
+ * True if overflow can occur, false otherwise.
+ */
+#define overflows_type(x, T) __must_check_overflow(({ \
+ typeof(T) v = 0; \
+ check_add_overflow((x), v, &v); \
+}))
+
/**
* size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
*
--
2.37.1

2022-09-09 11:13:00

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 6/9] drm/i915: Check for integer truncation on the configuration of ttm place

There is an impedance mismatch between the first/last valid page
frame number of ttm place in unsigned and our memory/page accounting in
unsigned long.
As the object size is under the control of userspace, we have to be prudent
and catch the conversion errors.
To catch the implicit truncation as we switch from unsigned long to
unsigned, we use overflows_type check and report E2BIG or overflow_type
prior to the operation.

v3: Not to change execution inside a macro. (Mauro)
Add safe_conversion_gem_bug_on() macro and remove temporal
SAFE_CONVERSION() macro.
v4: Fix unhandled GEM_BUG_ON() macro call from safe_conversion_gem_bug_on()
v6: Fix to follow general use case for GEM_BUG_ON(). (Jani)
v7: Fix to use WARN_ON() macro where GEM_BUG_ON() macro was used. (Jani)
v8: Replace safe_conversion() with check_assign() (Kees)

Signed-off-by: Gwan-gyeong Mun <[email protected]>
Cc: Chris Wilson <[email protected]>
Cc: Matthew Auld <[email protected]>
Cc: Thomas Hellström <[email protected]>
Cc: Jani Nikula <[email protected]>
Reviewed-by: Nirmoy Das <[email protected]> (v2)
Reviewed-by: Mauro Carvalho Chehab <[email protected]> (v3)
Reported-by: kernel test robot <[email protected]>
Reviewed-by: Andrzej Hajda <[email protected]> (v5)
---
drivers/gpu/drm/i915/gem/i915_gem_ttm.c | 6 +++---
drivers/gpu/drm/i915/intel_region_ttm.c | 17 ++++++++++++++---
2 files changed, 17 insertions(+), 6 deletions(-)

diff --git a/drivers/gpu/drm/i915/gem/i915_gem_ttm.c b/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
index 06a2e80a5702..6956d273fa5f 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
@@ -140,14 +140,14 @@ i915_ttm_place_from_region(const struct intel_memory_region *mr,
if (flags & I915_BO_ALLOC_CONTIGUOUS)
place->flags |= TTM_PL_FLAG_CONTIGUOUS;
if (offset != I915_BO_INVALID_OFFSET) {
- place->fpfn = offset >> PAGE_SHIFT;
- place->lpfn = place->fpfn + (size >> PAGE_SHIFT);
+ WARN_ON(check_assign(offset >> PAGE_SHIFT, &place->fpfn));
+ WARN_ON(check_assign(place->fpfn + (size >> PAGE_SHIFT), &place->lpfn));
} else if (mr->io_size && mr->io_size < mr->total) {
if (flags & I915_BO_ALLOC_GPU_ONLY) {
place->flags |= TTM_PL_FLAG_TOPDOWN;
} else {
place->fpfn = 0;
- place->lpfn = mr->io_size >> PAGE_SHIFT;
+ WARN_ON(check_assign(mr->io_size >> PAGE_SHIFT, &place->lpfn));
}
}
}
diff --git a/drivers/gpu/drm/i915/intel_region_ttm.c b/drivers/gpu/drm/i915/intel_region_ttm.c
index 575d67bc6ffe..37a964b20b36 100644
--- a/drivers/gpu/drm/i915/intel_region_ttm.c
+++ b/drivers/gpu/drm/i915/intel_region_ttm.c
@@ -209,14 +209,23 @@ intel_region_ttm_resource_alloc(struct intel_memory_region *mem,
if (flags & I915_BO_ALLOC_CONTIGUOUS)
place.flags |= TTM_PL_FLAG_CONTIGUOUS;
if (offset != I915_BO_INVALID_OFFSET) {
- place.fpfn = offset >> PAGE_SHIFT;
- place.lpfn = place.fpfn + (size >> PAGE_SHIFT);
+ if (WARN_ON(check_assign(offset >> PAGE_SHIFT, &place.fpfn))) {
+ ret = -E2BIG;
+ goto out;
+ }
+ if (WARN_ON(check_assign(place.fpfn + (size >> PAGE_SHIFT), &place.lpfn))) {
+ ret = -E2BIG;
+ goto out;
+ }
} else if (mem->io_size && mem->io_size < mem->total) {
if (flags & I915_BO_ALLOC_GPU_ONLY) {
place.flags |= TTM_PL_FLAG_TOPDOWN;
} else {
place.fpfn = 0;
- place.lpfn = mem->io_size >> PAGE_SHIFT;
+ if (WARN_ON(check_assign(mem->io_size >> PAGE_SHIFT, &place.lpfn))) {
+ ret = -E2BIG;
+ goto out;
+ }
}
}

@@ -224,6 +233,8 @@ intel_region_ttm_resource_alloc(struct intel_memory_region *mem,
mock_bo.bdev = &mem->i915->bdev;

ret = man->func->alloc(man, &mock_bo, &place, &res);
+
+out:
if (ret == -ENOSPC)
ret = -ENXIO;
if (!ret)
--
2.37.1

2022-09-09 11:15:00

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 7/9] drm/i915: Check if the size is too big while creating shmem file

The __shmem_file_setup() function returns -EINVAL if size is greater than
MAX_LFS_FILESIZE. To handle the same error as other code that returns
-E2BIG when the size is too large, it add a code that returns -E2BIG when
the size is larger than the size that can be handled.

v4: If BITS_PER_LONG is 32, size > MAX_LFS_FILESIZE is always false, so it
checks only when BITS_PER_LONG is 64.

Signed-off-by: Gwan-gyeong Mun <[email protected]>
Cc: Chris Wilson <[email protected]>
Cc: Matthew Auld <[email protected]>
Cc: Thomas Hellström <[email protected]>
Reviewed-by: Nirmoy Das <[email protected]>
Reviewed-by: Mauro Carvalho Chehab <[email protected]>
Reported-by: kernel test robot <[email protected]>
Reviewed-by: Andrzej Hajda <[email protected]>
---
drivers/gpu/drm/i915/gem/i915_gem_shmem.c | 14 ++++++++++++++
1 file changed, 14 insertions(+)

diff --git a/drivers/gpu/drm/i915/gem/i915_gem_shmem.c b/drivers/gpu/drm/i915/gem/i915_gem_shmem.c
index 339b0a9cf2d0..ca30060e34ab 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_shmem.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_shmem.c
@@ -541,6 +541,20 @@ static int __create_shmem(struct drm_i915_private *i915,

drm_gem_private_object_init(&i915->drm, obj, size);

+ /* XXX: The __shmem_file_setup() function returns -EINVAL if size is
+ * greater than MAX_LFS_FILESIZE.
+ * To handle the same error as other code that returns -E2BIG when
+ * the size is too large, we add a code that returns -E2BIG when the
+ * size is larger than the size that can be handled.
+ * If BITS_PER_LONG is 32, size > MAX_LFS_FILESIZE is always false,
+ * so we only needs to check when BITS_PER_LONG is 64.
+ * If BITS_PER_LONG is 32, E2BIG checks are processed when
+ * i915_gem_object_size_2big() is called before init_object() callback
+ * is called.
+ */
+ if (BITS_PER_LONG == 64 && size > MAX_LFS_FILESIZE)
+ return -E2BIG;
+
if (i915->mm.gemfs)
filp = shmem_file_setup_with_mnt(i915->mm.gemfs, "i915", size,
flags);
--
2.37.1

2022-09-09 11:17:07

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 4/9] drm/i915/gem: Typecheck page lookups

From: Chris Wilson <[email protected]>

We need to check that we avoid integer overflows when looking up a page,
and so fix all the instances where we have mistakenly used a plain
integer instead of a more suitable long. Be pedantic and add integer
typechecking to the lookup so that we can be sure that we are safe.
And it also uses pgoff_t as our page lookups must remain compatible with
the page cache, pgoff_t is currently exactly unsigned long.

v2: Move added i915_utils's macro into drm_util header (Jani N)
v3: Make not use the same macro name on a function. (Mauro)
For kernel-doc, macros and functions are handled in the same namespace,
the same macro name on a function prevents ever adding documentation
for it.
v4: Add kernel-doc markups to the kAPI functions and macros (Mauoro)
v5: Fix an alignment to match open parenthesis
v6: Rebase
v10: Use assert_typable instead of exactly_pgoff_t() macro. (Kees)

Signed-off-by: Chris Wilson <[email protected]>
Signed-off-by: Gwan-gyeong Mun <[email protected]>
Cc: Tvrtko Ursulin <[email protected]>
Cc: Matthew Auld <[email protected]>
Cc: Thomas Hellström <[email protected]>
Cc: Kees Cook <[email protected]>
Reviewed-by: Nirmoy Das <[email protected]> (v2)
Reviewed-by: Mauro Carvalho Chehab <[email protected]> (v3)
Reviewed-by: Andrzej Hajda <[email protected]> (v5)
---
drivers/gpu/drm/i915/gem/i915_gem_object.c | 7 +-
drivers/gpu/drm/i915/gem/i915_gem_object.h | 293 ++++++++++++++++--
drivers/gpu/drm/i915/gem/i915_gem_pages.c | 27 +-
drivers/gpu/drm/i915/gem/i915_gem_ttm.c | 2 +-
.../drm/i915/gem/selftests/i915_gem_context.c | 12 +-
.../drm/i915/gem/selftests/i915_gem_mman.c | 8 +-
.../drm/i915/gem/selftests/i915_gem_object.c | 8 +-
drivers/gpu/drm/i915/i915_gem.c | 18 +-
drivers/gpu/drm/i915/i915_utils.h | 1 +
drivers/gpu/drm/i915/i915_vma.c | 8 +-
10 files changed, 323 insertions(+), 61 deletions(-)

diff --git a/drivers/gpu/drm/i915/gem/i915_gem_object.c b/drivers/gpu/drm/i915/gem/i915_gem_object.c
index 85482a04d158..22a8c10eccec 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_object.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_object.c
@@ -413,10 +413,11 @@ void __i915_gem_object_invalidate_frontbuffer(struct drm_i915_gem_object *obj,
static void
i915_gem_object_read_from_page_kmap(struct drm_i915_gem_object *obj, u64 offset, void *dst, int size)
{
+ pgoff_t idx = offset >> PAGE_SHIFT;
void *src_map;
void *src_ptr;

- src_map = kmap_atomic(i915_gem_object_get_page(obj, offset >> PAGE_SHIFT));
+ src_map = kmap_atomic(i915_gem_object_get_page(obj, idx));

src_ptr = src_map + offset_in_page(offset);
if (!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
@@ -429,9 +430,10 @@ i915_gem_object_read_from_page_kmap(struct drm_i915_gem_object *obj, u64 offset,
static void
i915_gem_object_read_from_page_iomap(struct drm_i915_gem_object *obj, u64 offset, void *dst, int size)
{
+ pgoff_t idx = offset >> PAGE_SHIFT;
+ dma_addr_t dma = i915_gem_object_get_dma_address(obj, idx);
void __iomem *src_map;
void __iomem *src_ptr;
- dma_addr_t dma = i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT);

src_map = io_mapping_map_wc(&obj->mm.region->iomap,
dma - obj->mm.region->region.start,
@@ -460,6 +462,7 @@ i915_gem_object_read_from_page_iomap(struct drm_i915_gem_object *obj, u64 offset
*/
int i915_gem_object_read_from_page(struct drm_i915_gem_object *obj, u64 offset, void *dst, int size)
{
+ GEM_BUG_ON(overflows_type(offset >> PAGE_SHIFT, pgoff_t));
GEM_BUG_ON(offset >= obj->base.size);
GEM_BUG_ON(offset_in_page(offset) > PAGE_SIZE - size);
GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
diff --git a/drivers/gpu/drm/i915/gem/i915_gem_object.h b/drivers/gpu/drm/i915/gem/i915_gem_object.h
index 7317d4102955..8dd2b84468c8 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_object.h
+++ b/drivers/gpu/drm/i915/gem/i915_gem_object.h
@@ -27,8 +27,10 @@ enum intel_region_id;
* spot such a local variable, please consider fixing!
*
* Aside from our own locals (for which we have no excuse!):
- * - sg_table embeds unsigned int for num_pages
- * - get_user_pages*() mixed ints with longs
+ * - sg_table embeds unsigned int for nents
+ *
+ * We can check for invalidly typed locals with typecheck(), see for example
+ * i915_gem_object_get_sg().
*/
#define GEM_CHECK_SIZE_OVERFLOW(sz) \
GEM_WARN_ON((sz) >> PAGE_SHIFT > INT_MAX)
@@ -363,44 +365,289 @@ i915_gem_object_get_tile_row_size(const struct drm_i915_gem_object *obj)
int i915_gem_object_set_tiling(struct drm_i915_gem_object *obj,
unsigned int tiling, unsigned int stride);

+/**
+ * __i915_gem_object_page_iter_get_sg - helper to find the target scatterlist
+ * pointer and the target page position using pgoff_t n input argument and
+ * i915_gem_object_page_iter
+ * @obj: i915 GEM buffer object
+ * @iter: i915 GEM buffer object page iterator
+ * @n: page offset
+ * @offset: searched physical offset,
+ * it will be used for returning physical page offset value
+ *
+ * Context: Takes and releases the mutex lock of the i915_gem_object_page_iter.
+ * Takes and releases the RCU lock to search the radix_tree of
+ * i915_gem_object_page_iter.
+ *
+ * Returns:
+ * The target scatterlist pointer and the target page position.
+ *
+ * Recommended to use wrapper macro: i915_gem_object_page_iter_get_sg()
+ */
struct scatterlist *
-__i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
- struct i915_gem_object_page_iter *iter,
- unsigned int n,
- unsigned int *offset, bool dma);
+__i915_gem_object_page_iter_get_sg(struct drm_i915_gem_object *obj,
+ struct i915_gem_object_page_iter *iter,
+ pgoff_t n,
+ unsigned int *offset);

+/**
+ * i915_gem_object_page_iter_get_sg - wrapper macro for
+ * __i915_gem_object_page_iter_get_sg()
+ * @obj: i915 GEM buffer object
+ * @it: i915 GEM buffer object page iterator
+ * @n: page offset
+ * @offset: searched physical offset,
+ * it will be used for returning physical page offset value
+ *
+ * Context: Takes and releases the mutex lock of the i915_gem_object_page_iter.
+ * Takes and releases the RCU lock to search the radix_tree of
+ * i915_gem_object_page_iter.
+ *
+ * Returns:
+ * The target scatterlist pointer and the target page position.
+ *
+ * In order to avoid the truncation of the input parameter, it checks the page
+ * offset n's type from the input parameter before calling
+ * __i915_gem_object_page_iter_get_sg().
+ */
+#define i915_gem_object_page_iter_get_sg(obj, it, n, offset) ({ \
+ assert_typable(pgoff_t, n); \
+ __i915_gem_object_page_iter_get_sg(obj, it, n, offset); \
+})
+
+/**
+ * __i915_gem_object_get_sg - helper to find the target scatterlist
+ * pointer and the target page position using pgoff_t n input argument and
+ * drm_i915_gem_object. It uses an internal shmem scatterlist lookup function.
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ * @offset: searched physical offset,
+ * it will be used for returning physical page offset value
+ *
+ * It uses drm_i915_gem_object's internal shmem scatterlist lookup function as
+ * i915_gem_object_page_iter and calls __i915_gem_object_page_iter_get_sg().
+ *
+ * Returns:
+ * The target scatterlist pointer and the target page position.
+ *
+ * Recommended to use wrapper macro: i915_gem_object_get_sg()
+ * See also __i915_gem_object_page_iter_get_sg()
+ */
static inline struct scatterlist *
-i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
- unsigned int n,
- unsigned int *offset)
+__i915_gem_object_get_sg(struct drm_i915_gem_object *obj, pgoff_t n,
+ unsigned int *offset)
{
- return __i915_gem_object_get_sg(obj, &obj->mm.get_page, n, offset, false);
+ return __i915_gem_object_page_iter_get_sg(obj, &obj->mm.get_page, n, offset);
}

+/**
+ * i915_gem_object_get_sg - wrapper macro for __i915_gem_object_get_sg()
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ * @offset: searched physical offset,
+ * it will be used for returning physical page offset value
+ *
+ * Returns:
+ * The target scatterlist pointer and the target page position.
+ *
+ * In order to avoid the truncation of the input parameter, it checks the page
+ * offset n's type from the input parameter before calling
+ * __i915_gem_object_get_sg().
+ * See also __i915_gem_object_page_iter_get_sg()
+ */
+#define i915_gem_object_get_sg(obj, n, offset) ({ \
+ assert_typable(pgoff_t, n); \
+ __i915_gem_object_get_sg(obj, n, offset); \
+})
+
+/**
+ * __i915_gem_object_get_sg_dma - helper to find the target scatterlist
+ * pointer and the target page position using pgoff_t n input argument and
+ * drm_i915_gem_object. It uses an internal DMA mapped scatterlist lookup function
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ * @offset: searched physical offset,
+ * it will be used for returning physical page offset value
+ *
+ * It uses drm_i915_gem_object's internal DMA mapped scatterlist lookup function
+ * as i915_gem_object_page_iter and calls __i915_gem_object_page_iter_get_sg().
+ *
+ * Returns:
+ * The target scatterlist pointer and the target page position.
+ *
+ * Recommended to use wrapper macro: i915_gem_object_get_sg_dma()
+ * See also __i915_gem_object_page_iter_get_sg()
+ */
static inline struct scatterlist *
-i915_gem_object_get_sg_dma(struct drm_i915_gem_object *obj,
- unsigned int n,
- unsigned int *offset)
+__i915_gem_object_get_sg_dma(struct drm_i915_gem_object *obj, pgoff_t n,
+ unsigned int *offset)
{
- return __i915_gem_object_get_sg(obj, &obj->mm.get_dma_page, n, offset, true);
+ return __i915_gem_object_page_iter_get_sg(obj, &obj->mm.get_dma_page, n, offset);
}

+/**
+ * i915_gem_object_get_sg_dma - wrapper macro for __i915_gem_object_get_sg_dma()
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ * @offset: searched physical offset,
+ * it will be used for returning physical page offset value
+ *
+ * Returns:
+ * The target scatterlist pointer and the target page position.
+ *
+ * In order to avoid the truncation of the input parameter, it checks the page
+ * offset n's type from the input parameter before calling
+ * __i915_gem_object_get_sg_dma().
+ * See also __i915_gem_object_page_iter_get_sg()
+ */
+#define i915_gem_object_get_sg_dma(obj, n, offset) ({ \
+ assert_typable(pgoff_t, n); \
+ __i915_gem_object_get_sg_dma(obj, n, offset); \
+})
+
+/**
+ * __i915_gem_object_get_page - helper to find the target page with a page offset
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ *
+ * It uses drm_i915_gem_object's internal shmem scatterlist lookup function as
+ * i915_gem_object_page_iter and calls __i915_gem_object_page_iter_get_sg()
+ * internally.
+ *
+ * Returns:
+ * The target page pointer.
+ *
+ * Recommended to use wrapper macro: i915_gem_object_get_page()
+ * See also __i915_gem_object_page_iter_get_sg()
+ */
struct page *
-i915_gem_object_get_page(struct drm_i915_gem_object *obj,
- unsigned int n);
+__i915_gem_object_get_page(struct drm_i915_gem_object *obj, pgoff_t n);

+/**
+ * i915_gem_object_get_page - wrapper macro for __i915_gem_object_get_page
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ *
+ * Returns:
+ * The target page pointer.
+ *
+ * In order to avoid the truncation of the input parameter, it checks the page
+ * offset n's type from the input parameter before calling
+ * __i915_gem_object_get_page().
+ * See also __i915_gem_object_page_iter_get_sg()
+ */
+#define i915_gem_object_get_page(obj, n) ({ \
+ assert_typable(pgoff_t, n); \
+ __i915_gem_object_get_page(obj, n); \
+})
+
+/**
+ * __i915_gem_object_get_dirty_page - helper to find the target page with a page
+ * offset
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ *
+ * It works like i915_gem_object_get_page(), but it marks the returned page dirty.
+ *
+ * Returns:
+ * The target page pointer.
+ *
+ * Recommended to use wrapper macro: i915_gem_object_get_dirty_page()
+ * See also __i915_gem_object_page_iter_get_sg() and __i915_gem_object_get_page()
+ */
struct page *
-i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
- unsigned int n);
+__i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj, pgoff_t n);
+
+/**
+ * i915_gem_object_get_dirty_page - wrapper macro for __i915_gem_object_get_dirty_page
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ *
+ * Returns:
+ * The target page pointer.
+ *
+ * In order to avoid the truncation of the input parameter, it checks the page
+ * offset n's type from the input parameter before calling
+ * __i915_gem_object_get_dirty_page().
+ * See also __i915_gem_object_page_iter_get_sg() and __i915_gem_object_get_page()
+ */
+#define i915_gem_object_get_dirty_page(obj, n) ({ \
+ assert_typable(pgoff_t, n); \
+ __i915_gem_object_get_dirty_page(obj, n); \
+})

+/**
+ * __i915_gem_object_get_dma_address_len - helper to get bus addresses of
+ * targeted DMA mapped scatterlist from i915 GEM buffer object and it's length
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ * @len: DMA mapped scatterlist's DMA bus addresses length to return
+ *
+ * Returns:
+ * Bus addresses of targeted DMA mapped scatterlist
+ *
+ * Recommended to use wrapper macro: i915_gem_object_get_dma_address_len()
+ * See also __i915_gem_object_page_iter_get_sg() and __i915_gem_object_get_sg_dma()
+ */
dma_addr_t
-i915_gem_object_get_dma_address_len(struct drm_i915_gem_object *obj,
- unsigned long n,
- unsigned int *len);
+__i915_gem_object_get_dma_address_len(struct drm_i915_gem_object *obj, pgoff_t n,
+ unsigned int *len);

+/**
+ * i915_gem_object_get_dma_address_len - wrapper macro for
+ * __i915_gem_object_get_dma_address_len
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ * @len: DMA mapped scatterlist's DMA bus addresses length to return
+ *
+ * Returns:
+ * Bus addresses of targeted DMA mapped scatterlist
+ *
+ * In order to avoid the truncation of the input parameter, it checks the page
+ * offset n's type from the input parameter before calling
+ * __i915_gem_object_get_dma_address_len().
+ * See also __i915_gem_object_page_iter_get_sg() and
+ * __i915_gem_object_get_dma_address_len()
+ */
+#define i915_gem_object_get_dma_address_len(obj, n, len) ({ \
+ assert_typable(pgoff_t, n); \
+ __i915_gem_object_get_dma_address_len(obj, n, len); \
+})
+
+/**
+ * __i915_gem_object_get_dma_address - helper to get bus addresses of
+ * targeted DMA mapped scatterlist from i915 GEM buffer object
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ *
+ * Returns:
+ * Bus addresses of targeted DMA mapped scatterlis
+ *
+ * Recommended to use wrapper macro: i915_gem_object_get_dma_address()
+ * See also __i915_gem_object_page_iter_get_sg() and __i915_gem_object_get_sg_dma()
+ */
dma_addr_t
-i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
- unsigned long n);
+__i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj, pgoff_t n);
+
+/**
+ * i915_gem_object_get_dma_address - wrapper macro for
+ * __i915_gem_object_get_dma_address
+ * @obj: i915 GEM buffer object
+ * @n: page offset
+ *
+ * Returns:
+ * Bus addresses of targeted DMA mapped scatterlist
+ *
+ * In order to avoid the truncation of the input parameter, it checks the page
+ * offset n's type from the input parameter before calling
+ * __i915_gem_object_get_dma_address().
+ * See also __i915_gem_object_page_iter_get_sg() and
+ * __i915_gem_object_get_dma_address()
+ */
+#define i915_gem_object_get_dma_address(obj, n) ({ \
+ assert_typable(pgoff_t, n); \
+ __i915_gem_object_get_dma_address(obj, n); \
+})

void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
struct sg_table *pages,
diff --git a/drivers/gpu/drm/i915/gem/i915_gem_pages.c b/drivers/gpu/drm/i915/gem/i915_gem_pages.c
index 4df50b049cea..015b6cd071e4 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_pages.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_pages.c
@@ -510,14 +510,16 @@ void __i915_gem_object_release_map(struct drm_i915_gem_object *obj)
}

struct scatterlist *
-__i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
- struct i915_gem_object_page_iter *iter,
- unsigned int n,
- unsigned int *offset,
- bool dma)
+__i915_gem_object_page_iter_get_sg(struct drm_i915_gem_object *obj,
+ struct i915_gem_object_page_iter *iter,
+ pgoff_t n,
+ unsigned int *offset)
+
{
- struct scatterlist *sg;
+ const bool dma = iter == &obj->mm.get_dma_page ||
+ iter == &obj->ttm.get_io_page;
unsigned int idx, count;
+ struct scatterlist *sg;

might_sleep();
GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
@@ -625,7 +627,7 @@ __i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
}

struct page *
-i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
+__i915_gem_object_get_page(struct drm_i915_gem_object *obj, pgoff_t n)
{
struct scatterlist *sg;
unsigned int offset;
@@ -638,8 +640,7 @@ i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)

/* Like i915_gem_object_get_page(), but mark the returned page dirty */
struct page *
-i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
- unsigned int n)
+__i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj, pgoff_t n)
{
struct page *page;

@@ -651,9 +652,8 @@ i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
}

dma_addr_t
-i915_gem_object_get_dma_address_len(struct drm_i915_gem_object *obj,
- unsigned long n,
- unsigned int *len)
+__i915_gem_object_get_dma_address_len(struct drm_i915_gem_object *obj,
+ pgoff_t n, unsigned int *len)
{
struct scatterlist *sg;
unsigned int offset;
@@ -667,8 +667,7 @@ i915_gem_object_get_dma_address_len(struct drm_i915_gem_object *obj,
}

dma_addr_t
-i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
- unsigned long n)
+__i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj, pgoff_t n)
{
return i915_gem_object_get_dma_address_len(obj, n, NULL);
}
diff --git a/drivers/gpu/drm/i915/gem/i915_gem_ttm.c b/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
index f64a3deb12fc..b6c813d69ffa 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
@@ -685,7 +685,7 @@ static unsigned long i915_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
GEM_WARN_ON(bo->ttm);

base = obj->mm.region->iomap.base - obj->mm.region->region.start;
- sg = __i915_gem_object_get_sg(obj, &obj->ttm.get_io_page, page_offset, &ofs, true);
+ sg = i915_gem_object_page_iter_get_sg(obj, &obj->ttm.get_io_page, page_offset, &ofs);

return ((base + sg_dma_address(sg)) >> PAGE_SHIFT) + ofs;
}
diff --git a/drivers/gpu/drm/i915/gem/selftests/i915_gem_context.c b/drivers/gpu/drm/i915/gem/selftests/i915_gem_context.c
index c6ad67b90e8a..a18a890e681f 100644
--- a/drivers/gpu/drm/i915/gem/selftests/i915_gem_context.c
+++ b/drivers/gpu/drm/i915/gem/selftests/i915_gem_context.c
@@ -455,7 +455,8 @@ static int gpu_fill(struct intel_context *ce,
static int cpu_fill(struct drm_i915_gem_object *obj, u32 value)
{
const bool has_llc = HAS_LLC(to_i915(obj->base.dev));
- unsigned int n, m, need_flush;
+ unsigned int need_flush;
+ unsigned long n, m;
int err;

i915_gem_object_lock(obj, NULL);
@@ -485,7 +486,8 @@ static int cpu_fill(struct drm_i915_gem_object *obj, u32 value)
static noinline int cpu_check(struct drm_i915_gem_object *obj,
unsigned int idx, unsigned int max)
{
- unsigned int n, m, needs_flush;
+ unsigned int needs_flush;
+ unsigned long n;
int err;

i915_gem_object_lock(obj, NULL);
@@ -494,7 +496,7 @@ static noinline int cpu_check(struct drm_i915_gem_object *obj,
goto out_unlock;

for (n = 0; n < real_page_count(obj); n++) {
- u32 *map;
+ u32 *map, m;

map = kmap_atomic(i915_gem_object_get_page(obj, n));
if (needs_flush & CLFLUSH_BEFORE)
@@ -502,7 +504,7 @@ static noinline int cpu_check(struct drm_i915_gem_object *obj,

for (m = 0; m < max; m++) {
if (map[m] != m) {
- pr_err("%pS: Invalid value at object %d page %d/%ld, offset %d/%d: found %x expected %x\n",
+ pr_err("%pS: Invalid value at object %d page %ld/%ld, offset %d/%d: found %x expected %x\n",
__builtin_return_address(0), idx,
n, real_page_count(obj), m, max,
map[m], m);
@@ -513,7 +515,7 @@ static noinline int cpu_check(struct drm_i915_gem_object *obj,

for (; m < DW_PER_PAGE; m++) {
if (map[m] != STACK_MAGIC) {
- pr_err("%pS: Invalid value at object %d page %d, offset %d: found %x expected %x (uninitialised)\n",
+ pr_err("%pS: Invalid value at object %d page %ld, offset %d: found %x expected %x (uninitialised)\n",
__builtin_return_address(0), idx, n, m,
map[m], STACK_MAGIC);
err = -EINVAL;
diff --git a/drivers/gpu/drm/i915/gem/selftests/i915_gem_mman.c b/drivers/gpu/drm/i915/gem/selftests/i915_gem_mman.c
index b73c91aa5450..4ea6e48d8689 100644
--- a/drivers/gpu/drm/i915/gem/selftests/i915_gem_mman.c
+++ b/drivers/gpu/drm/i915/gem/selftests/i915_gem_mman.c
@@ -95,11 +95,11 @@ static int check_partial_mapping(struct drm_i915_gem_object *obj,
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct i915_gtt_view view;
struct i915_vma *vma;
+ unsigned long offset;
unsigned long page;
u32 __iomem *io;
struct page *p;
unsigned int n;
- u64 offset;
u32 *cpu;
int err;

@@ -156,7 +156,7 @@ static int check_partial_mapping(struct drm_i915_gem_object *obj,
cpu = kmap(p) + offset_in_page(offset);
drm_clflush_virt_range(cpu, sizeof(*cpu));
if (*cpu != (u32)page) {
- pr_err("Partial view for %lu [%u] (offset=%llu, size=%u [%llu, row size %u], fence=%d, tiling=%d, stride=%d) misalignment, expected write to page (%llu + %u [0x%llx]) of 0x%x, found 0x%x\n",
+ pr_err("Partial view for %lu [%u] (offset=%llu, size=%u [%llu, row size %u], fence=%d, tiling=%d, stride=%d) misalignment, expected write to page (%lu + %u [0x%lx]) of 0x%x, found 0x%x\n",
page, n,
view.partial.offset,
view.partial.size,
@@ -212,10 +212,10 @@ static int check_partial_mappings(struct drm_i915_gem_object *obj,
for_each_prime_number_from(page, 1, npages) {
struct i915_gtt_view view =
compute_partial_view(obj, page, MIN_CHUNK_PAGES);
+ unsigned long offset;
u32 __iomem *io;
struct page *p;
unsigned int n;
- u64 offset;
u32 *cpu;

GEM_BUG_ON(view.partial.size > nreal);
@@ -252,7 +252,7 @@ static int check_partial_mappings(struct drm_i915_gem_object *obj,
cpu = kmap(p) + offset_in_page(offset);
drm_clflush_virt_range(cpu, sizeof(*cpu));
if (*cpu != (u32)page) {
- pr_err("Partial view for %lu [%u] (offset=%llu, size=%u [%llu, row size %u], fence=%d, tiling=%d, stride=%d) misalignment, expected write to page (%llu + %u [0x%llx]) of 0x%x, found 0x%x\n",
+ pr_err("Partial view for %lu [%u] (offset=%llu, size=%u [%llu, row size %u], fence=%d, tiling=%d, stride=%d) misalignment, expected write to page (%lu + %u [0x%lx]) of 0x%x, found 0x%x\n",
page, n,
view.partial.offset,
view.partial.size,
diff --git a/drivers/gpu/drm/i915/gem/selftests/i915_gem_object.c b/drivers/gpu/drm/i915/gem/selftests/i915_gem_object.c
index bdf5bb40ccf1..19e374f68ff7 100644
--- a/drivers/gpu/drm/i915/gem/selftests/i915_gem_object.c
+++ b/drivers/gpu/drm/i915/gem/selftests/i915_gem_object.c
@@ -33,10 +33,10 @@ static int igt_gem_object(void *arg)

static int igt_gem_huge(void *arg)
{
- const unsigned int nreal = 509; /* just to be awkward */
+ const unsigned long nreal = 509; /* just to be awkward */
struct drm_i915_private *i915 = arg;
struct drm_i915_gem_object *obj;
- unsigned int n;
+ unsigned long n;
int err;

/* Basic sanitycheck of our huge fake object allocation */
@@ -49,7 +49,7 @@ static int igt_gem_huge(void *arg)

err = i915_gem_object_pin_pages_unlocked(obj);
if (err) {
- pr_err("Failed to allocate %u pages (%lu total), err=%d\n",
+ pr_err("Failed to allocate %lu pages (%lu total), err=%d\n",
nreal, obj->base.size / PAGE_SIZE, err);
goto out;
}
@@ -57,7 +57,7 @@ static int igt_gem_huge(void *arg)
for (n = 0; n < obj->base.size / PAGE_SIZE; n++) {
if (i915_gem_object_get_page(obj, n) !=
i915_gem_object_get_page(obj, n % nreal)) {
- pr_err("Page lookup mismatch at index %u [%u]\n",
+ pr_err("Page lookup mismatch at index %lu [%lu]\n",
n, n % nreal);
err = -EINVAL;
goto out_unpin;
diff --git a/drivers/gpu/drm/i915/i915_gem.c b/drivers/gpu/drm/i915/i915_gem.c
index bae857d5221d..d82fc4abc348 100644
--- a/drivers/gpu/drm/i915/i915_gem.c
+++ b/drivers/gpu/drm/i915/i915_gem.c
@@ -229,8 +229,9 @@ i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
struct drm_i915_gem_pread *args)
{
unsigned int needs_clflush;
- unsigned int idx, offset;
char __user *user_data;
+ unsigned long offset;
+ pgoff_t idx;
u64 remain;
int ret;

@@ -383,13 +384,17 @@ i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
{
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
+ unsigned long remain, offset;
intel_wakeref_t wakeref;
struct drm_mm_node node;
void __user *user_data;
struct i915_vma *vma;
- u64 remain, offset;
int ret = 0;

+ if (overflows_type(args->size, remain) ||
+ overflows_type(args->offset, offset))
+ return -EINVAL;
+
wakeref = intel_runtime_pm_get(&i915->runtime_pm);

vma = i915_gem_gtt_prepare(obj, &node, false);
@@ -540,13 +545,17 @@ i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
struct intel_runtime_pm *rpm = &i915->runtime_pm;
+ unsigned long remain, offset;
intel_wakeref_t wakeref;
struct drm_mm_node node;
struct i915_vma *vma;
- u64 remain, offset;
void __user *user_data;
int ret = 0;

+ if (overflows_type(args->size, remain) ||
+ overflows_type(args->offset, offset))
+ return -EINVAL;
+
if (i915_gem_object_has_struct_page(obj)) {
/*
* Avoid waking the device up if we can fallback, as
@@ -654,8 +663,9 @@ i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
{
unsigned int partial_cacheline_write;
unsigned int needs_clflush;
- unsigned int offset, idx;
void __user *user_data;
+ unsigned long offset;
+ pgoff_t idx;
u64 remain;
int ret;

diff --git a/drivers/gpu/drm/i915/i915_utils.h b/drivers/gpu/drm/i915/i915_utils.h
index efd3d69b78f7..d2144986cbf1 100644
--- a/drivers/gpu/drm/i915/i915_utils.h
+++ b/drivers/gpu/drm/i915/i915_utils.h
@@ -33,6 +33,7 @@
#include <linux/workqueue.h>
#include <linux/sched/clock.h>
#include <linux/overflow.h>
+#include <linux/util_macros.h>

#ifdef CONFIG_X86
#include <asm/hypervisor.h>
diff --git a/drivers/gpu/drm/i915/i915_vma.c b/drivers/gpu/drm/i915/i915_vma.c
index f17c09ead7d7..bf3a30cd02bf 100644
--- a/drivers/gpu/drm/i915/i915_vma.c
+++ b/drivers/gpu/drm/i915/i915_vma.c
@@ -909,7 +909,7 @@ rotate_pages(struct drm_i915_gem_object *obj, unsigned int offset,
struct sg_table *st, struct scatterlist *sg)
{
unsigned int column, row;
- unsigned int src_idx;
+ pgoff_t src_idx;

for (column = 0; column < width; column++) {
unsigned int left;
@@ -1015,7 +1015,7 @@ add_padding_pages(unsigned int count,

static struct scatterlist *
remap_tiled_color_plane_pages(struct drm_i915_gem_object *obj,
- unsigned int offset, unsigned int alignment_pad,
+ unsigned long offset, unsigned int alignment_pad,
unsigned int width, unsigned int height,
unsigned int src_stride, unsigned int dst_stride,
struct sg_table *st, struct scatterlist *sg,
@@ -1074,7 +1074,7 @@ remap_tiled_color_plane_pages(struct drm_i915_gem_object *obj,

static struct scatterlist *
remap_contiguous_pages(struct drm_i915_gem_object *obj,
- unsigned int obj_offset,
+ pgoff_t obj_offset,
unsigned int count,
struct sg_table *st, struct scatterlist *sg)
{
@@ -1107,7 +1107,7 @@ remap_contiguous_pages(struct drm_i915_gem_object *obj,

static struct scatterlist *
remap_linear_color_plane_pages(struct drm_i915_gem_object *obj,
- unsigned int obj_offset, unsigned int alignment_pad,
+ pgoff_t obj_offset, unsigned int alignment_pad,
unsigned int size,
struct sg_table *st, struct scatterlist *sg,
unsigned int *gtt_offset)
--
2.37.1

2022-09-09 11:18:29

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 8/9] drm/i915: Use error code as -E2BIG when the size of gem ttm object is too large

The ttm_bo_init_reserved() functions returns -ENOSPC if the size is too big
to add vma. The direct function that returns -ENOSPC is drm_mm_insert_node_in_range().
To handle the same error as other code returning -E2BIG when the size is
too large, it converts return value to -E2BIG.

Signed-off-by: Gwan-gyeong Mun <[email protected]>
Cc: Chris Wilson <[email protected]>
Cc: Matthew Auld <[email protected]>
Cc: Thomas Hellström <[email protected]>
Reviewed-by: Nirmoy Das <[email protected]>
Reviewed-by: Mauro Carvalho Chehab <[email protected]>
Reviewed-by: Andrzej Hajda <[email protected]>
---
drivers/gpu/drm/i915/gem/i915_gem_ttm.c | 11 +++++++++++
1 file changed, 11 insertions(+)

diff --git a/drivers/gpu/drm/i915/gem/i915_gem_ttm.c b/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
index 6956d273fa5f..955635ae5982 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
@@ -1210,6 +1210,17 @@ int __i915_gem_ttm_object_init(struct intel_memory_region *mem,
ret = ttm_bo_init_reserved(&i915->bdev, i915_gem_to_ttm(obj), bo_type,
&i915_sys_placement, page_size >> PAGE_SHIFT,
&ctx, NULL, NULL, i915_ttm_bo_destroy);
+
+ /*
+ * XXX: The ttm_bo_init_reserved() functions returns -ENOSPC if the size
+ * is too big to add vma. The direct function that returns -ENOSPC is
+ * drm_mm_insert_node_in_range(). To handle the same error as other code
+ * that returns -E2BIG when the size is too large, it converts -ENOSPC to
+ * -E2BIG.
+ */
+ if (size >> PAGE_SHIFT > INT_MAX && ret == -ENOSPC)
+ ret = -E2BIG;
+
if (ret)
return i915_ttm_err_to_gem(ret);

--
2.37.1

2022-09-09 11:18:33

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 3/9] compiler_types.h: Add assert_type to catch type mis-match while compiling

It adds assert_type and assert_typable macros to catch type mis-match while
compiling. The existing typecheck() macro outputs build warnings, but the
newly added assert_type() macro uses the _Static_assert() keyword (which is
introduced in C11) to generate a build break when the types are different
and can be used to detect explicit build errors.
Unlike the assert_type() macro, assert_typable() macro allows a constant
value as the second argument.

Suggested-by: Kees Cook <[email protected]>
Signed-off-by: Gwan-gyeong Mun <[email protected]>
Cc: Thomas Hellström <[email protected]>
Cc: Matthew Auld <[email protected]>
Cc: Nirmoy Das <[email protected]>
Cc: Jani Nikula <[email protected]>
Cc: Andi Shyti <[email protected]>
Cc: Mauro Carvalho Chehab <[email protected]>
Cc: Andrzej Hajda <[email protected]>
Cc: Kees Cook <[email protected]>
---
include/linux/compiler_types.h | 39 ++++++++++++++++++++++++++++++++++
1 file changed, 39 insertions(+)

diff --git a/include/linux/compiler_types.h b/include/linux/compiler_types.h
index 4f2a819fd60a..19cc125918bb 100644
--- a/include/linux/compiler_types.h
+++ b/include/linux/compiler_types.h
@@ -294,6 +294,45 @@ struct ftrace_likely_data {
/* Are two types/vars the same type (ignoring qualifiers)? */
#define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))

+/**
+ * assert_type - break compile if the first argument's data type and the second
+ * argument's data type are not the same
+ *
+ * @t1: data type or variable
+ * @t2: data type or variable
+ *
+ * The first and second arguments can be data types or variables or mixed (the
+ * first argument is the data type and the second argument is variable or vice
+ * versa). It determines whether the first argument's data type and the second
+ * argument's data type are the same while compiling, and it breaks compile if
+ * the two types are not the same.
+ * See also assert_typable().
+ */
+#define assert_type(t1, t2) _Static_assert(__same_type(t1, t2))
+
+/**
+ * assert_typable - break compile if the first argument's data type and the
+ * second argument's data type are not the same
+ *
+ * @t: data type or variable
+ * @n: data type or variable or constant value
+ *
+ * The first and second arguments can be data types or variables or mixed (the
+ * first argument is the data type and the second argument is variable or vice
+ * versa). Unlike the assert_type() macro, this macro allows a constant value
+ * as the second argument. And if the second argument is a constant value, it
+ * always passes. And it doesn't mean that the types are explicitly the same.
+ * When a constant value is used as the second argument, if you need an
+ * overflow check when assigning a constant value to a variable of the type of
+ * the first argument, you can use the overflows_type() macro. When a constant
+ * value is not used as a second argument, it determines whether the first
+ * argument's data type and the second argument's data type are the same while
+ * compiling, and it breaks compile if the two types are not the same.
+ * See also assert_type() and overflows_type().
+ */
+#define assert_typable(t, n) _Static_assert(__builtin_constant_p(n) || \
+ __same_type(t, typeof(n)))
+
/*
* __unqual_scalar_typeof(x) - Declare an unqualified scalar type, leaving
* non-scalar types unchanged.
--
2.37.1

2022-09-09 11:19:18

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 5/9] drm/i915: Check for integer truncation on scatterlist creation

From: Chris Wilson <[email protected]>

There is an impedance mismatch between the scatterlist API using unsigned
int and our memory/page accounting in unsigned long. That is we may try
to create a scatterlist for a large object that overflows returning a
small table into which we try to fit very many pages. As the object size
is under control of userspace, we have to be prudent and catch the
conversion errors.

To catch the implicit truncation as we switch from unsigned long into the
scatterlist's unsigned int, we use overflows_type check and report
E2BIG prior to the operation. This is already used in our create ioctls to
indicate if the uABI request is simply too large for the backing store.
Failing that type check, we have a second check at sg_alloc_table time
to make sure the values we are passing into the scatterlist API are not
truncated.

It uses pgoff_t for locals that are dealing with page indices, in this
case, the page count is the limit of the page index.
And it uses safe_conversion() macro which performs a type conversion (cast)
of an integer value into a new variable, checking that the destination is
large enough to hold the source value.

v2: Move added i915_utils's macro into drm_util header (Jani N)
v5: Fix macros to be enclosed in parentheses for complex values
Fix too long line warning
v8: Replace safe_conversion() with check_assign() (Kees)

Signed-off-by: Chris Wilson <[email protected]>
Signed-off-by: Gwan-gyeong Mun <[email protected]>
Cc: Tvrtko Ursulin <[email protected]>
Cc: Brian Welty <[email protected]>
Cc: Matthew Auld <[email protected]>
Cc: Thomas Hellström <[email protected]>
Reviewed-by: Nirmoy Das <[email protected]>
Reviewed-by: Mauro Carvalho Chehab <[email protected]>
Reviewed-by: Andrzej Hajda <[email protected]>
---
drivers/gpu/drm/i915/gem/i915_gem_internal.c | 6 ++++--
drivers/gpu/drm/i915/gem/i915_gem_object.h | 3 ---
drivers/gpu/drm/i915/gem/i915_gem_phys.c | 4 ++++
drivers/gpu/drm/i915/gem/i915_gem_shmem.c | 5 ++++-
drivers/gpu/drm/i915/gem/i915_gem_ttm.c | 4 ++++
drivers/gpu/drm/i915/gem/i915_gem_userptr.c | 5 ++++-
drivers/gpu/drm/i915/gvt/dmabuf.c | 9 +++++----
drivers/gpu/drm/i915/i915_scatterlist.h | 11 +++++++++++
8 files changed, 36 insertions(+), 11 deletions(-)

diff --git a/drivers/gpu/drm/i915/gem/i915_gem_internal.c b/drivers/gpu/drm/i915/gem/i915_gem_internal.c
index c698f95af15f..53fa27e1c950 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_internal.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_internal.c
@@ -37,10 +37,13 @@ static int i915_gem_object_get_pages_internal(struct drm_i915_gem_object *obj)
struct sg_table *st;
struct scatterlist *sg;
unsigned int sg_page_sizes;
- unsigned int npages;
+ pgoff_t npages; /* restricted by sg_alloc_table */
int max_order;
gfp_t gfp;

+ if (check_assign(obj->base.size >> PAGE_SHIFT, &npages))
+ return -E2BIG;
+
max_order = MAX_ORDER;
#ifdef CONFIG_SWIOTLB
if (is_swiotlb_active(obj->base.dev->dev)) {
@@ -67,7 +70,6 @@ static int i915_gem_object_get_pages_internal(struct drm_i915_gem_object *obj)
if (!st)
return -ENOMEM;

- npages = obj->base.size / PAGE_SIZE;
if (sg_alloc_table(st, npages, GFP_KERNEL)) {
kfree(st);
return -ENOMEM;
diff --git a/drivers/gpu/drm/i915/gem/i915_gem_object.h b/drivers/gpu/drm/i915/gem/i915_gem_object.h
index 8dd2b84468c8..a64fe73c05b5 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_object.h
+++ b/drivers/gpu/drm/i915/gem/i915_gem_object.h
@@ -26,9 +26,6 @@ enum intel_region_id;
* this and catch if we ever need to fix it. In the meantime, if you do
* spot such a local variable, please consider fixing!
*
- * Aside from our own locals (for which we have no excuse!):
- * - sg_table embeds unsigned int for nents
- *
* We can check for invalidly typed locals with typecheck(), see for example
* i915_gem_object_get_sg().
*/
diff --git a/drivers/gpu/drm/i915/gem/i915_gem_phys.c b/drivers/gpu/drm/i915/gem/i915_gem_phys.c
index 0d0e46dae559..88ba7266a3a5 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_phys.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_phys.c
@@ -28,6 +28,10 @@ static int i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
void *dst;
int i;

+ /* Contiguous chunk, with a single scatterlist element */
+ if (overflows_type(obj->base.size, sg->length))
+ return -E2BIG;
+
if (GEM_WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
return -EINVAL;

diff --git a/drivers/gpu/drm/i915/gem/i915_gem_shmem.c b/drivers/gpu/drm/i915/gem/i915_gem_shmem.c
index f42ca1179f37..339b0a9cf2d0 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_shmem.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_shmem.c
@@ -193,13 +193,16 @@ static int shmem_get_pages(struct drm_i915_gem_object *obj)
struct drm_i915_private *i915 = to_i915(obj->base.dev);
struct intel_memory_region *mem = obj->mm.region;
struct address_space *mapping = obj->base.filp->f_mapping;
- const unsigned long page_count = obj->base.size / PAGE_SIZE;
unsigned int max_segment = i915_sg_segment_size();
struct sg_table *st;
struct sgt_iter sgt_iter;
+ pgoff_t page_count;
struct page *page;
int ret;

+ if (check_assign(obj->base.size >> PAGE_SHIFT, &page_count))
+ return -E2BIG;
+
/*
* Assert that the object is not currently in any GPU domain. As it
* wasn't in the GTT, there shouldn't be any way it could have been in
diff --git a/drivers/gpu/drm/i915/gem/i915_gem_ttm.c b/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
index b6c813d69ffa..06a2e80a5702 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_ttm.c
@@ -783,6 +783,10 @@ static int i915_ttm_get_pages(struct drm_i915_gem_object *obj)
{
struct ttm_place requested, busy[I915_TTM_MAX_PLACEMENTS];
struct ttm_placement placement;
+ pgoff_t num_pages;
+
+ if (check_assign(obj->base.size >> PAGE_SHIFT, &num_pages))
+ return -E2BIG;

GEM_BUG_ON(obj->mm.n_placements > I915_TTM_MAX_PLACEMENTS);

diff --git a/drivers/gpu/drm/i915/gem/i915_gem_userptr.c b/drivers/gpu/drm/i915/gem/i915_gem_userptr.c
index 8423df021b71..48237e443863 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_userptr.c
+++ b/drivers/gpu/drm/i915/gem/i915_gem_userptr.c
@@ -128,13 +128,16 @@ static void i915_gem_object_userptr_drop_ref(struct drm_i915_gem_object *obj)

static int i915_gem_userptr_get_pages(struct drm_i915_gem_object *obj)
{
- const unsigned long num_pages = obj->base.size >> PAGE_SHIFT;
unsigned int max_segment = i915_sg_segment_size();
struct sg_table *st;
unsigned int sg_page_sizes;
struct page **pvec;
+ pgoff_t num_pages; /* limited by sg_alloc_table_from_pages_segment */
int ret;

+ if (check_assign(obj->base.size >> PAGE_SHIFT, &num_pages))
+ return -E2BIG;
+
st = kmalloc(sizeof(*st), GFP_KERNEL);
if (!st)
return -ENOMEM;
diff --git a/drivers/gpu/drm/i915/gvt/dmabuf.c b/drivers/gpu/drm/i915/gvt/dmabuf.c
index 01e54b45c5c1..bc6e823584ad 100644
--- a/drivers/gpu/drm/i915/gvt/dmabuf.c
+++ b/drivers/gpu/drm/i915/gvt/dmabuf.c
@@ -42,8 +42,7 @@

#define GEN8_DECODE_PTE(pte) (pte & GENMASK_ULL(63, 12))

-static int vgpu_gem_get_pages(
- struct drm_i915_gem_object *obj)
+static int vgpu_gem_get_pages(struct drm_i915_gem_object *obj)
{
struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
struct intel_vgpu *vgpu;
@@ -52,7 +51,10 @@ static int vgpu_gem_get_pages(
int i, j, ret;
gen8_pte_t __iomem *gtt_entries;
struct intel_vgpu_fb_info *fb_info;
- u32 page_num;
+ pgoff_t page_num;
+
+ if (check_assign(obj->base.size >> PAGE_SHIFT, &page_num))
+ return -E2BIG;

fb_info = (struct intel_vgpu_fb_info *)obj->gvt_info;
if (drm_WARN_ON(&dev_priv->drm, !fb_info))
@@ -66,7 +68,6 @@ static int vgpu_gem_get_pages(
if (unlikely(!st))
return -ENOMEM;

- page_num = obj->base.size >> PAGE_SHIFT;
ret = sg_alloc_table(st, page_num, GFP_KERNEL);
if (ret) {
kfree(st);
diff --git a/drivers/gpu/drm/i915/i915_scatterlist.h b/drivers/gpu/drm/i915/i915_scatterlist.h
index 9ddb3e743a3e..1d1802beb42b 100644
--- a/drivers/gpu/drm/i915/i915_scatterlist.h
+++ b/drivers/gpu/drm/i915/i915_scatterlist.h
@@ -220,4 +220,15 @@ struct i915_refct_sgt *i915_rsgt_from_buddy_resource(struct ttm_resource *res,
u64 region_start,
u32 page_alignment);

+/* Wrap scatterlist.h to sanity check for integer truncation */
+typedef unsigned int __sg_size_t; /* see linux/scatterlist.h */
+#define sg_alloc_table(sgt, nents, gfp) \
+ overflows_type(nents, __sg_size_t) ? -E2BIG \
+ : ((sg_alloc_table)(sgt, (__sg_size_t)(nents), gfp))
+
+#define sg_alloc_table_from_pages_segment(sgt, pages, npages, offset, size, max_segment, gfp) \
+ overflows_type(npages, __sg_size_t) ? -E2BIG \
+ : ((sg_alloc_table_from_pages_segment)(sgt, pages, (__sg_size_t)(npages), offset, \
+ size, max_segment, gfp))
+
#endif
--
2.37.1

2022-09-09 11:20:37

by Gwan-gyeong Mun

[permalink] [raw]
Subject: [PATCH v10 9/9] drm/i915: Remove truncation warning for large objects

From: Chris Wilson <[email protected]>

Having addressed the issues surrounding incorrect types for local
variables and potential integer truncation in using the scatterlist API,
we have closed all the loop holes we had previously identified with
dangerously large object creation. As such, we can eliminate the warning
put in place to remind us to complete the review.

Signed-off-by: Chris Wilson <[email protected]>
Signed-off-by: Gwan-gyeong Mun <[email protected]>
Cc: Tvrtko Ursulin <[email protected]>
Cc: Brian Welty <[email protected]>
Cc: Matthew Auld <[email protected]>
Cc: Thomas Hellström <[email protected]>
Testcase: igt@gem_create@create-massive
Closes: https://gitlab.freedesktop.org/drm/intel/-/issues/4991
Reviewed-by: Nirmoy Das <[email protected]>
Reviewed-by: Mauro Carvalho Chehab <[email protected]>
Reviewed-by: Andrzej Hajda <[email protected]>
---
drivers/gpu/drm/i915/gem/i915_gem_object.h | 15 ---------------
1 file changed, 15 deletions(-)

diff --git a/drivers/gpu/drm/i915/gem/i915_gem_object.h b/drivers/gpu/drm/i915/gem/i915_gem_object.h
index a64fe73c05b5..ad88ab88b828 100644
--- a/drivers/gpu/drm/i915/gem/i915_gem_object.h
+++ b/drivers/gpu/drm/i915/gem/i915_gem_object.h
@@ -20,25 +20,10 @@

enum intel_region_id;

-/*
- * XXX: There is a prevalence of the assumption that we fit the
- * object's page count inside a 32bit _signed_ variable. Let's document
- * this and catch if we ever need to fix it. In the meantime, if you do
- * spot such a local variable, please consider fixing!
- *
- * We can check for invalidly typed locals with typecheck(), see for example
- * i915_gem_object_get_sg().
- */
-#define GEM_CHECK_SIZE_OVERFLOW(sz) \
- GEM_WARN_ON((sz) >> PAGE_SHIFT > INT_MAX)
-
static inline bool i915_gem_object_size_2big(u64 size)
{
struct drm_i915_gem_object *obj;

- if (GEM_CHECK_SIZE_OVERFLOW(size))
- return true;
-
if (overflows_type(size, obj->base.size))
return true;

--
2.37.1

2022-09-11 10:47:12

by Andi Shyti

[permalink] [raw]
Subject: Re: [PATCH v10 1/9] overflow: Allow mixed type arguments

Hi Kees,

On Fri, Sep 09, 2022 at 07:59:05PM +0900, Gwan-gyeong Mun wrote:
> From: Kees Cook <[email protected]>
>
> When the check_[op]_overflow() helpers were introduced, all arguments were
> required to be the same type to make the fallback macros simpler. However,
> now that the fallback macros have been removed[1], it is fine to allow
> mixed types, which makes using the helpers much more useful, as they
> can be used to test for type-based overflows (e.g. adding two large ints
> but storing into a u8), as would be handy in the drm core[2].
>
> Remove the restriction, and add additional self-tests that exercise some
> of the mixed-type overflow cases, and double-check for accidental macro
> side-effects.

I would split in two different patches the check_[op]_overflow()
helpers with the tests.

Overall they look good though.

> [1] https://git.kernel.org/linus/4eb6bd55cfb22ffc20652732340c4962f3ac9a91
> [2] https://lore.kernel.org/lkml/[email protected]
>
> Cc: Rasmus Villemoes <[email protected]>
> Cc: Gwan-gyeong Mun <[email protected]>
> Cc: Andrzej Hajda <[email protected]>
> Cc: "Gustavo A. R. Silva" <[email protected]>
> Cc: Nick Desaulniers <[email protected]>
> Cc: [email protected]
> Signed-off-by: Kees Cook <[email protected]>

Gwan-gyeong, can you please add your SoB here? And you don't need
to 'Cc:' yourself.

Andi

2022-09-11 11:13:16

by Andi Shyti

[permalink] [raw]
Subject: Re: [PATCH v10 3/9] compiler_types.h: Add assert_type to catch type mis-match while compiling

Hi Gwan-gyeong,

On Fri, Sep 09, 2022 at 07:59:07PM +0900, Gwan-gyeong Mun wrote:
> It adds assert_type and assert_typable macros to catch type mis-match while

/Add/It adds/, please use the imperative form.

> compiling. The existing typecheck() macro outputs build warnings, but the
> newly added assert_type() macro uses the _Static_assert() keyword (which is
> introduced in C11) to generate a build break when the types are different
> and can be used to detect explicit build errors.
> Unlike the assert_type() macro, assert_typable() macro allows a constant
> value as the second argument.
>
> Suggested-by: Kees Cook <[email protected]>
> Signed-off-by: Gwan-gyeong Mun <[email protected]>
> Cc: Thomas Hellstr?m <[email protected]>
> Cc: Matthew Auld <[email protected]>
> Cc: Nirmoy Das <[email protected]>
> Cc: Jani Nikula <[email protected]>
> Cc: Andi Shyti <[email protected]>
> Cc: Mauro Carvalho Chehab <[email protected]>
> Cc: Andrzej Hajda <[email protected]>
> Cc: Kees Cook <[email protected]>
> ---
> include/linux/compiler_types.h | 39 ++++++++++++++++++++++++++++++++++
> 1 file changed, 39 insertions(+)
>
> diff --git a/include/linux/compiler_types.h b/include/linux/compiler_types.h
> index 4f2a819fd60a..19cc125918bb 100644
> --- a/include/linux/compiler_types.h
> +++ b/include/linux/compiler_types.h
> @@ -294,6 +294,45 @@ struct ftrace_likely_data {
> /* Are two types/vars the same type (ignoring qualifiers)? */
> #define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
>
> +/**
> + * assert_type - break compile if the first argument's data type and the second
> + * argument's data type are not the same

I would use /aborts compilation/break compile/

> + *

nowhere is written that this extra blank line is not needed, but
just checking the style in compiler_types.h it is not used.

I personally like the blank line, but standing to the general
taste, it should be removed also for keeping a coherent style.

> + * @t1: data type or variable
> + * @t2: data type or variable
> + *
> + * The first and second arguments can be data types or variables or mixed (the
> + * first argument is the data type and the second argument is variable or vice
> + * versa). It determines whether the first argument's data type and the second
> + * argument's data type are the same while compiling, and it breaks compile if
> + * the two types are not the same.
> + * See also assert_typable().
> + */
> +#define assert_type(t1, t2) _Static_assert(__same_type(t1, t2))

In C11 _Static_assert is defined as:

_Static_assert ( constant-expression , string-literal ) ;

While

_Static_assert ( constant-expression ) ;

is defined in C17 along with the previous. I think you should add
the error message as a 'string-literal'.

Andi

> +/**
> + * assert_typable - break compile if the first argument's data type and the
> + * second argument's data type are not the same
> + *
> + * @t: data type or variable
> + * @n: data type or variable or constant value
> + *
> + * The first and second arguments can be data types or variables or mixed (the
> + * first argument is the data type and the second argument is variable or vice
> + * versa). Unlike the assert_type() macro, this macro allows a constant value
> + * as the second argument. And if the second argument is a constant value, it
> + * always passes. And it doesn't mean that the types are explicitly the same.
> + * When a constant value is used as the second argument, if you need an
> + * overflow check when assigning a constant value to a variable of the type of
> + * the first argument, you can use the overflows_type() macro. When a constant
> + * value is not used as a second argument, it determines whether the first
> + * argument's data type and the second argument's data type are the same while
> + * compiling, and it breaks compile if the two types are not the same.
> + * See also assert_type() and overflows_type().
> + */
> +#define assert_typable(t, n) _Static_assert(__builtin_constant_p(n) || \
> + __same_type(t, typeof(n)))
> +
> /*
> * __unqual_scalar_typeof(x) - Declare an unqualified scalar type, leaving
> * non-scalar types unchanged.
> --
> 2.37.1

2022-09-12 08:49:46

by Andrzej Hajda

[permalink] [raw]
Subject: Re: [PATCH v10 1/9] overflow: Allow mixed type arguments



On 09.09.2022 12:59, Gwan-gyeong Mun wrote:
> From: Kees Cook <[email protected]>
>
> When the check_[op]_overflow() helpers were introduced, all arguments were
> required to be the same type to make the fallback macros simpler. However,
> now that the fallback macros have been removed[1], it is fine to allow
> mixed types, which makes using the helpers much more useful, as they
> can be used to test for type-based overflows (e.g. adding two large ints
> but storing into a u8), as would be handy in the drm core[2].
>
> Remove the restriction, and add additional self-tests that exercise some
> of the mixed-type overflow cases, and double-check for accidental macro
> side-effects.
>
> [1] https://git.kernel.org/linus/4eb6bd55cfb22ffc20652732340c4962f3ac9a91
> [2] https://lore.kernel.org/lkml/[email protected]
>
> Cc: Rasmus Villemoes <[email protected]>
> Cc: Gwan-gyeong Mun <[email protected]>
> Cc: Andrzej Hajda <[email protected]>
> Cc: "Gustavo A. R. Silva" <[email protected]>
> Cc: Nick Desaulniers <[email protected]>
> Cc: [email protected]
> Signed-off-by: Kees Cook <[email protected]>

Reviewed-by: Andrzej Hajda <[email protected]>

Regards
Andrzej

> ---
> include/linux/overflow.h | 72 ++++++++++++++++------------
> lib/overflow_kunit.c | 101 ++++++++++++++++++++++++++++-----------
> 2 files changed, 113 insertions(+), 60 deletions(-)
>
> diff --git a/include/linux/overflow.h b/include/linux/overflow.h
> index 0eb3b192f07a..19dfdd74835e 100644
> --- a/include/linux/overflow.h
> +++ b/include/linux/overflow.h
> @@ -51,40 +51,50 @@ static inline bool __must_check __must_check_overflow(bool overflow)
> return unlikely(overflow);
> }
>
> -/*
> - * For simplicity and code hygiene, the fallback code below insists on
> - * a, b and *d having the same type (similar to the min() and max()
> - * macros), whereas gcc's type-generic overflow checkers accept
> - * different types. Hence we don't just make check_add_overflow an
> - * alias for __builtin_add_overflow, but add type checks similar to
> - * below.
> +/** check_add_overflow() - Calculate addition with overflow checking
> + *
> + * @a: first addend
> + * @b: second addend
> + * @d: pointer to store sum
> + *
> + * Returns 0 on success.
> + *
> + * *@d holds the results of the attempted addition, but is not considered
> + * "safe for use" on a non-zero return value, which indicates that the
> + * sum has overflowed or been truncated.
> */
> -#define check_add_overflow(a, b, d) __must_check_overflow(({ \
> - typeof(a) __a = (a); \
> - typeof(b) __b = (b); \
> - typeof(d) __d = (d); \
> - (void) (&__a == &__b); \
> - (void) (&__a == __d); \
> - __builtin_add_overflow(__a, __b, __d); \
> -}))
> +#define check_add_overflow(a, b, d) \
> + __must_check_overflow(__builtin_add_overflow(a, b, d))
>
> -#define check_sub_overflow(a, b, d) __must_check_overflow(({ \
> - typeof(a) __a = (a); \
> - typeof(b) __b = (b); \
> - typeof(d) __d = (d); \
> - (void) (&__a == &__b); \
> - (void) (&__a == __d); \
> - __builtin_sub_overflow(__a, __b, __d); \
> -}))
> +/** check_sub_overflow() - Calculate subtraction with overflow checking
> + *
> + * @a: minuend; value to subtract from
> + * @b: subtrahend; value to subtract from @a
> + * @d: pointer to store difference
> + *
> + * Returns 0 on success.
> + *
> + * *@d holds the results of the attempted subtraction, but is not considered
> + * "safe for use" on a non-zero return value, which indicates that the
> + * difference has underflowed or been truncated.
> + */
> +#define check_sub_overflow(a, b, d) \
> + __must_check_overflow(__builtin_sub_overflow(a, b, d))
>
> -#define check_mul_overflow(a, b, d) __must_check_overflow(({ \
> - typeof(a) __a = (a); \
> - typeof(b) __b = (b); \
> - typeof(d) __d = (d); \
> - (void) (&__a == &__b); \
> - (void) (&__a == __d); \
> - __builtin_mul_overflow(__a, __b, __d); \
> -}))
> +/** check_mul_overflow() - Calculate multiplication with overflow checking
> + *
> + * @a: first factor
> + * @b: second factor
> + * @d: pointer to store product
> + *
> + * Returns 0 on success.
> + *
> + * *@d holds the results of the attempted multiplication, but is not
> + * considered "safe for use" on a non-zero return value, which indicates
> + * that the product has overflowed or been truncated.
> + */
> +#define check_mul_overflow(a, b, d) \
> + __must_check_overflow(__builtin_mul_overflow(a, b, d))
>
> /** check_shl_overflow() - Calculate a left-shifted value and check overflow
> *
> diff --git a/lib/overflow_kunit.c b/lib/overflow_kunit.c
> index 7e3e43679b73..0d98c9bc75da 100644
> --- a/lib/overflow_kunit.c
> +++ b/lib/overflow_kunit.c
> @@ -16,12 +16,15 @@
> #include <linux/types.h>
> #include <linux/vmalloc.h>
>
> -#define DEFINE_TEST_ARRAY(t) \
> - static const struct test_ ## t { \
> - t a, b; \
> - t sum, diff, prod; \
> - bool s_of, d_of, p_of; \
> - } t ## _tests[]
> +#define DEFINE_TEST_ARRAY_TYPED(t1, t2, t) \
> + static const struct test_ ## t1 ## _ ## t2 ## __ ## t { \
> + t1 a; \
> + t2 b; \
> + t sum, diff, prod; \
> + bool s_of, d_of, p_of; \
> + } t1 ## _ ## t2 ## __ ## t ## _tests[]
> +
> +#define DEFINE_TEST_ARRAY(t) DEFINE_TEST_ARRAY_TYPED(t, t, t)
>
> DEFINE_TEST_ARRAY(u8) = {
> {0, 0, 0, 0, 0, false, false, false},
> @@ -222,21 +225,27 @@ DEFINE_TEST_ARRAY(s64) = {
> };
> #endif
>
> -#define check_one_op(t, fmt, op, sym, a, b, r, of) do { \
> - t _r; \
> - bool _of; \
> - \
> - _of = check_ ## op ## _overflow(a, b, &_r); \
> - KUNIT_EXPECT_EQ_MSG(test, _of, of, \
> +#define check_one_op(t, fmt, op, sym, a, b, r, of) do { \
> + int _a_orig = a, _a_bump = a + 1; \
> + int _b_orig = b, _b_bump = b + 1; \
> + bool _of; \
> + t _r; \
> + \
> + _of = check_ ## op ## _overflow(a, b, &_r); \
> + KUNIT_EXPECT_EQ_MSG(test, _of, of, \
> "expected "fmt" "sym" "fmt" to%s overflow (type %s)\n", \
> - a, b, of ? "" : " not", #t); \
> - KUNIT_EXPECT_EQ_MSG(test, _r, r, \
> + a, b, of ? "" : " not", #t); \
> + KUNIT_EXPECT_EQ_MSG(test, _r, r, \
> "expected "fmt" "sym" "fmt" == "fmt", got "fmt" (type %s)\n", \
> - a, b, r, _r, #t); \
> + a, b, r, _r, #t); \
> + /* Check for internal macro side-effects. */ \
> + _of = check_ ## op ## _overflow(_a_orig++, _b_orig++, &_r); \
> + KUNIT_EXPECT_EQ_MSG(test, _a_orig, _a_bump, "Unexpected " #op " macro side-effect!\n"); \
> + KUNIT_EXPECT_EQ_MSG(test, _b_orig, _b_bump, "Unexpected " #op " macro side-effect!\n"); \
> } while (0)
>
> -#define DEFINE_TEST_FUNC(t, fmt) \
> -static void do_test_ ## t(struct kunit *test, const struct test_ ## t *p) \
> +#define DEFINE_TEST_FUNC_TYPED(n, t, fmt) \
> +static void do_test_ ## n(struct kunit *test, const struct test_ ## n *p) \
> { \
> check_one_op(t, fmt, add, "+", p->a, p->b, p->sum, p->s_of); \
> check_one_op(t, fmt, add, "+", p->b, p->a, p->sum, p->s_of); \
> @@ -245,15 +254,18 @@ static void do_test_ ## t(struct kunit *test, const struct test_ ## t *p) \
> check_one_op(t, fmt, mul, "*", p->b, p->a, p->prod, p->p_of); \
> } \
> \
> -static void t ## _overflow_test(struct kunit *test) { \
> +static void n ## _overflow_test(struct kunit *test) { \
> unsigned i; \
> \
> - for (i = 0; i < ARRAY_SIZE(t ## _tests); ++i) \
> - do_test_ ## t(test, &t ## _tests[i]); \
> + for (i = 0; i < ARRAY_SIZE(n ## _tests); ++i) \
> + do_test_ ## n(test, &n ## _tests[i]); \
> kunit_info(test, "%zu %s arithmetic tests finished\n", \
> - ARRAY_SIZE(t ## _tests), #t); \
> + ARRAY_SIZE(n ## _tests), #n); \
> }
>
> +#define DEFINE_TEST_FUNC(t, fmt) \
> + DEFINE_TEST_FUNC_TYPED(t ## _ ## t ## __ ## t, t, fmt)
> +
> DEFINE_TEST_FUNC(u8, "%d");
> DEFINE_TEST_FUNC(s8, "%d");
> DEFINE_TEST_FUNC(u16, "%d");
> @@ -265,6 +277,33 @@ DEFINE_TEST_FUNC(u64, "%llu");
> DEFINE_TEST_FUNC(s64, "%lld");
> #endif
>
> +DEFINE_TEST_ARRAY_TYPED(u32, u32, u8) = {
> + {0, 0, 0, 0, 0, false, false, false},
> + {U8_MAX, 2, 1, U8_MAX - 2, U8_MAX - 1, true, false, true},
> + {U8_MAX + 1, 0, 0, 0, 0, true, true, false},
> +};
> +DEFINE_TEST_FUNC_TYPED(u32_u32__u8, u8, "%d");
> +
> +DEFINE_TEST_ARRAY_TYPED(u32, u32, int) = {
> + {0, 0, 0, 0, 0, false, false, false},
> + {U32_MAX, 0, -1, -1, 0, true, true, false},
> +};
> +DEFINE_TEST_FUNC_TYPED(u32_u32__int, int, "%d");
> +
> +DEFINE_TEST_ARRAY_TYPED(u8, u8, int) = {
> + {0, 0, 0, 0, 0, false, false, false},
> + {U8_MAX, U8_MAX, 2 * U8_MAX, 0, U8_MAX * U8_MAX, false, false, false},
> + {1, 2, 3, -1, 2, false, false, false},
> +};
> +DEFINE_TEST_FUNC_TYPED(u8_u8__int, int, "%d");
> +
> +DEFINE_TEST_ARRAY_TYPED(int, int, u8) = {
> + {0, 0, 0, 0, 0, false, false, false},
> + {1, 2, 3, U8_MAX, 2, false, true, false},
> + {-1, 0, U8_MAX, U8_MAX, 0, true, true, false},
> +};
> +DEFINE_TEST_FUNC_TYPED(int_int__u8, u8, "%d");
> +
> static void overflow_shift_test(struct kunit *test)
> {
> int count = 0;
> @@ -649,17 +688,21 @@ static void overflow_size_helpers_test(struct kunit *test)
> }
>
> static struct kunit_case overflow_test_cases[] = {
> - KUNIT_CASE(u8_overflow_test),
> - KUNIT_CASE(s8_overflow_test),
> - KUNIT_CASE(u16_overflow_test),
> - KUNIT_CASE(s16_overflow_test),
> - KUNIT_CASE(u32_overflow_test),
> - KUNIT_CASE(s32_overflow_test),
> + KUNIT_CASE(u8_u8__u8_overflow_test),
> + KUNIT_CASE(s8_s8__s8_overflow_test),
> + KUNIT_CASE(u16_u16__u16_overflow_test),
> + KUNIT_CASE(s16_s16__s16_overflow_test),
> + KUNIT_CASE(u32_u32__u32_overflow_test),
> + KUNIT_CASE(s32_s32__s32_overflow_test),
> /* Clang 13 and earlier generate unwanted libcalls on 32-bit. */
> #if BITS_PER_LONG == 64
> - KUNIT_CASE(u64_overflow_test),
> - KUNIT_CASE(s64_overflow_test),
> + KUNIT_CASE(u64_u64__u64_overflow_test),
> + KUNIT_CASE(s64_s64__s64_overflow_test),
> #endif
> + KUNIT_CASE(u32_u32__u8_overflow_test),
> + KUNIT_CASE(u32_u32__int_overflow_test),
> + KUNIT_CASE(u8_u8__int_overflow_test),
> + KUNIT_CASE(int_int__u8_overflow_test),
> KUNIT_CASE(overflow_shift_test),
> KUNIT_CASE(overflow_allocation_test),
> KUNIT_CASE(overflow_size_helpers_test),

2022-09-12 10:26:31

by Rasmus Villemoes

[permalink] [raw]
Subject: Re: [PATCH v10 3/9] compiler_types.h: Add assert_type to catch type mis-match while compiling

On 11/09/2022 13.04, Andi Shyti wrote:
> Hi Gwan-gyeong,
>
> On Fri, Sep 09, 2022 at 07:59:07PM +0900, Gwan-gyeong Mun wrote:
>> It adds assert_type and assert_typable macros to catch type mis-match while
>
> /Add/It adds/, please use the imperative form.
>
>> compiling. The existing typecheck() macro outputs build warnings, but the
>> newly added assert_type() macro uses the _Static_assert() keyword (which is
>> introduced in C11) to generate a build break when the types are different
>> and can be used to detect explicit build errors.
>> Unlike the assert_type() macro, assert_typable() macro allows a constant
>> value as the second argument.
>>
>> Suggested-by: Kees Cook <[email protected]>
>> Signed-off-by: Gwan-gyeong Mun <[email protected]>
>> Cc: Thomas Hellström <[email protected]>
>> Cc: Matthew Auld <[email protected]>
>> Cc: Nirmoy Das <[email protected]>
>> Cc: Jani Nikula <[email protected]>
>> Cc: Andi Shyti <[email protected]>
>> Cc: Mauro Carvalho Chehab <[email protected]>
>> Cc: Andrzej Hajda <[email protected]>
>> Cc: Kees Cook <[email protected]>
>> ---
>> include/linux/compiler_types.h | 39 ++++++++++++++++++++++++++++++++++
>> 1 file changed, 39 insertions(+)
>>
>> diff --git a/include/linux/compiler_types.h b/include/linux/compiler_types.h
>> index 4f2a819fd60a..19cc125918bb 100644
>> --- a/include/linux/compiler_types.h
>> +++ b/include/linux/compiler_types.h
>> @@ -294,6 +294,45 @@ struct ftrace_likely_data {
>> /* Are two types/vars the same type (ignoring qualifiers)? */
>> #define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
>>
>> +/**
>> + * assert_type - break compile if the first argument's data type and the second
>> + * argument's data type are not the same
>
> I would use /aborts compilation/break compile/
>
>> + *
>
> nowhere is written that this extra blank line is not needed, but
> just checking the style in compiler_types.h it is not used.
>
> I personally like the blank line, but standing to the general
> taste, it should be removed also for keeping a coherent style.
>
>> + * @t1: data type or variable
>> + * @t2: data type or variable
>> + *
>> + * The first and second arguments can be data types or variables or mixed (the
>> + * first argument is the data type and the second argument is variable or vice
>> + * versa). It determines whether the first argument's data type and the second
>> + * argument's data type are the same while compiling, and it breaks compile if
>> + * the two types are not the same.
>> + * See also assert_typable().
>> + */
>> +#define assert_type(t1, t2) _Static_assert(__same_type(t1, t2))
>
> In C11 _Static_assert is defined as:
>
> _Static_assert ( constant-expression , string-literal ) ;
>
> While
>
> _Static_assert ( constant-expression ) ;
>
> is defined in C17 along with the previous. I think you should add
> the error message as a 'string-literal'.

See how static_assert() is defined in linux/build_bug.h, and let's avoid
using _Static_assert directly. So this should IMO just be

#define assert_same_type(t1, t2) static_assert(__same_type(t1, t2))

(including the naming of the macro; I don't think "assert_type" is a
good name). No need to add an explicit string literal, the name of the
macro and the constant expression itself are plenty to explain what is
being asserted (with the latter being the reason the string was made
optional).

Rasmus

2022-09-12 10:29:29

by Andi Shyti

[permalink] [raw]
Subject: Re: [PATCH v10 3/9] compiler_types.h: Add assert_type to catch type mis-match while compiling

Hi Rasmus,

Thanks for dropping in,

[...]

> >> + * @t1: data type or variable
> >> + * @t2: data type or variable
> >> + *
> >> + * The first and second arguments can be data types or variables or mixed (the
> >> + * first argument is the data type and the second argument is variable or vice
> >> + * versa). It determines whether the first argument's data type and the second
> >> + * argument's data type are the same while compiling, and it breaks compile if
> >> + * the two types are not the same.
> >> + * See also assert_typable().
> >> + */
> >> +#define assert_type(t1, t2) _Static_assert(__same_type(t1, t2))
> >
> > In C11 _Static_assert is defined as:
> >
> > _Static_assert ( constant-expression , string-literal ) ;
> >
> > While
> >
> > _Static_assert ( constant-expression ) ;
> >
> > is defined in C17 along with the previous. I think you should add
> > the error message as a 'string-literal'.
>
> See how static_assert() is defined in linux/build_bug.h, and let's avoid
> using _Static_assert directly. So this should IMO just be

yes, our definition of static_assert() is against the C11
specification, which should define it as:

#define static_assert _Static_assert

this doesn't make me a big fan of it. But, because it's widely
used, I think it should be used here as well, as you are
suggesting.

> #define assert_same_type(t1, t2) static_assert(__same_type(t1, t2))
>
> (including the naming of the macro; I don't think "assert_type" is a
> good name). No need to add an explicit string literal, the name of the
> macro and the constant expression itself are plenty to explain what is
> being asserted (with the latter being the reason the string was made
> optional).

The string literal would be "__same_type(t1, t2)", right? I would
still use something more explicit... up to Gwan-gyeong.

Thanks,
Andi

2022-09-13 12:17:48

by Kees Cook

[permalink] [raw]
Subject: Re: [PATCH v10 3/9] compiler_types.h: Add assert_type to catch type mis-match while compiling

On Fri, Sep 09, 2022 at 07:59:07PM +0900, Gwan-gyeong Mun wrote:
> It adds assert_type and assert_typable macros to catch type mis-match while
> compiling. The existing typecheck() macro outputs build warnings, but the
> newly added assert_type() macro uses the _Static_assert() keyword (which is
> introduced in C11) to generate a build break when the types are different
> and can be used to detect explicit build errors.
> Unlike the assert_type() macro, assert_typable() macro allows a constant
> value as the second argument.
>
> Suggested-by: Kees Cook <[email protected]>
> Signed-off-by: Gwan-gyeong Mun <[email protected]>
> Cc: Thomas Hellstr?m <[email protected]>
> Cc: Matthew Auld <[email protected]>
> Cc: Nirmoy Das <[email protected]>
> Cc: Jani Nikula <[email protected]>
> Cc: Andi Shyti <[email protected]>
> Cc: Mauro Carvalho Chehab <[email protected]>
> Cc: Andrzej Hajda <[email protected]>
> Cc: Kees Cook <[email protected]>
> ---
> include/linux/compiler_types.h | 39 ++++++++++++++++++++++++++++++++++
> 1 file changed, 39 insertions(+)
>
> diff --git a/include/linux/compiler_types.h b/include/linux/compiler_types.h
> index 4f2a819fd60a..19cc125918bb 100644
> --- a/include/linux/compiler_types.h
> +++ b/include/linux/compiler_types.h
> @@ -294,6 +294,45 @@ struct ftrace_likely_data {
> /* Are two types/vars the same type (ignoring qualifiers)? */
> #define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
>
> +/**
> + * assert_type - break compile if the first argument's data type and the second
> + * argument's data type are not the same
> + *
> + * @t1: data type or variable
> + * @t2: data type or variable
> + *
> + * The first and second arguments can be data types or variables or mixed (the
> + * first argument is the data type and the second argument is variable or vice
> + * versa). It determines whether the first argument's data type and the second
> + * argument's data type are the same while compiling, and it breaks compile if
> + * the two types are not the same.
> + * See also assert_typable().
> + */
> +#define assert_type(t1, t2) _Static_assert(__same_type(t1, t2))
> +
> +/**
> + * assert_typable - break compile if the first argument's data type and the
> + * second argument's data type are not the same
> + *
> + * @t: data type or variable
> + * @n: data type or variable or constant value
> + *
> + * The first and second arguments can be data types or variables or mixed (the
> + * first argument is the data type and the second argument is variable or vice
> + * versa). Unlike the assert_type() macro, this macro allows a constant value
> + * as the second argument. And if the second argument is a constant value, it
> + * always passes. And it doesn't mean that the types are explicitly the same.
> + * When a constant value is used as the second argument, if you need an
> + * overflow check when assigning a constant value to a variable of the type of
> + * the first argument, you can use the overflows_type() macro. When a constant

I wonder if the overflows_type() check should happen in this test? It
seems weird that assert_typable(u8, 1024) would pass...

> + * value is not used as a second argument, it determines whether the first
> + * argument's data type and the second argument's data type are the same while
> + * compiling, and it breaks compile if the two types are not the same.
> + * See also assert_type() and overflows_type().
> + */
> +#define assert_typable(t, n) _Static_assert(__builtin_constant_p(n) || \
> + __same_type(t, typeof(n)))

Totally untested -- I'm not sure if this gets the right semantics for
constant expressoins, etc...

static_assert(__builtin_choose_expression(__builtin_constant_p(n), \
overflows_type(n, typeof(t)), \
__same_type(t, typeof(n))))


Also, can you please add KUnit tests for these new helpers into
lib/overflow_kunit.c?

--
Kees Cook

2022-09-13 12:18:43

by Kees Cook

[permalink] [raw]
Subject: Re: [PATCH v10 2/9] overflow: Move and add few utility macros into overflow

On Fri, Sep 09, 2022 at 07:59:06PM +0900, Gwan-gyeong Mun wrote:
> It moves overflows_type utility macro into overflow header from i915_utils
> header. The overflows_type can be used to catch the truncaion (overflow)
> between different data types. And it adds check_assign() macro which
> performs an assigning source value into destination pointer along with an
> overflow check. overflow_type macro has been improved to handle the
> different data types between source and destination by check_add_overflow
> macro. It also adds check_assign_user_ptr macro which performs an assigning
> source value into destination pointer type variable along with an overflow
> check. If an explicit overflow check is required while assigning,
> check_assign_user_ptr() can be used to assign integers into pointers along
> with an overflow check.
>
> v3: Add is_type_unsigned() macro (Mauro)
> Modify overflows_type() macro to consider signed data types (Mauro)
> Fix the problem that safe_conversion() macro always returns true
> v4: Fix kernel-doc markups
> v6: Move macro addition location so that it can be used by other than drm
> subsystem (Jani, Mauro, Andi)
> Change is_type_unsigned to is_unsigned_type to have the same name form
> as is_signed_type macro
> v8: Add check_assign() and remove safe_conversion() (Kees)
> Fix overflows_type() to use gcc's built-in overflow function (Andrzej)
> Add overflows_ptr() to allow overflow checking when assigning a value
> into a pointer variable (G.G.)
> v9: Fix overflows_type() to use __builtin_add_overflow() instead of
> __builtin_add_overflow_p() (Andrzej)
> Fix overflows_ptr() to use overflows_type() with the unsigned long type
> (Andrzej)
> v10: Remove a redundant type checking for a pointer. (Andrzej)
> Use updated check_add_overflow macro instead of __builtin_add_overflow
> (G.G)
> Add check_assign_user_ptr() macro and drop overflows_ptr() macro(Kees)
>
> Signed-off-by: Gwan-gyeong Mun <[email protected]>

Acked-by: Kees Cook <[email protected]>

--
Kees Cook

2022-09-18 01:11:41

by kernel test robot

[permalink] [raw]
Subject: Re: [PATCH v10 2/9] overflow: Move and add few utility macros into overflow

Hi Gwan-gyeong,

Thank you for the patch! Perhaps something to improve:

[auto build test WARNING on drm-tip/drm-tip]
[also build test WARNING on linus/master v6.0-rc5]
[cannot apply to drm-intel/for-linux-next kees/for-next/hardening next-20220916]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url: https://github.com/intel-lab-lkp/linux/commits/Gwan-gyeong-Mun/Fixes-integer-overflow-or-integer-truncation-issues-in-page-lookups-ttm-place-configuration-and-scatterlist-creation/20220909-190301
base: git://anongit.freedesktop.org/drm/drm-tip drm-tip
config: i386-randconfig-s002 (https://download.01.org/0day-ci/archive/20220918/[email protected]/config)
compiler: gcc-11 (Debian 11.3.0-5) 11.3.0
reproduce:
# apt-get install sparse
# sparse version: v0.6.4-39-gce1a6720-dirty
# https://github.com/intel-lab-lkp/linux/commit/8d39d691758034d1082773e43b9cb4738b1f4387
git remote add linux-review https://github.com/intel-lab-lkp/linux
git fetch --no-tags linux-review Gwan-gyeong-Mun/Fixes-integer-overflow-or-integer-truncation-issues-in-page-lookups-ttm-place-configuration-and-scatterlist-creation/20220909-190301
git checkout 8d39d691758034d1082773e43b9cb4738b1f4387
# save the config file
mkdir build_dir && cp config build_dir/.config
make W=1 C=1 CF='-fdiagnostic-prefix -D__CHECK_ENDIAN__' O=build_dir ARCH=i386 SHELL=/bin/bash drivers/gpu/drm/i915/

If you fix the issue, kindly add following tag where applicable
Reported-by: kernel test robot <[email protected]>

sparse warnings: (new ones prefixed by >>)
>> drivers/gpu/drm/i915/i915_user_extensions.c:56:21: sparse: sparse: incorrect type in assignment (different address spaces) @@ expected struct i915_user_extension [noderef] __user *ext @@ got void *[noderef] __user @@
drivers/gpu/drm/i915/i915_user_extensions.c:56:21: sparse: expected struct i915_user_extension [noderef] __user *ext
drivers/gpu/drm/i915/i915_user_extensions.c:56:21: sparse: got void *[noderef] __user

vim +56 drivers/gpu/drm/i915/i915_user_extensions.c

15
16 int i915_user_extensions(struct i915_user_extension __user *ext,
17 const i915_user_extension_fn *tbl,
18 unsigned int count,
19 void *data)
20 {
21 unsigned int stackdepth = 512;
22
23 while (ext) {
24 int i, err;
25 u32 name;
26 u64 next;
27
28 if (!stackdepth--) /* recursion vs useful flexibility */
29 return -E2BIG;
30
31 err = check_user_mbz(&ext->flags);
32 if (err)
33 return err;
34
35 for (i = 0; i < ARRAY_SIZE(ext->rsvd); i++) {
36 err = check_user_mbz(&ext->rsvd[i]);
37 if (err)
38 return err;
39 }
40
41 if (get_user(name, &ext->name))
42 return -EFAULT;
43
44 err = -EINVAL;
45 if (name < count) {
46 name = array_index_nospec(name, count);
47 if (tbl[name])
48 err = tbl[name](ext, data);
49 }
50 if (err)
51 return err;
52
53 if (get_user(next, &ext->next_extension))
54 return -EFAULT;
55
> 56 if (check_assign_user_ptr(next, ext))

--
0-DAY CI Kernel Test Service
https://01.org/lkp

2022-09-21 14:34:20

by Gwan-gyeong Mun

[permalink] [raw]
Subject: Re: [PATCH v10 3/9] compiler_types.h: Add assert_type to catch type mis-match while compiling



On 9/13/22 3:01 PM, Kees Cook wrote:
> On Fri, Sep 09, 2022 at 07:59:07PM +0900, Gwan-gyeong Mun wrote:
>> It adds assert_type and assert_typable macros to catch type mis-match while
>> compiling. The existing typecheck() macro outputs build warnings, but the
>> newly added assert_type() macro uses the _Static_assert() keyword (which is
>> introduced in C11) to generate a build break when the types are different
>> and can be used to detect explicit build errors.
>> Unlike the assert_type() macro, assert_typable() macro allows a constant
>> value as the second argument.
>>
>> Suggested-by: Kees Cook <[email protected]>
>> Signed-off-by: Gwan-gyeong Mun <[email protected]>
>> Cc: Thomas Hellström <[email protected]>
>> Cc: Matthew Auld <[email protected]>
>> Cc: Nirmoy Das <[email protected]>
>> Cc: Jani Nikula <[email protected]>
>> Cc: Andi Shyti <[email protected]>
>> Cc: Mauro Carvalho Chehab <[email protected]>
>> Cc: Andrzej Hajda <[email protected]>
>> Cc: Kees Cook <[email protected]>
>> ---
>> include/linux/compiler_types.h | 39 ++++++++++++++++++++++++++++++++++
>> 1 file changed, 39 insertions(+)
>>
>> diff --git a/include/linux/compiler_types.h b/include/linux/compiler_types.h
>> index 4f2a819fd60a..19cc125918bb 100644
>> --- a/include/linux/compiler_types.h
>> +++ b/include/linux/compiler_types.h
>> @@ -294,6 +294,45 @@ struct ftrace_likely_data {
>> /* Are two types/vars the same type (ignoring qualifiers)? */
>> #define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
>>
>> +/**
>> + * assert_type - break compile if the first argument's data type and the second
>> + * argument's data type are not the same
>> + *
>> + * @t1: data type or variable
>> + * @t2: data type or variable
>> + *
>> + * The first and second arguments can be data types or variables or mixed (the
>> + * first argument is the data type and the second argument is variable or vice
>> + * versa). It determines whether the first argument's data type and the second
>> + * argument's data type are the same while compiling, and it breaks compile if
>> + * the two types are not the same.
>> + * See also assert_typable().
>> + */
>> +#define assert_type(t1, t2) _Static_assert(__same_type(t1, t2))
>> +
>> +/**
>> + * assert_typable - break compile if the first argument's data type and the
>> + * second argument's data type are not the same
>> + *
>> + * @t: data type or variable
>> + * @n: data type or variable or constant value
>> + *
>> + * The first and second arguments can be data types or variables or mixed (the
>> + * first argument is the data type and the second argument is variable or vice
>> + * versa). Unlike the assert_type() macro, this macro allows a constant value
>> + * as the second argument. And if the second argument is a constant value, it
>> + * always passes. And it doesn't mean that the types are explicitly the same.
>> + * When a constant value is used as the second argument, if you need an
>> + * overflow check when assigning a constant value to a variable of the type of
>> + * the first argument, you can use the overflows_type() macro. When a constant
>
> I wonder if the overflows_type() check should happen in this test? It
> seems weird that assert_typable(u8, 1024) would pass...
>
Yes, that's right. If a constant is used as an argument here, it seems
necessary to check whether an overflow occurs when the constant value is
assigned to the target type or target variable.

>> + * value is not used as a second argument, it determines whether the first
>> + * argument's data type and the second argument's data type are the same while
>> + * compiling, and it breaks compile if the two types are not the same.
>> + * See also assert_type() and overflows_type().
>> + */
>> +#define assert_typable(t, n) _Static_assert(__builtin_constant_p(n) || \
>> + __same_type(t, typeof(n)))
>
> Totally untested -- I'm not sure if this gets the right semantics for
> constant expressoins, etc...
>
> static_assert(__builtin_choose_expression(__builtin_constant_p(n), \
> overflows_type(n, typeof(t)), \
> __same_type(t, typeof(n))))
>
>
However, if we change the macro in the form below, the "error:
expression in static assertion is not constant" error occurs due to the
restriction [1][2] of _Static_assert() as you mentioned.
( overflows_type() internally uses the __builtin_add_overflow() builtin
function [3], which returns a bool type.)

#define assert_same_typable(t, n) static_assert( \
__builtin_choose_expr(__builtin_constant_p(n), \
overflows_type(n, typeof(t)) == false, \
__same_type(t, typeof(n))))

Can I have your opinion on the new addition of
overflows_type_return_const_expr(), which returns a constant value at
compile time to check whether an overflow occurs when assigning a
constant value to an argument type?
If it is allowable to add the macro, I would try to use the macro that
returns "an integer constant expression" after checking for overflow
between the constant value and the argument type at compile time with
reference to implemented in the previous version. [4] or [5]

#define assert_same_typable(t, n) static_assert( \
__builtin_choose_expr(__builtin_constant_p(n), \
overflows_type_return_const_expr(n,t) == 0, \
__same_type(t, typeof(n))))


option (1): add is_unsigned_type() and overflows_type_return_const_expr()
#define is_unsigned_type(x) (!is_signed_type(x))
#define overflows_type_return_const_expr(x, T) \
(is_unsigned_type(x) ? \
is_unsigned_type(T) ? \
(sizeof(x) > sizeof(T) && (x) >> BITS_PER_TYPE(T)) ? 1 : 0 \
: (sizeof(x) >= sizeof(T) && (x) >> (BITS_PER_TYPE(T) - 1)) ? 1 : 0 \
: is_unsigned_type(T) ? \
((x) < 0) ? 1 : (sizeof(x) > sizeof(T) && (x) >> BITS_PER_TYPE(T)) ? 1
: 0 \
: (sizeof(x) > sizeof(T)) ? \
((x) < 0) ? (((x) * -1) >> BITS_PER_TYPE(T)) ? 1 : 0 \
: ((x) >> BITS_PER_TYPE(T)) ? 1 : 0 \
: 0)


or option (2): modify current __type_half_max(), type_max(), type_min()
and add overflows_type_return_const_expr()

#define __type_half_max(x) (((typeof(x))1) << (BITS_PER_TYPE(x) - 1 -
is_signed_type(x)))
#define type_max(x) ((typeof(x))((__type_half_max(x) - 1) +
__type_half_max(x)))
#define type_min(x) ((typeof(x))((typeof(x))-type_max(x)-(typeof(x))1))
#define overflows_type_return_const_expr(x,T) ( \
is_unsigned_type(x) ? \
x > type_max(T) ? 1 : 0 \
: is_unsigned_type(T) ? \
x < 0 || x > type_max(T) ? 1 : 0 \
: x < type_min(T) || x > type_max(T) ? 1 : 0 )

> Also, can you please add KUnit tests for these new helpers into
> lib/overflow_kunit.c?
>
yes the kunit tests for assert_same_typable() and assert_same_type()
will be added in the case of normal build in the form below so that the
build of other test cases is not interrupted. [6]

And the added overflows_type() and check_assign() and
check_assign_user_ptr() macros use the check_add_overflow() macro, and
this macro is verified with another test case. Is it necessary to add it?
And if it's okay to add the overflows_type_return_const_expr() macro
mentioned above, I'll add the macro in the new version and add a test case.

[1] https://en.cppreference.com/w/c/language/_Static_assert
_Static_assert ( expression , message ) (since C11)

[2] C11 standard (ISO/IEC 9899:2011):
6.7.10 Static assertions

Syntax
1 static_assert-declaration:
_Static_assert ( constant-expression , string-literal ) ;

Constraints
2 The constant expression shall compare unequal to 0.

Semantics
3 The constant expression shall be an integer constant expression. If
the value of the constant expression compares unequal to 0, the
declaration has no effect. Otherwise, the constraint is violated and the
implementation shall produce a diagnostic message that includes the text
of the string literal, except that characters not in the basic source
character set are not required to appear in the message.

[3] https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html
6.56 Built-in Functions to Perform Arithmetic with Overflow Checking
Built-in Function: bool __builtin_add_overflow (type1 a, type2 b,
type3 *res)

[4] https://patchwork.freedesktop.org/patch/494722/?series=104704&rev=6

[5]
https://lore.kernel.org/all/[email protected]/

[6]

/* Arg is: type */
#define TEST_ASSERT_SAME_TYPE(t) do { \
typeof(t) __t1 = type_max(t); \
typeof(t) __t2 = type_min(t); \
assert_same_type(t, t); \
assert_same_type(t, __t1); \
assert_same_type(__t1, t); \
assert_same_type(__t1, __t2); \
} while (0)

/* Arg is: type */
#define TEST_ASSERT_SAME_TYPABLE(t) do { \
typeof(t) __t1 = type_max(t); \
typeof(t) __t2 = type_min(t); \
assert_same_typable(t, __t1); \
assert_same_typable(t, type_max(t)); \
assert_same_typable(t, type_min(t)); \
assert_same_typable(__t1, type_max(t)); \
assert_same_typable(__t1, type_min(t)); \
assert_same_typable(__t1, __t2); \
} while (0)


TEST_ASSERT_SAME_TYPE(u8);
TEST_ASSERT_SAME_TYPE(u16);
TEST_ASSERT_SAME_TYPE(u32);
TEST_ASSERT_SAME_TYPE(u64);
TEST_ASSERT_SAME_TYPE(s8);
TEST_ASSERT_SAME_TYPE(s16);
TEST_ASSERT_SAME_TYPE(s32);
TEST_ASSERT_SAME_TYPE(s64);
TEST_ASSERT_SAME_TYPABLE(u8);
TEST_ASSERT_SAME_TYPABLE(u16);
TEST_ASSERT_SAME_TYPABLE(u32);
TEST_ASSERT_SAME_TYPABLE(u64);
TEST_ASSERT_SAME_TYPABLE(s8);
TEST_ASSERT_SAME_TYPABLE(s16);
TEST_ASSERT_SAME_TYPABLE(s32);
TEST_ASSERT_SAME_TYPABLE(s64);